Skip to content

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

Multichannel MVP: Multicurrency (#6242)

Marcin Gębaladc6e1b5fec97
diff --git a/.github/workflows/pytest.yml b/.github/workflows/pytest.yml
index e5727ec937..6ddc763326 100644
--- a/.github/workflows/pytest.yml
+++ b/.github/workflows/pytest.yml
@@ -2,7 +2,7 @@ name: Pytest
on:
pull_request:
- types: [ opened, synchronize, reopened ]
+ types: [opened, synchronize, reopened]
push:
branches:
- master
@@ -31,68 +31,68 @@ jobs:
--health-retries 5
steps:
- - uses: actions/checkout@v2
+ - uses: actions/checkout@v2
- - name: Setup Python
- uses: actions/setup-python@v2
- with:
- python-version: "3.8"
+ - name: Setup Python
+ uses: actions/setup-python@v2
+ with:
+ python-version: "3.8"
- - name: Install system dependencies
- run: apt-get install -y libpq-dev
+ - name: Install system dependencies
+ run: apt-get install -y libpq-dev
- - uses: actions/cache@v2
- with:
- path: ~/.cache/pip
- key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements_dev.txt') }}
- restore-keys: |
- ${{ runner.os }}-pip-
+ - uses: actions/cache@v2
+ with:
+ path: ~/.cache/pip
+ key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements_dev.txt') }}
+ restore-keys: |
+ ${{ runner.os }}-pip-
- - name: Install dependencies
- run: |
- python -m pip install wheel
- python -m pip install -r requirements_dev.txt
+ - name: Install dependencies
+ run: |
+ python -m pip install wheel
+ python -m pip install -r requirements_dev.txt
- - name: Run tests
- run: |
- pytest \
- --cov \
- --junitxml=junit/test-results.xml \
- --django-db-bench=${{ env.BENCH_PATH }}
+ - name: Run tests
+ run: |
+ pytest \
+ --cov \
+ --junitxml=junit/test-results.xml \
+ --django-db-bench=${{ env.BENCH_PATH }}
- - uses: actions/cache@v2
- with:
- path: ~/.cache/pre-commit
- key: ${{ runner.os }}-pre-commit-${{ hashFiles('**/.pre-commit-config.yaml') }}
- restore-keys: |
- ${{ runner.os }}-pre-commit-
+ - uses: actions/cache@v2
+ with:
+ path: ~/.cache/pre-commit
+ key: ${{ runner.os }}-pre-commit-${{ hashFiles('**/.pre-commit-config.yaml') }}
+ restore-keys: |
+ ${{ runner.os }}-pre-commit-
- # Publish coverage and test results
- - uses: codecov/codecov-action@v1
- - uses: actions/upload-artifact@v1
- with:
- name: pytest-results
- path: junit/test-results.xml
- if: ${{ always() }}
+ # Publish coverage and test results
+ - uses: codecov/codecov-action@v1
+ - uses: actions/upload-artifact@v1
+ with:
+ name: pytest-results
+ path: junit/test-results.xml
+ if: ${{ always() }}
- # Publish detected differences as comment
- - uses: NyanKiyoshi/pytest-django-queries-ci-tools@v1
- with:
- query_raw_dump_path: ${{ env.BENCH_PATH }}
- diff_endpoint: "https://dtab784j47g1o.cloudfront.net/default/saleor-db-queries-bot-diff"
- diff_results_base_url: "https://dtab784j47g1o.cloudfront.net"
- if: ${{ github.event_name == 'pull_request' }}
+ # Publish detected differences as comment
+ - uses: NyanKiyoshi/pytest-django-queries-ci-tools@v1
+ with:
+ query_raw_dump_path: ${{ env.BENCH_PATH }}
+ diff_endpoint: "https://dtab784j47g1o.cloudfront.net/default/saleor-db-queries-bot-diff"
+ diff_results_base_url: "https://dtab784j47g1o.cloudfront.net"
+ if: ${{ github.event_name == 'pull_request' }}
- # Save results for future comparison against pull requests
- - uses: NyanKiyoshi/pytest-django-queries-ci-tools@v1
- with:
- query_raw_dump_path: ${{ env.BENCH_PATH }}
- upload_endpoint: ${{ secrets.QUERIES_UPLOAD_ENDPOINT_URL }}
- upload_secret_key: ${{ secrets.QUERIES_UPLOAD_SECRET }}
- if: ${{ github.event_name == 'push' }}
+ # Save results for future comparison against pull requests
+ - uses: NyanKiyoshi/pytest-django-queries-ci-tools@v1
+ with:
+ query_raw_dump_path: ${{ env.BENCH_PATH }}
+ upload_endpoint: ${{ secrets.QUERIES_UPLOAD_ENDPOINT_URL }}
+ upload_secret_key: ${{ secrets.QUERIES_UPLOAD_SECRET }}
+ if: ${{ github.event_name == 'push' }}
- # Run linters and Django related checks
- - name: Run Linters and Checks
- run: |
- pre-commit run --all
- if: ${{ always() }}
+ # Run linters and Django related checks
+ - name: Run Linters and Checks
+ run: |
+ pre-commit run --all
+ if: ${{ always() }}
diff --git a/conftest.py b/conftest.py
index 9773d9e716..e23e4a8b9f 100644
--- a/conftest.py
+++ b/conftest.py
@@ -2,4 +2,5 @@ pytest_plugins = [
"saleor.tests.fixtures",
"saleor.plugins.tests.fixtures",
"saleor.graphql.tests.fixtures",
+ "saleor.graphql.channel.tests.fixtures",
]
diff --git a/saleor/data_feeds/__init__.py b/saleor/channel/__init__.py
similarity index 100%
rename from saleor/data_feeds/__init__.py
rename to saleor/channel/__init__.py
diff --git a/saleor/channel/error_codes.py b/saleor/channel/error_codes.py
new file mode 100644
index 0000000000..0413aa88d4
--- /dev/null
+++ b/saleor/channel/error_codes.py
@@ -0,0 +1,12 @@
+from enum import Enum
+
+
+class ChannelErrorCode(Enum):
+ ALREADY_EXISTS = "already_exists"
+ GRAPHQL_ERROR = "graphql_error"
+ INVALID = "invalid"
+ NOT_FOUND = "not_found"
+ REQUIRED = "required"
+ UNIQUE = "unique"
+ CHANNEL_TARGET_ID_MUST_BE_DIFFERENT = "channel_target_id_must_be_different"
+ CHANNELS_CURRENCY_MUST_BE_THE_SAME = "channels_currency_must_be_the_same"
diff --git a/saleor/channel/exceptions.py b/saleor/channel/exceptions.py
new file mode 100644
index 0000000000..f58f961b48
--- /dev/null
+++ b/saleor/channel/exceptions.py
@@ -0,0 +1,12 @@
+class ChannelNotDefined(Exception):
+ def __init__(self, msg=None):
+ if msg is None:
+ msg = "More than one channel exists. Specify which channel to use."
+ super().__init__(msg)
+
+
+class NoDefaultChannel(Exception):
+ def __init__(self, msg=None):
+ if msg is None:
+ msg = "A default channel does not exist."
+ super().__init__(msg)
diff --git a/saleor/channel/migrations/0001_initial.py b/saleor/channel/migrations/0001_initial.py
new file mode 100644
index 0000000000..300efb1bff
--- /dev/null
+++ b/saleor/channel/migrations/0001_initial.py
@@ -0,0 +1,101 @@
+# Generated by Django 3.0.6 on 2020-06-16 07:54
+
+from django.conf import settings
+from django.core.management.sql import emit_post_migrate_signal
+from django.db import migrations, models
+
+
+def assing_permissions(apps, schema_editor):
+ # force post signal as permissions are created in post migrate signals
+ # related Django issue https://code.djangoproject.com/ticket/23422
+ emit_post_migrate_signal(2, False, "default")
+ Group = apps.get_model("auth", "Group")
+ Permission = apps.get_model("auth", "Permission")
+ manage_channels = Permission.objects.filter(
+ codename="manage_channels", content_type__app_label="channel"
+ ).first()
+ full_access = Group.objects.filter(name="Full Access").first()
+ if full_access:
+ full_access.permissions.add(manage_channels)
+
+
+def get_default_currency(Checkout, Order, Product, ShippingMethod, Voucher):
+ latest_product = Product.objects.order_by("-pk").first()
+ if latest_product:
+ return latest_product.currency
+ latest_voucher = Voucher.objects.order_by("-pk").first()
+ if latest_voucher:
+ return latest_voucher.currency
+ latest_shipping_method = ShippingMethod.objects.order_by("-pk").first()
+ if latest_shipping_method:
+ return latest_shipping_method.currency
+ latest_order = Order.objects.order_by("-pk").first()
+ if latest_order:
+ return latest_order.currency
+ latest_checkout = Checkout.objects.order_by("-pk").first()
+ if latest_checkout:
+ return latest_checkout.currency
+ return None
+
+
+def create_default_channel(apps, schema_editor):
+ Channel = apps.get_model("channel", "Channel")
+ Checkout = apps.get_model("checkout", "Checkout")
+ Order = apps.get_model("order", "Order")
+ Product = apps.get_model("product", "Product")
+ ShippingMethod = apps.get_model("shipping", "ShippingMethod")
+ Voucher = apps.get_model("discount", "Voucher")
+
+ default_currency = get_default_currency(
+ Checkout, Order, Product, ShippingMethod, Voucher
+ )
+ if default_currency:
+ Channel.objects.create(
+ name="Default channel",
+ slug=settings.DEFAULT_CHANNEL_SLUG,
+ currency_code=default_currency,
+ is_active=True,
+ )
+
+
+class Migration(migrations.Migration):
+
+ initial = True
+
+ dependencies = [
+ ("checkout", "0025_auto_20200221_0257"),
+ ("discount", "0019_auto_20200217_0350"),
+ ("order", "0084_auto_20200522_0522"),
+ ("product", "0118_populate_product_variant_price"),
+ ("shipping", "0018_default_zones_countries"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="Channel",
+ fields=[
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("name", models.CharField(max_length=250)),
+ ("slug", models.SlugField(max_length=255, unique=True)),
+ ("is_active", models.BooleanField(default=False)),
+ (
+ "currency_code",
+ models.CharField(max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH),
+ ),
+ ],
+ options={
+ "ordering": ("slug",),
+ "permissions": (("manage_channels", "Manage channels."),),
+ },
+ ),
+ migrations.RunPython(create_default_channel, migrations.RunPython.noop),
+ migrations.RunPython(assing_permissions, migrations.RunPython.noop),
+ ]
diff --git a/saleor/data_feeds/management/__init__.py b/saleor/channel/migrations/__init__.py
similarity index 100%
rename from saleor/data_feeds/management/__init__.py
rename to saleor/channel/migrations/__init__.py
diff --git a/saleor/channel/models.py b/saleor/channel/models.py
new file mode 100644
index 0000000000..3ce4b25883
--- /dev/null
+++ b/saleor/channel/models.py
@@ -0,0 +1,21 @@
+from django.conf import settings
+from django.db import models
+
+from ..core.permissions import ChannelPermissions
+
+
+class Channel(models.Model):
+ name = models.CharField(max_length=250)
+ is_active = models.BooleanField(default=False)
+ slug = models.SlugField(max_length=255, unique=True)
+ currency_code = models.CharField(max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH)
+
+ class Meta:
+ ordering = ("slug",)
+ app_label = "channel"
+ permissions = (
+ (ChannelPermissions.MANAGE_CHANNELS.codename, "Manage channels.",),
+ )
+
+ def __str__(self):
+ return self.slug
diff --git a/saleor/data_feeds/management/commands/__init__.py b/saleor/channel/tests/__init__.py
similarity index 100%
rename from saleor/data_feeds/management/commands/__init__.py
rename to saleor/channel/tests/__init__.py
diff --git a/saleor/channel/tests/test_utils.py b/saleor/channel/tests/test_utils.py
new file mode 100644
index 0000000000..14c0dc553d
--- /dev/null
+++ b/saleor/channel/tests/test_utils.py
@@ -0,0 +1,24 @@
+import warnings
+
+import pytest
+
+from ..exceptions import ChannelNotDefined, NoDefaultChannel
+from ..utils import DEPRECATION_WARNING_MESSAGE, get_default_channel
+
+
+def test_get_default_channel_without_channels():
+ with pytest.raises(NoDefaultChannel):
+ get_default_channel()
+
+
+def test_get_default_channel_with_one_channels(channel_USD):
+ with warnings.catch_warnings(record=True) as warns:
+ get_default_channel()
+ assert any(
+ [str(warning.message) == DEPRECATION_WARNING_MESSAGE for warning in warns]
+ )
+
+
+def test_get_default_channel_with_many_channels(channel_USD, channel_PLN):
+ with pytest.raises(ChannelNotDefined):
+ get_default_channel()
diff --git a/saleor/channel/utils.py b/saleor/channel/utils.py
new file mode 100644
index 0000000000..ecce4b96a4
--- /dev/null
+++ b/saleor/channel/utils.py
@@ -0,0 +1,38 @@
+import warnings
+
+from .exceptions import ChannelNotDefined, NoDefaultChannel
+from .models import Channel
+
+DEPRECATION_WARNING_MESSAGE = (
+ "Default channel used in a query. Please make sure that channel is explicitly "
+ "provided. This behavior works only when a one channel exists and will be removed "
+ "after 2020-12-31."
+)
+
+
+def get_default_channel() -> Channel:
+ """Return a default channel.
+
+ Returns a channel only when exactly one channel exists in the system. If there are
+ more channels, you need to ensure that the channel is explicitly specified. This
+ function is intended to use throughout the full migration to the multi-channel
+ approach in Saleor and will be removed after 2020-12-31. Since then, the API and
+ all functions will require specifying the channel.
+
+ :raises ChannelNotDefined: When there is more than one channel.
+ :raises NoDefaultChannel: When there are no channels.
+ """
+
+ try:
+ channel = Channel.objects.get()
+ except Channel.MultipleObjectsReturned:
+ channels = list(Channel.objects.filter(is_active=True))
+ if len(channels) == 1:
+ warnings.warn(DEPRECATION_WARNING_MESSAGE)
+ return channels[0]
+ raise ChannelNotDefined()
+ except Channel.DoesNotExist:
+ raise NoDefaultChannel()
+ else:
+ warnings.warn(DEPRECATION_WARNING_MESSAGE)
+ return channel
diff --git a/saleor/checkout/base_calculations.py b/saleor/checkout/base_calculations.py
index 5c9d772974..5dfd535c23 100644
--- a/saleor/checkout/base_calculations.py
+++ b/saleor/checkout/base_calculations.py
@@ -15,16 +15,20 @@ from ..discount import DiscountInfo
if TYPE_CHECKING:
# flake8: noqa
from .models import Checkout, CheckoutLine
+ from ..channel.models import Channel
def base_checkout_shipping_price(
checkout: "Checkout", lines: Iterable["CheckoutLine"]
) -> TaxedMoney:
"""Return checkout shipping price."""
- if not checkout.shipping_method or not checkout.is_shipping_required():
+ shipping_method = checkout.shipping_method
+ if not shipping_method or not checkout.is_shipping_required():
return zero_taxed_money(checkout.currency)
+ shipping_price = shipping_method.channel_listings.get(
+ channel_id=checkout.channel_id,
+ ).get_total()
- shipping_price = checkout.shipping_method.get_total()
return quantize_price(
TaxedMoney(net=shipping_price, gross=shipping_price), shipping_price.currency
)
@@ -47,9 +51,11 @@ def base_checkout_total(
def base_checkout_line_total(
- line: "CheckoutLine", discounts: Optional[Iterable[DiscountInfo]] = None
+ line: "CheckoutLine",
+ channel: "Channel",
+ discounts: Optional[Iterable[DiscountInfo]] = None,
) -> TaxedMoney:
"""Return the total price of this line."""
- amount = line.quantity * line.variant.get_price(discounts or [])
+ amount = line.quantity * line.variant.get_price(channel.slug, discounts or [])
price = quantize_price(amount, amount.currency)
return TaxedMoney(net=price, gross=price)
diff --git a/saleor/checkout/calculations.py b/saleor/checkout/calculations.py
index c3dfad67d4..8048abe5cb 100644
--- a/saleor/checkout/calculations.py
+++ b/saleor/checkout/calculations.py
@@ -9,6 +9,7 @@ if TYPE_CHECKING:
from prices import TaxedMoney
from .models import Checkout, CheckoutLine
+ from ..channel.models import Channel
def checkout_shipping_price(
@@ -74,13 +75,16 @@ def checkout_total(
def checkout_line_total(
- *, line: "CheckoutLine", discounts: Optional[Iterable[DiscountInfo]] = None
+ *,
+ line: "CheckoutLine",
+ discounts: Optional[Iterable[DiscountInfo]] = None,
+ channel: "Channel"
) -> "TaxedMoney":
"""Return the total price of provided line, taxes included.
It takes in account all plugins.
"""
calculated_line_total = get_plugins_manager().calculate_checkout_line_total(
- line, discounts or []
+ line, discounts or [], channel
)
return quantize_price(calculated_line_total, line.checkout.currency)
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.py
index d278323a46..f2d7809dc3 100644
--- a/saleor/checkout/complete_checkout.py
+++ b/saleor/checkout/complete_checkout.py
@@ -11,6 +11,7 @@ from prices import TaxedMoney
from ..account.error_codes import AccountErrorCode
from ..account.models import User
from ..account.utils import store_user_address
+from ..channel.models import Channel
from ..checkout import calculations
from ..checkout.error_codes import CheckoutErrorCode
from ..core.exceptions import InsufficientStock
@@ -123,7 +124,9 @@ def _validate_gift_cards(checkout: Checkout):
raise NotApplicable(msg)
-def _create_line_for_order(checkout_line: "CheckoutLine", discounts) -> OrderLine:
+def _create_line_for_order(
+ checkout_line: "CheckoutLine", discounts, channel: "Channel"
+) -> OrderLine:
"""Create a line for the given order.
:raises InsufficientStock: when there is not enough items in stock for this variant.
@@ -148,7 +151,9 @@ def _create_line_for_order(checkout_line: "CheckoutLine", discounts) -> OrderLin
translated_variant_name = ""
manager = get_plugins_manager()
- total_line_price = manager.calculate_checkout_line_total(checkout_line, discounts)
+ total_line_price = manager.calculate_checkout_line_total(
+ checkout_line, discounts, channel
+ )
unit_price = quantize_price(
total_line_price / checkout_line.quantity, total_line_price.currency
)
@@ -203,8 +208,9 @@ def _prepare_order_data(
}
)
+ channel = checkout.channel
order_data["lines"] = [
- _create_line_for_order(checkout_line=line, discounts=discounts)
+ _create_line_for_order(checkout_line=line, discounts=discounts, channel=channel)
for line in lines
]
@@ -248,7 +254,9 @@ def _create_order(*, checkout: Checkout, order_data: dict, user: User) -> Order:
total_price_left = order_data.pop("total_price_left")
order_lines = order_data.pop("lines")
- order = Order.objects.create(**order_data, checkout_token=checkout.token)
+ order = Order.objects.create(
+ **order_data, checkout_token=checkout.token, channel=checkout.channel
+ )
for line in order_lines:
line.order_id = order.pk
order_lines = OrderLine.objects.bulk_create(order_lines)
@@ -294,7 +302,15 @@ def _prepare_checkout(
clean_checkout_payment(
checkout, lines, discounts, CheckoutErrorCode, last_payment=payment
)
-
+ if not checkout.channel.is_active:
+ raise ValidationError(
+ {
+ "channel": ValidationError(
+ "Cannot complete checkout with inactive channel.",
+ code=CheckoutErrorCode.CHANNEL_INACTIVE.value,
+ )
+ }
+ )
if redirect_url:
try:
validate_storefront_url(redirect_url)
diff --git a/saleor/checkout/error_codes.py b/saleor/checkout/error_codes.py
index 98e13e270f..88edb54539 100644
--- a/saleor/checkout/error_codes.py
+++ b/saleor/checkout/error_codes.py
@@ -22,3 +22,5 @@ class CheckoutErrorCode(Enum):
UNIQUE = "unique"
VOUCHER_NOT_APPLICABLE = "voucher_not_applicable"
ZERO_QUANTITY = "zero_quantity"
+ MISSING_CHANNEL_SLUG = "missing_channel_slug"
+ CHANNEL_INACTIVE = "channel_inactive"
diff --git a/saleor/checkout/migrations/0021_django_price_2.py b/saleor/checkout/migrations/0021_django_price_2.py
index 7e457a432a..eec40314af 100644
--- a/saleor/checkout/migrations/0021_django_price_2.py
+++ b/saleor/checkout/migrations/0021_django_price_2.py
@@ -1,4 +1,6 @@
# Generated by Django 2.2.4 on 2019-08-14 09:13
+import os
+
from django.conf import settings
from django.db import migrations, models
@@ -12,7 +14,7 @@ class Migration(migrations.Migration):
model_name="checkout",
name="currency",
field=models.CharField(
- default=settings.DEFAULT_CURRENCY,
+ default=os.environ.get("DEFAULT_CURRENCY", "USD"),
max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH,
),
)
diff --git a/saleor/checkout/migrations/0030_checkout_channel_listing.py b/saleor/checkout/migrations/0030_checkout_channel_listing.py
new file mode 100644
index 0000000000..c13e0e1cca
--- /dev/null
+++ b/saleor/checkout/migrations/0030_checkout_channel_listing.py
@@ -0,0 +1,53 @@
+# Generated by Django 3.1 on 2020-09-04 10:00
+
+import django.db.models.deletion
+from django.db import migrations, models
+from django.utils.text import slugify
+
+
+def add_channel_slug(apps, schema_editor):
+ Channel = apps.get_model("channel", "Channel")
+ Checkout = apps.get_model("checkout", "Checkout")
+
+ channels_dict = {}
+
+ for checkout in Checkout.objects.iterator():
+ currency = checkout.currency
+ channel = channels_dict.get(currency)
+
+ if not channel:
+ name = f"Channel {currency}"
+ channel, _ = Channel.objects.get_or_create(
+ currency_code=currency, defaults={"name": name, "slug": slugify(name)},
+ )
+ channels_dict[currency] = channel
+
+ checkout.channel = channel
+
+ checkout.save(update_fields=["channel"])
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("channel", "0001_initial"),
+ ("checkout", "0029_auto_20200904_0529"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="checkout",
+ name="channel",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.PROTECT,
+ related_name="checkouts",
+ to="channel.channel",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="checkout",
+ name="currency",
+ field=models.CharField(max_length=3),
+ ),
+ migrations.RunPython(add_channel_slug),
+ ]
diff --git a/saleor/checkout/models.py b/saleor/checkout/models.py
index 2ba4ba665b..96d9b02e5c 100644
--- a/saleor/checkout/models.py
+++ b/saleor/checkout/models.py
@@ -13,6 +13,7 @@ from django_prices.models import MoneyField
from prices import Money
from ..account.models import Address
+from ..channel.models import Channel
from ..core.models import ModelWithMetadata
from ..core.permissions import CheckoutPermissions
from ..core.taxes import zero_money
@@ -64,6 +65,9 @@ class Checkout(ModelWithMetadata):
email = models.EmailField()
token = models.UUIDField(primary_key=True, default=uuid4, editable=False)
quantity = models.PositiveIntegerField(default=0)
+ channel = models.ForeignKey(
+ Channel, related_name="checkouts", on_delete=models.PROTECT,
+ )
billing_address = models.ForeignKey(
Address, related_name="+", editable=False, null=True, on_delete=models.SET_NULL
)
@@ -79,10 +83,7 @@ class Checkout(ModelWithMetadata):
)
note = models.TextField(blank=True, default="")
- currency = models.CharField(
- max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH,
- default=settings.DEFAULT_CURRENCY,
- )
+ currency = models.CharField(max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH,)
country = CountryField(default=get_default_country)
discount_amount = models.DecimalField(
diff --git a/saleor/checkout/tests/test_cart.py b/saleor/checkout/tests/test_cart.py
index 5343ceaf06..958760ae2f 100644
--- a/saleor/checkout/tests/test_cart.py
+++ b/saleor/checkout/tests/test_cart.py
@@ -9,34 +9,16 @@ from ..utils import add_variant_to_checkout
@pytest.fixture()
-def anonymous_checkout(db):
- return Checkout.objects.get_or_create(user=None)[0]
-
-
-def test_get_or_create_user_checkout(
- customer_user, anonymous_checkout, user_checkout, admin_user
-):
- checkout = utils.get_user_checkout(customer_user, auto_create=True)[0]
- assert Checkout.objects.all().count() == 2
- assert checkout == user_checkout
-
- # test against creating new checkouts
- Checkout.objects.create(user=admin_user)
- queryset = Checkout.objects.all()
- checkouts = list(queryset)
- checkout = utils.get_user_checkout(admin_user, auto_create=True)[0]
- assert Checkout.objects.all().count() == 3
- assert checkout in checkouts
- assert checkout.user == admin_user
+def anonymous_checkout(db, channel_USD):
+ return Checkout.objects.get_or_create(user=None, channel=channel_USD)[0]
def test_get_user_checkout(
anonymous_checkout, user_checkout, admin_user, customer_user
):
- checkout, created = utils.get_user_checkout(customer_user)
+ checkout = utils.get_user_checkout(customer_user)
assert Checkout.objects.all().count() == 2
assert checkout == user_checkout
- assert not created
def test_adding_zero_quantity(checkout, product):
@@ -100,9 +82,14 @@ def test_get_prices_of_discounted_specific_product(
voucher.collections.add(collection)
voucher.categories.add(category)
- prices = utils.get_prices_of_discounted_specific_product(checkout, voucher)
+ prices = utils.get_prices_of_discounted_specific_product(
+ list(checkout), voucher, checkout.channel
+ )
- excepted_value = [line.variant.get_price() for item in range(line.quantity)]
+ channel_slug = checkout.channel.slug
+ excepted_value = [
+ line.variant.get_price(channel_slug) for item in range(line.quantity)
+ ]
assert prices == excepted_value
@@ -119,9 +106,14 @@ def test_get_prices_of_discounted_specific_product_only_product(
add_variant_to_checkout(checkout, product2.variants.get(), 1)
voucher.products.add(product)
- prices = utils.get_prices_of_discounted_specific_product(checkout, voucher)
+ prices = utils.get_prices_of_discounted_specific_product(
+ list(checkout), voucher, checkout.channel
+ )
- excepted_value = [line.variant.get_price() for item in range(line.quantity)]
+ channel_slug = checkout.channel.slug
+ excepted_value = [
+ line.variant.get_price(channel_slug) for item in range(line.quantity)
+ ]
assert checkout.lines.count() > 1
assert prices == excepted_value
@@ -143,9 +135,14 @@ def test_get_prices_of_discounted_specific_product_only_collection(
product.collections.add(collection)
voucher.collections.add(collection)
- prices = utils.get_prices_of_discounted_specific_product(checkout, voucher)
+ prices = utils.get_prices_of_discounted_specific_product(
+ list(checkout), voucher, checkout.channel
+ )
- excepted_value = [line.variant.get_price() for item in range(line.quantity)]
+ channel_slug = checkout.channel.slug
+ excepted_value = [
+ line.variant.get_price(channel_slug) for item in range(line.quantity)
+ ]
assert checkout.lines.count() > 1
assert prices == excepted_value
@@ -167,9 +164,14 @@ def test_get_prices_of_discounted_specific_product_only_category(
add_variant_to_checkout(checkout, product2.variants.get(), 1)
voucher.categories.add(category)
- prices = utils.get_prices_of_discounted_specific_product(checkout, voucher)
+ prices = utils.get_prices_of_discounted_specific_product(
+ list(checkout), voucher, checkout.channel
+ )
- excepted_value = [line.variant.get_price() for item in range(line.quantity)]
+ channel_slug = checkout.channel.slug
+ excepted_value = [
+ line.variant.get_price(channel_slug) for item in range(line.quantity)
+ ]
assert checkout.lines.count() > 1
assert prices == excepted_value
@@ -182,9 +184,14 @@ def test_get_prices_of_discounted_specific_product_all_products(
voucher = voucher_specific_product_type
line = checkout.lines.first()
- prices = utils.get_prices_of_discounted_specific_product(checkout, voucher)
+ prices = utils.get_prices_of_discounted_specific_product(
+ list(checkout), voucher, checkout.channel
+ )
- excepted_value = [line.variant.get_price() for item in range(line.quantity)]
+ channel_slug = checkout.channel.slug
+ excepted_value = [
+ line.variant.get_price(channel_slug) for item in range(line.quantity)
+ ]
assert prices == excepted_value
diff --git a/saleor/checkout/tests/test_checkout.py b/saleor/checkout/tests/test_checkout.py
index 0563e7c549..f001e91263 100644
--- a/saleor/checkout/tests/test_checkout.py
+++ b/saleor/checkout/tests/test_checkout.py
@@ -12,7 +12,7 @@ from ...account.models import Address, User
from ...account.utils import store_user_address
from ...core.taxes import zero_money
from ...discount import DiscountValueType, VoucherType
-from ...discount.models import NotApplicable, Voucher
+from ...discount.models import NotApplicable, Voucher, VoucherChannelListing
from ...payment.models import Payment
from ...plugins.manager import get_plugins_manager
from ...shipping.models import ShippingZone
@@ -99,18 +99,21 @@ def test_get_discount_for_checkout_value_voucher(
discount_value_type,
expected_value,
monkeypatch,
+ channel_USD,
):
- voucher = Voucher(
+ voucher = Voucher.objects.create(
code="unique",
type=VoucherType.ENTIRE_ORDER,
discount_value_type=discount_value_type,
- discount_value=discount_value,
- min_spent=(
- Money(min_spent_amount, "USD") if min_spent_amount is not None else None
- ),
min_checkout_items_quantity=min_checkout_items_quantity,
)
- checkout = Mock(spec=Checkout, quantity=total_quantity)
+ VoucherChannelListing.objects.create(
+ voucher=voucher,
+ channel=channel_USD,
+ discount=Money(discount_value, channel_USD.currency_code),
+ min_spent_amount=(min_spent_amount if min_spent_amount is not None else None),
+ )
+ checkout = Mock(spec=Checkout, quantity=total_quantity, channel=channel_USD)
subtotal = TaxedMoney(Money(total, "USD"), Money(total, "USD"))
monkeypatch.setattr(
"saleor.checkout.utils.calculations.checkout_subtotal",
@@ -138,7 +141,7 @@ def test_get_voucher_discount_for_checkout_voucher_validation(
quantity = checkout_with_voucher.quantity
customer_email = checkout_with_voucher.get_customer_email()
mock_validate_voucher.assert_called_once_with(
- voucher, subtotal.gross, quantity, customer_email
+ voucher, subtotal.gross, quantity, customer_email, checkout_with_voucher.channel
)
@@ -161,18 +164,21 @@ def test_get_discount_for_checkout_entire_order_voucher_not_applicable(
min_spent_amount,
min_checkout_items_quantity,
monkeypatch,
+ channel_USD,
):
- voucher = Voucher(
+ voucher = Voucher.objects.create(
code="unique",
type=VoucherType.ENTIRE_ORDER,
discount_value_type=discount_type,
- discount_value=discount_value,
- min_spent=(
- Money(min_spent_amount, "USD") if min_spent_amount is not None else None
- ),
min_checkout_items_quantity=min_checkout_items_quantity,
)
- checkout = Mock(spec=Checkout, quantity=total_quantity)
+ VoucherChannelListing.objects.create(
+ voucher=voucher,
+ channel=channel_USD,
+ discount=Money(discount_value, channel_USD.currency_code),
+ min_spent_amount=(min_spent_amount if min_spent_amount is not None else None),
+ )
+ checkout = Mock(spec=Checkout, quantity=total_quantity, channel=channel_USD)
subtotal = TaxedMoney(Money(total, "USD"), Money(total, "USD"))
monkeypatch.setattr(
"saleor.checkout.utils.calculations.checkout_subtotal",
@@ -203,14 +209,19 @@ def test_get_discount_for_checkout_specific_products_voucher(
discount_type,
apply_once_per_order,
discount_amount,
+ channel_USD,
):
voucher = Voucher.objects.create(
code="unique",
type=VoucherType.SPECIFIC_PRODUCT,
discount_value_type=discount_type,
- discount_value=discount_value,
apply_once_per_order=apply_once_per_order,
)
+ VoucherChannelListing.objects.create(
+ voucher=voucher,
+ channel=channel_USD,
+ discount=Money(discount_value, channel_USD.currency_code),
+ )
for product in product_list:
voucher.products.add(product)
discount = get_voucher_discount_for_checkout(
@@ -238,6 +249,7 @@ def test_get_discount_for_checkout_specific_products_voucher_not_applicable(
discount_type,
min_spent_amount,
min_checkout_items_quantity,
+ channel_USD,
):
discounts = []
monkeypatch.setattr(
@@ -261,17 +273,19 @@ def test_get_discount_for_checkout_specific_products_voucher_not_applicable(
),
)
- voucher = Voucher(
+ voucher = Voucher.objects.create(
code="unique",
type=VoucherType.SPECIFIC_PRODUCT,
discount_value_type=discount_type,
- discount_value=discount_value,
- min_spent=(
- Money(min_spent_amount, "USD") if min_spent_amount is not None else None
- ),
min_checkout_items_quantity=min_checkout_items_quantity,
)
- checkout = Mock(quantity=total_quantity, spec=Checkout)
+ VoucherChannelListing.objects.create(
+ voucher=voucher,
+ channel=channel_USD,
+ discount=Money(discount_value, channel_USD.currency_code),
+ min_spent_amount=(min_spent_amount if min_spent_amount is not None else None),
+ )
+ checkout = Mock(quantity=total_quantity, spec=Checkout, channel=channel_USD)
with pytest.raises(NotApplicable):
get_voucher_discount_for_checkout(voucher, checkout, [], discounts)
@@ -294,6 +308,8 @@ def test_get_discount_for_checkout_shipping_voucher(
countries,
expected_value,
monkeypatch,
+ channel_USD,
+ shipping_method,
):
subtotal = TaxedMoney(Money(100, "USD"), Money(100, "USD"))
monkeypatch.setattr(
@@ -308,22 +324,30 @@ def test_get_discount_for_checkout_shipping_voucher(
checkout = Mock(
spec=Checkout,
is_shipping_required=Mock(return_value=True),
- shipping_method=Mock(get_total=Mock(return_value=shipping_total)),
+ channel_id=channel_USD.id,
+ channel=channel_USD,
+ shipping_method=shipping_method,
get_shipping_price=Mock(return_value=shipping_total),
shipping_address=Mock(country=Country(shipping_country_code)),
)
- voucher = Voucher(
+ voucher = Voucher.objects.create(
code="unique",
type=VoucherType.SHIPPING,
discount_value_type=discount_type,
- discount_value=discount_value,
countries=countries,
)
+ VoucherChannelListing.objects.create(
+ voucher=voucher,
+ channel=channel_USD,
+ discount=Money(discount_value, channel_USD.currency_code),
+ )
discount = get_voucher_discount_for_checkout(voucher, checkout, [])
assert discount == Money(expected_value, "USD")
-def test_get_discount_for_checkout_shipping_voucher_all_countries(monkeypatch):
+def test_get_discount_for_checkout_shipping_voucher_all_countries(
+ monkeypatch, channel_USD, shipping_method
+):
subtotal = TaxedMoney(Money(100, "USD"), Money(100, "USD"))
monkeypatch.setattr(
"saleor.checkout.utils.calculations.checkout_subtotal",
@@ -340,24 +364,33 @@ def test_get_discount_for_checkout_shipping_voucher_all_countries(monkeypatch):
)
checkout = Mock(
spec=Checkout,
+ channel_id=channel_USD.id,
+ channel=channel_USD,
+ shipping_method_id=shipping_method.id,
is_shipping_required=Mock(return_value=True),
shipping_method=Mock(get_total=Mock(return_value=shipping_total)),
shipping_address=Mock(country=Country("PL")),
)
- voucher = Voucher(
+ voucher = Voucher.objects.create(
code="unique",
type=VoucherType.SHIPPING,
discount_value_type=DiscountValueType.PERCENTAGE,
- discount_value=50,
countries=[],
)
+ VoucherChannelListing.objects.create(
+ voucher=voucher,
+ channel=channel_USD,
+ discount=Money(50, channel_USD.currency_code),
+ )
discount = get_voucher_discount_for_checkout(voucher, checkout, [])
assert discount == Money(5, "USD")
-def test_get_discount_for_checkout_shipping_voucher_limited_countries(monkeypatch):
+def test_get_discount_for_checkout_shipping_voucher_limited_countries(
+ monkeypatch, channel_USD
+):
subtotal = TaxedMoney(net=Money(100, "USD"), gross=Money(100, "USD"))
shipping_total = TaxedMoney(net=Money(10, "USD"), gross=Money(10, "USD"))
monkeypatch.setattr(
@@ -366,17 +399,22 @@ def test_get_discount_for_checkout_shipping_voucher_limited_countries(monkeypatc
)
checkout = Mock(
get_subtotal=Mock(return_value=subtotal),
+ channel=channel_USD,
is_shipping_required=Mock(return_value=True),
shipping_method=Mock(get_total=Mock(return_value=shipping_total)),
shipping_address=Mock(country=Country("PL")),
)
- voucher = Voucher(
+ voucher = Voucher.objects.create(
code="unique",
type=VoucherType.SHIPPING,
discount_value_type=DiscountValueType.PERCENTAGE,
- discount_value=50,
countries=["UK", "DE"],
)
+ VoucherChannelListing.objects.create(
+ voucher=voucher,
+ channel=channel_USD,
+ discount=Money(50, channel_USD.currency_code),
+ )
with pytest.raises(NotApplicable):
get_voucher_discount_for_checkout(voucher, checkout, [])
@@ -473,6 +511,7 @@ def test_get_discount_for_checkout_shipping_voucher_not_applicable(
total_quantity,
error_msg,
monkeypatch,
+ channel_USD,
):
monkeypatch.setattr(
"saleor.checkout.utils.calculations.checkout_subtotal",
@@ -487,19 +526,22 @@ def test_get_discount_for_checkout_shipping_voucher_not_applicable(
shipping_method=shipping_method,
quantity=total_quantity,
spec=Checkout,
+ channel=channel_USD,
)
- voucher = Voucher(
+ voucher = Voucher.objects.create(
code="unique",
type=VoucherType.SHIPPING,
discount_value_type=discount_type,
- discount_value=discount_value,
- min_spent=(
- Money(min_spent_amount, "USD") if min_spent_amount is not None else None
- ),
min_checkout_items_quantity=min_checkout_items_quantity,
countries=countries,
)
+ VoucherChannelListing.objects.create(
+ voucher=voucher,
+ channel=channel_USD,
+ discount=Money(discount_value, channel_USD.currency_code),
+ min_spent_amount=(min_spent_amount if min_spent_amount is not None else None),
+ )
with pytest.raises(NotApplicable) as e:
get_voucher_discount_for_checkout(voucher, checkout, [])
assert str(e.value) == error_msg
@@ -530,15 +572,14 @@ def test_remove_voucher_from_checkout(checkout_with_voucher, voucher_translation
assert not checkout.voucher_code
assert not checkout.discount_name
assert not checkout.translated_discount_name
- assert checkout.discount == zero_money()
+ assert checkout.discount == zero_money(checkout.channel.currency_code)
def test_recalculate_checkout_discount(
- checkout_with_voucher, voucher, voucher_translation_fr, settings
+ checkout_with_voucher, voucher, voucher_translation_fr, settings, channel_USD
):
settings.LANGUAGE_CODE = "fr"
- voucher.discount_value = 10
- voucher.save()
+ voucher.channel_listings.filter(channel=channel_USD).update(discount_value=10)
recalculate_checkout_discount(
checkout_with_voucher, list(checkout_with_voucher), None
@@ -561,11 +602,10 @@ def test_recalculate_checkout_discount_with_sale(
def test_recalculate_checkout_discount_voucher_not_applicable(
- checkout_with_voucher, voucher
+ checkout_with_voucher, voucher, channel_USD
):
checkout = checkout_with_voucher
- voucher.min_spent = Money(100, "USD")
- voucher.save(update_fields=["min_spent_amount", "currency"])
+ voucher.channel_listings.filter(channel=channel_USD).update(min_spent_amount=100)
recalculate_checkout_discount(
checkout_with_voucher, list(checkout_with_voucher), None
@@ -573,7 +613,7 @@ def test_recalculate_checkout_discount_voucher_not_applicable(
assert not checkout.voucher_code
assert not checkout.discount_name
- assert checkout.discount == zero_money()
+ assert checkout.discount == zero_money(checkout.channel.currency_code)
def test_recalculate_checkout_discount_expired_voucher(checkout_with_voucher, voucher):
@@ -588,25 +628,27 @@ def test_recalculate_checkout_discount_expired_voucher(checkout_with_voucher, vo
assert not checkout.voucher_code
assert not checkout.discount_name
- assert checkout.discount == zero_money()
+ assert checkout.discount == zero_money(checkout.channel.currency_code)
def test_recalculate_checkout_discount_free_shipping_subtotal_less_than_shipping(
checkout_with_voucher_percentage_and_shipping,
voucher_free_shipping,
shipping_method,
+ channel_USD,
):
checkout = checkout_with_voucher_percentage_and_shipping
lines = list(checkout)
- shipping_method.price = calculations.checkout_subtotal(
+ channel_listing = shipping_method.channel_listings.get(channel_id=channel_USD.id)
+ channel_listing.price = calculations.checkout_subtotal(
checkout=checkout, lines=lines
).gross + Money("10.00", "USD")
- shipping_method.save()
+ channel_listing.save()
recalculate_checkout_discount(checkout, lines, None)
- assert checkout.discount == shipping_method.price
+ assert checkout.discount == channel_listing.price
assert checkout.discount_name == "Free shipping"
assert calculations.checkout_total(
checkout=checkout, lines=lines
@@ -617,18 +659,20 @@ def test_recalculate_checkout_discount_free_shipping_subtotal_bigger_than_shippi
checkout_with_voucher_percentage_and_shipping,
voucher_free_shipping,
shipping_method,
+ channel_USD,
):
checkout = checkout_with_voucher_percentage_and_shipping
lines = list(checkout)
- shipping_method.price = calculations.checkout_subtotal(
+ channel_listing = shipping_method.channel_listings.get(channel=channel_USD)
+ channel_listing.price = calculations.checkout_subtotal(
checkout=checkout, lines=lines
).gross - Money("1.00", "USD")
- shipping_method.save()
+ channel_listing.save()
recalculate_checkout_discount(checkout, lines, None)
- assert checkout.discount == shipping_method.price
+ assert checkout.discount == channel_listing.price
assert checkout.discount_name == "Free shipping"
assert calculations.checkout_total(
checkout=checkout, lines=lines
@@ -644,7 +688,7 @@ def test_recalculate_checkout_discount_free_shipping_for_checkout_without_shippi
assert not checkout.discount_name
assert not checkout.voucher_code
- assert checkout.discount == zero_money()
+ assert checkout.discount == zero_money(checkout.channel.currency_code)
def test_change_address_in_checkout(checkout, address):
diff --git a/saleor/checkout/tests/test_checkout_complete.py b/saleor/checkout/tests/test_checkout_complete.py
index a7c7e152aa..9c1511b6c4 100644
--- a/saleor/checkout/tests/test_checkout_complete.py
+++ b/saleor/checkout/tests/test_checkout_complete.py
@@ -537,7 +537,7 @@ def test_create_order_with_gift_card_partial_use(
)
assert order.gift_cards.count() > 0
- assert order.total == zero_taxed_money()
+ assert order.total == zero_taxed_money(order.currency)
assert gift_card_balance_before_order == expected_old_balance
@@ -579,7 +579,7 @@ def test_create_order_with_many_gift_cards(
gift_card_created_by_staff.refresh_from_db()
gift_card.refresh_from_db()
- zero_price = zero_money()
+ zero_price = zero_money(gift_card.currency)
assert order.gift_cards.count() > 0
assert gift_card_created_by_staff.current_balance == zero_price
assert gift_card.current_balance == zero_price
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index 0e0c43514b..f3b904335d 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -7,6 +7,7 @@ from django.utils import timezone
from prices import Money, MoneyRange, TaxedMoneyRange
from ..account.models import User
+from ..channel.models import Channel
from ..checkout import calculations
from ..checkout.error_codes import CheckoutErrorCode
from ..core.exceptions import ProductNotPublished
@@ -36,22 +37,9 @@ from .models import Checkout, CheckoutLine
def get_user_checkout(
- user: User, checkout_queryset=Checkout.objects.all(), auto_create=False
+ user: User, checkout_queryset=Checkout.objects.all()
) -> Tuple[Optional[Checkout], bool]:
- """Return an active checkout for given user or None if no auto create.
-
- If auto create is enabled, it will retrieve an active checkout or create it
- (safer for concurrency).
- """
- if auto_create:
- return checkout_queryset.get_or_create(
- user=user,
- defaults={
- "shipping_address": user.default_shipping_address,
- "billing_address": user.default_billing_address,
- },
- )
- return checkout_queryset.filter(user=user).first(), False
+ return checkout_queryset.filter(user=user, channel__is_active=True).first()
def update_checkout_quantity(checkout):
@@ -93,7 +81,10 @@ def add_variant_to_checkout(
If `replace` is truthy then any previous quantity is discarded instead
of added to.
"""
- if not variant.product.is_published:
+ product_channel_listing = variant.product.channel_listings.filter(
+ channel_id=checkout.channel_id
+ ).first()
+ if not product_channel_listing or not product_channel_listing.is_published:
raise ProductNotPublished()
new_quantity, line = check_variant_in_stock(
@@ -194,25 +185,28 @@ def _get_shipping_voucher_discount_for_checkout(
shipping_price = calculations.checkout_shipping_price(
checkout=checkout, lines=lines, discounts=discounts
).gross
- return voucher.get_discount_amount_for(shipping_price)
+ return voucher.get_discount_amount_for(shipping_price, checkout.channel)
def _get_products_voucher_discount(
- lines, voucher, discounts: Optional[Iterable[DiscountInfo]] = None
+ lines, voucher, channel, discounts: Optional[Iterable[DiscountInfo]] = None
):
"""Calculate products discount value for a voucher, depending on its type."""
prices = None
if voucher.type == VoucherType.SPECIFIC_PRODUCT:
- prices = get_prices_of_discounted_specific_product(lines, voucher, discounts)
+ prices = get_prices_of_discounted_specific_product(
+ lines, voucher, channel, discounts
+ )
if not prices:
msg = "This offer is only valid for selected items."
raise NotApplicable(msg)
- return get_products_voucher_discount(voucher, prices)
+ return get_products_voucher_discount(voucher, prices, channel)
def get_prices_of_discounted_specific_product(
lines: List[CheckoutLine],
voucher: Voucher,
+ channel: Channel,
discounts: Optional[Iterable[DiscountInfo]] = None,
) -> List[Money]:
"""Get prices of variants belonging to the discounted specific products.
@@ -225,7 +219,7 @@ def get_prices_of_discounted_specific_product(
discounted_lines = get_discounted_lines(lines, voucher)
for line in discounted_lines:
line_total = calculations.checkout_line_total(
- line=line, discounts=discounts or []
+ line=line, discounts=discounts or [], channel=channel
).gross
line_unit_price = quantize_price(
(line_total / line.quantity), line_total.currency
@@ -250,13 +244,15 @@ def get_voucher_discount_for_checkout(
subtotal = calculations.checkout_subtotal(
checkout=checkout, lines=lines, discounts=discounts
).gross
- return voucher.get_discount_amount_for(subtotal)
+ return voucher.get_discount_amount_for(subtotal, checkout.channel)
if voucher.type == VoucherType.SHIPPING:
return _get_shipping_voucher_discount_for_checkout(
voucher, checkout, lines, discounts
)
if voucher.type == VoucherType.SPECIFIC_PRODUCT:
- return _get_products_voucher_discount(lines, voucher, discounts)
+ return _get_products_voucher_discount(
+ lines, voucher, checkout.channel, discounts
+ )
raise NotImplementedError("Unknown discount type")
@@ -266,7 +262,9 @@ def get_voucher_for_checkout(
"""Return voucher with voucher code saved in checkout if active or None."""
if checkout.voucher_code is not None:
if vouchers is None:
- vouchers = Voucher.objects.active(date=timezone.now())
+ vouchers = Voucher.objects.active_in_channel(
+ date=timezone.now(), channel_slug=checkout.channel.slug
+ )
try:
qs = vouchers
if with_lock:
@@ -302,7 +300,7 @@ def recalculate_checkout_discount(
if voucher.type != VoucherType.SHIPPING
else discount
)
- checkout.discount_name = str(voucher)
+ checkout.discount_name = voucher.name
checkout.translated_discount_name = (
voucher.translated.name
if voucher.translated.name != voucher.name
@@ -349,7 +347,9 @@ def add_voucher_code_to_checkout(
Raise InvalidPromoCode() if voucher of given type cannot be applied.
"""
try:
- voucher = Voucher.objects.active(date=timezone.now()).get(code=voucher_code)
+ voucher = Voucher.objects.active_in_channel(
+ date=timezone.now(), channel_slug=checkout.channel.slug
+ ).get(code=voucher_code)
except Voucher.DoesNotExist:
raise InvalidPromoCode()
try:
@@ -433,6 +433,7 @@ def get_valid_shipping_methods_for_checkout(
manager = get_plugins_manager()
return ShippingMethod.objects.applicable_shipping_methods_for_instance(
checkout,
+ channel_id=checkout.channel_id,
price=manager.calculate_checkout_subtotal(checkout, lines, discounts).gross,
country_code=country_code,
)
diff --git a/saleor/core/management/commands/populatedb.py b/saleor/core/management/commands/populatedb.py
index 2ff7d38dfc..d0469167d8 100644
--- a/saleor/core/management/commands/populatedb.py
+++ b/saleor/core/management/commands/populatedb.py
@@ -9,6 +9,7 @@ from django.db import connection
from ....account.utils import create_superuser
from ...utils.random_data import (
add_address_to_admin,
+ create_channels,
create_gift_card,
create_menus,
create_orders,
@@ -20,7 +21,6 @@ from ...utils.random_data import (
create_users,
create_vouchers,
create_warehouses,
- set_homepage_collection,
)
@@ -95,6 +95,8 @@ class Command(BaseCommand):
]
self.make_database_faster()
create_images = not options["withoutimages"]
+ for msg in create_channels():
+ self.stdout.write(msg)
for msg in create_shipping_zones():
self.stdout.write(msg)
create_warehouses()
@@ -111,8 +113,6 @@ class Command(BaseCommand):
self.stdout.write(msg)
for msg in create_orders(20):
self.stdout.write(msg)
- for msg in set_homepage_collection():
- self.stdout.write(msg)
for msg in create_page():
self.stdout.write(msg)
for msg in create_menus():
diff --git a/saleor/core/middleware.py b/saleor/core/middleware.py
index 3bd7f119c5..36fe239aca 100644
--- a/saleor/core/middleware.py
+++ b/saleor/core/middleware.py
@@ -80,8 +80,6 @@ def currency(get_response):
def _currency_middleware(request):
if hasattr(request, "country") and request.country is not None:
request.currency = get_currency_for_country(request.country)
- else:
- request.currency = settings.DEFAULT_CURRENCY
return get_response(request)
return _currency_middleware
diff --git a/saleor/core/permissions.py b/saleor/core/permissions.py
index 3932c32194..609526ec92 100644
--- a/saleor/core/permissions.py
+++ b/saleor/core/permissions.py
@@ -19,6 +19,10 @@ class AppPermission(BasePermissionEnum):
MANAGE_APPS = "app.manage_apps"
+class ChannelPermissions(BasePermissionEnum):
+ MANAGE_CHANNELS = "channel.manage_channels"
+
+
class DiscountPermissions(BasePermissionEnum):
MANAGE_DISCOUNTS = "discount.manage_discounts"
@@ -67,6 +71,7 @@ class SitePermissions(BasePermissionEnum):
PERMISSIONS_ENUMS = [
AccountPermissions,
AppPermission,
+ ChannelPermissions,
DiscountPermissions,
PluginsPermissions,
GiftcardPermissions,
diff --git a/saleor/core/taxes.py b/saleor/core/taxes.py
index 474e545028..713ef8dbf7 100644
--- a/saleor/core/taxes.py
+++ b/saleor/core/taxes.py
@@ -1,7 +1,6 @@
from dataclasses import dataclass
from typing import Union
-from django.conf import settings
from django.contrib.sites.models import Site
from prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange
@@ -10,7 +9,7 @@ class TaxError(Exception):
"""Default tax error."""
-def zero_money(currency: str = settings.DEFAULT_CURRENCY) -> Money:
+def zero_money(currency: str) -> Money:
"""Return a money object set to zero.
This is a function used as a model's default.
@@ -18,7 +17,7 @@ def zero_money(currency: str = settings.DEFAULT_CURRENCY) -> Money:
return Money(0, currency)
-def zero_taxed_money(currency: str = settings.DEFAULT_CURRENCY) -> TaxedMoney:
+def zero_taxed_money(currency: str) -> TaxedMoney:
zero = zero_money(currency)
return TaxedMoney(net=zero, gross=zero)
diff --git a/saleor/core/tests/test_core.py b/saleor/core/tests/test_core.py
index 72b4c88c11..4f75b0b1d8 100644
--- a/saleor/core/tests/test_core.py
+++ b/saleor/core/tests/test_core.py
@@ -11,7 +11,8 @@ from django.test import RequestFactory, override_settings
from ...account.models import Address, User
from ...account.utils import create_superuser
-from ...discount.models import Sale, Voucher
+from ...channel.models import Channel
+from ...discount.models import Sale, SaleChannelListing, Voucher, VoucherChannelListing
from ...giftcard.models import GiftCard
from ...order.models import Order
from ...product.models import ProductImage, ProductType
@@ -112,6 +113,23 @@ def test_create_shipping_zones(db):
assert ShippingZone.objects.all().count() == 5
+def test_create_channels(db):
+ assert Channel.objects.all().count() == 0
+ for _ in random_data.create_channels():
+ pass
+ assert Channel.objects.all().count() == 2
+ assert Channel.objects.get(slug="channel-pln")
+
+
+@override_settings(DEFAULT_CHANNEL_SLUG="test-slug")
+def test_create_channels_with_default_channel_slug(db):
+ assert Channel.objects.all().count() == 0
+ for _ in random_data.create_channels():
+ pass
+ assert Channel.objects.all().count() == 2
+ assert Channel.objects.get(slug="test-slug")
+
+
def test_create_fake_user(db):
assert User.objects.all().count() == 0
random_data.create_fake_user()
@@ -138,6 +156,8 @@ def test_create_fake_order(db, monkeypatch, image, media_root, warehouse):
monkeypatch.setattr(
"saleor.core.utils.random_data.get_image", Mock(return_value=image)
)
+ for _ in random_data.create_channels():
+ pass
for _ in random_data.create_shipping_zones():
pass
for _ in random_data.create_users(3):
@@ -151,16 +171,25 @@ def test_create_fake_order(db, monkeypatch, image, media_root, warehouse):
def test_create_product_sales(db):
how_many = 5
+ channel_count = 0
+ for _ in random_data.create_channels():
+ channel_count += 1
for _ in random_data.create_product_sales(how_many):
pass
- assert Sale.objects.all().count() == 5
+ assert Sale.objects.all().count() == how_many
+ assert SaleChannelListing.objects.all().count() == how_many * channel_count
def test_create_vouchers(db):
+ voucher_count = 3
+ channel_count = 0
+ for _ in random_data.create_channels():
+ channel_count += 1
assert Voucher.objects.all().count() == 0
for _ in random_data.create_vouchers():
pass
- assert Voucher.objects.all().count() == 3
+ assert Voucher.objects.all().count() == voucher_count
+ assert VoucherChannelListing.objects.all().count() == voucher_count * channel_count
def test_create_gift_card(db):
diff --git a/saleor/core/tests/test_postgresql_search.py b/saleor/core/tests/test_postgresql_search.py
index f35ddd3229..2312b0c9f3 100644
--- a/saleor/core/tests/test_postgresql_search.py
+++ b/saleor/core/tests/test_postgresql_search.py
@@ -2,7 +2,7 @@ import pytest
from django.utils.text import slugify
from ...account.models import Address
-from ...product.models import Product
+from ...product.models import Product, ProductChannelListing
from ...search.backends.postgresql import search_storefront
PRODUCTS = [
@@ -13,7 +13,7 @@ PRODUCTS = [
@pytest.fixture
-def named_products(category, product_type):
+def named_products(category, product_type, channel_USD):
def gen_product(name, description):
product = Product.objects.create(
name=name,
@@ -21,7 +21,9 @@ def named_products(category, product_type):
description=description,
product_type=product_type,
category=category,
- is_published=True,
+ )
+ ProductChannelListing.objects.create(
+ product=product, channel=channel_USD, is_published=True,
)
return product
@@ -53,12 +55,6 @@ def test_storefront_product_fuzzy_name_search(named_products, phrase, product_nu
assert named_products[product_num] in results
-def unpublish_product(product):
- prod_to_unpublish = product
- prod_to_unpublish.is_published = False
- prod_to_unpublish.save()
-
-
USERS = [
("Andreas", "Knop", "[email protected]"),
("Euzebiusz", "Ziemniak", "[email protected]"),
diff --git a/saleor/core/utils/__init__.py b/saleor/core/utils/__init__.py
index 66afea4b26..d40b3939c3 100644
--- a/saleor/core/utils/__init__.py
+++ b/saleor/core/utils/__init__.py
@@ -1,4 +1,5 @@
import logging
+import os
import socket
from typing import TYPE_CHECKING, Optional, Type, Union
from urllib.parse import urljoin
@@ -93,7 +94,7 @@ def get_currency_for_country(country):
currencies = get_territory_currencies(country.code)
if currencies:
return currencies[0]
- return settings.DEFAULT_CURRENCY
+ return os.environ.get("DEFAULT_CURRENCY", "USD")
def to_local_currency(price, currency):
diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.py
index 49899dbbbd..b23eff735b 100644
--- a/saleor/core/utils/random_data.py
+++ b/saleor/core/utils/random_data.py
@@ -5,6 +5,7 @@ import random
import unicodedata
import uuid
from collections import defaultdict
+from decimal import Decimal
from typing import Type, Union
from unittest.mock import patch
@@ -23,6 +24,7 @@ from prices import Money, TaxedMoney
from ...account.models import Address, User
from ...account.utils import store_user_address
+from ...channel.models import Channel
from ...checkout import AddressType
from ...core.permissions import (
AccountPermissions,
@@ -34,7 +36,7 @@ from ...core.permissions import (
from ...core.utils import build_absolute_uri
from ...core.weight import zero_weight
from ...discount import DiscountValueType, VoucherType
-from ...discount.models import Sale, Voucher
+from ...discount.models import Sale, SaleChannelListing, Voucher, VoucherChannelListing
from ...discount.utils import fetch_discounts
from ...giftcard.models import GiftCard
from ...menu.models import Menu
@@ -53,19 +55,27 @@ from ...product.models import (
AttributeVariant,
Category,
Collection,
+ CollectionChannelListing,
CollectionProduct,
Product,
+ ProductChannelListing,
ProductImage,
ProductType,
ProductVariant,
+ ProductVariantChannelListing,
)
-from ...product.tasks import update_products_minimal_variant_prices_of_discount_task
+from ...product.tasks import update_products_discounted_prices_of_discount_task
from ...product.thumbnails import (
create_category_background_image_thumbnails,
create_collection_background_image_thumbnails,
create_product_thumbnails,
)
-from ...shipping.models import ShippingMethod, ShippingMethodType, ShippingZone
+from ...shipping.models import (
+ ShippingMethod,
+ ShippingMethodChannelListing,
+ ShippingMethodType,
+ ShippingZone,
+)
from ...warehouse.management import increase_stock
from ...warehouse.models import Stock, Warehouse
@@ -136,7 +146,7 @@ IMAGES_MAPPING = {
CATEGORY_IMAGES = {7: "accessories.jpg", 8: "groceries.jpg", 9: "apparel.jpg"}
-COLLECTION_IMAGES = {1: "summer.jpg", 2: "clothing.jpg"}
+COLLECTION_IMAGES = {1: "summer.jpg", 2: "clothing.jpg", 3: "clothing.jpg"}
def get_weight(weight):
@@ -171,6 +181,18 @@ def create_categories(categories_data, placeholder_dir):
create_category_background_image_thumbnails.delay(pk)
+def create_collection_channel_listings(collection_channel_listings_data):
+ channel_USD = Channel.objects.get(currency_code="USD")
+ channel_PLN = Channel.objects.get(currency_code="PLN")
+ for collection_channel_listing in collection_channel_listings_data:
+ pk = collection_channel_listing["pk"]
+ defaults = collection_channel_listing["fields"]
+ defaults["collection_id"] = defaults.pop("collection")
+ channel = defaults.pop("channel")
+ defaults["channel_id"] = channel_USD.pk if channel == 1 else channel_PLN.pk
+ CollectionChannelListing.objects.update_or_create(pk=pk, defaults=defaults)
+
+
def create_collections(data, placeholder_dir):
placeholder_dir = get_product_list_images_dir(placeholder_dir)
for collection in data:
@@ -227,6 +249,18 @@ def create_products(products_data, placeholder_dir, create_images):
create_product_image(product, placeholder_dir, image_name)
+def create_product_channel_listings(product_channel_listings_data):
+ channel_USD = Channel.objects.get(currency_code="USD")
+ channel_PLN = Channel.objects.get(currency_code="PLN")
+ for product_channel_listing in product_channel_listings_data:
+ pk = product_channel_listing["pk"]
+ defaults = product_channel_listing["fields"]
+ defaults["product_id"] = defaults.pop("product")
+ channel = defaults.pop("channel")
+ defaults["channel_id"] = channel_USD.pk if channel == 1 else channel_PLN.pk
+ ProductChannelListing.objects.update_or_create(pk=pk, defaults=defaults)
+
+
def create_stocks(variant, warehouse_qs=None, **defaults):
if warehouse_qs is None:
warehouse_qs = Warehouse.objects.all()
@@ -259,6 +293,19 @@ def create_product_variants(variants_data):
create_stocks(variant, quantity=quantity)
+def create_product_variant_channel_listings(product_variant_channel_listings_data):
+ channel_USD = Channel.objects.get(currency_code="USD")
+ channel_PLN = Channel.objects.get(currency_code="PLN")
+ for variant_channel_listing in product_variant_channel_listings_data:
+ pk = variant_channel_listing["pk"]
+ defaults = variant_channel_listing["fields"]
+
+ defaults["variant_id"] = defaults.pop("variant")
+ channel = defaults.pop("channel")
+ defaults["channel_id"] = channel_USD.pk if channel == 1 else channel_PLN.pk
+ ProductVariantChannelListing.objects.update_or_create(pk=pk, defaults=defaults)
+
+
def assign_attributes_to_product_types(
association_model: Union[Type[AttributeProduct], Type[AttributeVariant]],
attributes: list,
@@ -328,7 +375,15 @@ def create_products_by_schema(placeholder_dir, create_images):
placeholder_dir=placeholder_dir,
create_images=create_images,
)
+ create_product_channel_listings(
+ product_channel_listings_data=types["product.productchannellisting"],
+ )
create_product_variants(variants_data=types["product.productvariant"])
+ create_product_variant_channel_listings(
+ product_variant_channel_listings_data=types[
+ "product.productvariantchannellisting"
+ ],
+ )
assign_attributes_to_product_types(
AttributeProduct, attributes=types["product.attributeproduct"]
)
@@ -344,6 +399,9 @@ def create_products_by_schema(placeholder_dir, create_images):
create_collections(
data=types["product.collection"], placeholder_dir=placeholder_dir
)
+ create_collection_channel_listings(
+ collection_channel_listings_data=types["product.collectionchannellisting"],
+ )
assign_products_to_collections(associations=types["product.collectionproduct"])
@@ -459,18 +517,22 @@ def create_fake_payment(mock_email_confirmation, order):
def create_order_lines(order, discounts, how_many=10):
+ channel = order.channel
+ available_variant_ids = channel.variant_listings.values_list(
+ "variant_id", flat=True
+ )
variants = (
- ProductVariant.objects.filter()
+ ProductVariant.objects.filter(pk__in=available_variant_ids)
.order_by("?")
.prefetch_related("product__product_type")[:how_many]
)
variants_iter = itertools.cycle(variants)
lines = []
- for dummy in range(how_many):
+ for _ in range(how_many):
variant = next(variants_iter)
product = variant.product
quantity = random.randrange(1, 5)
- unit_price = variant.get_price(discounts)
+ unit_price = variant.get_price(channel.slug, discounts)
unit_price = TaxedMoney(net=unit_price, gross=unit_price)
lines.append(
OrderLine(
@@ -524,6 +586,7 @@ def create_fulfillments(order):
def create_fake_order(discounts, max_order_lines=5):
+ channel = Channel.objects.all().order_by("?").first()
customers = (
User.objects.filter(is_superuser=False)
.exclude(default_billing_address=None)
@@ -547,11 +610,17 @@ def create_fake_order(discounts, max_order_lines=5):
}
manager = get_plugins_manager()
- shipping_method = ShippingMethod.objects.order_by("?").first()
- shipping_price = shipping_method.price
+ shipping_method_chanel_listing = (
+ ShippingMethodChannelListing.objects.filter(channel=channel)
+ .order_by("?")
+ .first()
+ )
+ 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)
order_data.update(
{
+ "channel": channel,
"shipping_method": shipping_method,
"shipping_method_name": shipping_method.name,
"shipping_price": shipping_price,
@@ -559,7 +628,6 @@ def create_fake_order(discounts, max_order_lines=5):
)
order = Order.objects.create(**order_data)
-
lines = create_order_lines(order, discounts, random.randrange(1, max_order_lines))
order.total = sum([line.get_total() for line in lines], shipping_price)
weight = Weight(kg=0)
@@ -575,10 +643,15 @@ def create_fake_order(discounts, max_order_lines=5):
def create_fake_sale():
sale = Sale.objects.create(
- name="Happy %s day!" % fake.word(),
- type=DiscountValueType.PERCENTAGE,
- value=random.choice([10, 20, 30, 40, 50]),
+ name="Happy %s day!" % fake.word(), type=DiscountValueType.PERCENTAGE,
)
+ for channel in Channel.objects.all():
+ SaleChannelListing.objects.create(
+ channel=channel,
+ currency=channel.currency_code,
+ sale=sale,
+ discount_value=random.choice([10, 20, 30, 40, 50]),
+ )
for product in Product.objects.all().order_by("?")[:4]:
sale.products.add(product)
return sale
@@ -651,33 +724,69 @@ def create_orders(how_many=10):
def create_product_sales(how_many=5):
for dummy in range(how_many):
sale = create_fake_sale()
- update_products_minimal_variant_prices_of_discount_task.delay(sale.pk)
+ update_products_discounted_prices_of_discount_task.delay(sale.pk)
yield "Sale: %s" % (sale,)
+def create_channel(channel_name, currency_code, slug=None):
+ if not slug:
+ slug = slugify(channel_name)
+ channel, _ = Channel.objects.get_or_create(
+ slug=slug,
+ defaults={
+ "name": channel_name,
+ "currency_code": currency_code,
+ "is_active": True,
+ },
+ )
+ return f"Channel: {channel}"
+
+
+def create_channels():
+ yield create_channel(
+ channel_name="Channel-USD",
+ currency_code="USD",
+ slug=settings.DEFAULT_CHANNEL_SLUG,
+ )
+ yield create_channel(
+ channel_name="Channel-PLN", currency_code="PLN",
+ )
+
+
def create_shipping_zone(shipping_methods_names, countries, shipping_zone_name):
shipping_zone = ShippingZone.objects.get_or_create(
name=shipping_zone_name, defaults={"countries": countries}
)[0]
- ShippingMethod.objects.bulk_create(
+ shipping_methods = ShippingMethod.objects.bulk_create(
[
ShippingMethod(
name=name,
- price=fake.money(),
shipping_zone=shipping_zone,
type=(
ShippingMethodType.PRICE_BASED
if random.randint(0, 1)
else ShippingMethodType.WEIGHT_BASED
),
- minimum_order_price=Money(0, settings.DEFAULT_CURRENCY),
- maximum_order_price_amount=None,
minimum_order_weight=0,
maximum_order_weight=None,
)
for name in shipping_methods_names
]
)
+ for channel in Channel.objects.all():
+ ShippingMethodChannelListing.objects.bulk_create(
+ [
+ ShippingMethodChannelListing(
+ shipping_method=shipping_method,
+ price_amount=fake.money().amount,
+ minimum_order_price_amount=Decimal(0),
+ maximum_order_price_amount=None,
+ channel=channel,
+ currency=channel.currency_code,
+ )
+ for shipping_method in shipping_methods
+ ]
+ )
return "Shipping Zone: %s" % shipping_zone
@@ -984,15 +1093,21 @@ def create_warehouses():
def create_vouchers():
+ channels = list(Channel.objects.all())
voucher, created = Voucher.objects.get_or_create(
code="FREESHIPPING",
defaults={
"type": VoucherType.SHIPPING,
"name": "Free shipping",
"discount_value_type": DiscountValueType.PERCENTAGE,
- "discount_value": 100,
},
)
+ for channel in channels:
+ VoucherChannelListing.objects.get_or_create(
+ voucher=voucher,
+ channel=channel,
+ defaults={"discount_value": 100, "currency": channel.currency_code},
+ )
if created:
yield "Voucher #%d" % voucher.id
else:
@@ -1004,10 +1119,23 @@ def create_vouchers():
"type": VoucherType.ENTIRE_ORDER,
"name": "Big order discount",
"discount_value_type": DiscountValueType.FIXED,
- "discount_value": 25,
- "min_spent": Money(200, settings.DEFAULT_CURRENCY),
},
)
+ for channel in channels:
+ discount_value = 25
+ min_spent_amount = 200
+ if channel.currency_code == "PLN":
+ min_spent_amount *= 4
+ discount_value *= 4
+ VoucherChannelListing.objects.get_or_create(
+ voucher=voucher,
+ channel=channel,
+ defaults={
+ "discount_value": discount_value,
+ "currency": channel.currency_code,
+ "min_spent_amount": 200,
+ },
+ )
if created:
yield "Voucher #%d" % voucher.id
else:
@@ -1018,9 +1146,14 @@ def create_vouchers():
defaults={
"type": VoucherType.ENTIRE_ORDER,
"discount_value_type": DiscountValueType.PERCENTAGE,
- "discount_value": 5,
},
)
+ for channel in channels:
+ VoucherChannelListing.objects.get_or_create(
+ voucher=voucher,
+ channel=channel,
+ defaults={"discount_value": 5, "currency": channel.currency_code},
+ )
if created:
yield "Voucher #%d" % voucher.id
else:
@@ -1045,15 +1178,6 @@ def create_gift_card():
yield "Gift card already exists"
-def set_homepage_collection():
- homepage_collection = Collection.objects.order_by("?").first()
- site = Site.objects.get_current()
- site_settings = site.settings
- site_settings.homepage_collection = homepage_collection
- site_settings.save()
- yield "Homepage collection assigned"
-
-
def add_address_to_admin(email):
address = create_address()
user = User.objects.get(email=email)
diff --git a/saleor/csv/tests/export/products_data/test_get_products_data.py b/saleor/csv/tests/export/products_data/test_get_products_data.py
index abbfa08337..0f431d76f1 100644
--- a/saleor/csv/tests/export/products_data/test_get_products_data.py
+++ b/saleor/csv/tests/export/products_data/test_get_products_data.py
@@ -1,16 +1,20 @@
from measurement.measures import Weight
+from .....channel.models import Channel
from .....product.models import Attribute, Product, ProductVariant, VariantImage
from .....warehouse.models import Warehouse
-from ....utils.products_data import ProductExportFields, get_products_data
+from ....utils import ProductExportFields
+from ....utils.products_data import get_products_data
from .utils import (
+ add_channel_to_expected_product_data,
+ add_channel_to_expected_variant_data,
add_product_attribute_data_to_expected_data,
add_stocks_to_expected_data,
add_variant_attribute_data_to_expected_data,
)
-def test_get_products_data(product, product_with_image, collection, image):
+def test_get_products_data(product, product_with_image, collection, image, channel_USD):
# given
product.weight = Weight(kg=5)
product.save()
@@ -28,6 +32,7 @@ def test_get_products_data(product, product_with_image, collection, image):
)
warehouse_ids = [str(warehouse.pk) for warehouse in Warehouse.objects.all()]
attribute_ids = [str(attr.pk) for attr in Attribute.objects.all()]
+ channel_ids = [str(channel.pk) for channel in Channel.objects.all()]
variants = []
for variant in product.variants.all():
@@ -46,7 +51,7 @@ def test_get_products_data(product, product_with_image, collection, image):
# when
result_data = get_products_data(
- products, export_fields, attribute_ids, warehouse_ids
+ products, export_fields, attribute_ids, warehouse_ids, channel_ids
)
# then
@@ -55,9 +60,6 @@ def test_get_products_data(product, product_with_image, collection, image):
product_data = {
"id": product.id,
"name": product.name,
- "is_published": product.is_published,
- "available_for_purchase": product.available_for_purchase,
- "visible_in_listings": product.visible_in_listings,
"description": product.description,
"category__slug": product.category.slug,
"product_type__name": product.product_type.name,
@@ -82,13 +84,13 @@ def test_get_products_data(product, product_with_image, collection, image):
product_data = add_product_attribute_data_to_expected_data(
product_data, product, attribute_ids
)
+ product_data = add_channel_to_expected_product_data(
+ product_data, product, channel_ids
+ )
for variant in product.variants.all():
data = {
"variants__sku": variant.sku,
- "variants__currency": variant.currency,
- "variants__price_amount": variant.price_amount,
- "variants__cost_price_amount": variant.cost_price_amount,
"variants__images__image": (
""
if not variant.images.all()
@@ -106,9 +108,9 @@ def test_get_products_data(product, product_with_image, collection, image):
data = add_variant_attribute_data_to_expected_data(
data, variant, attribute_ids
)
+ data = add_channel_to_expected_variant_data(data, variant, channel_ids)
expected_data.append(data)
-
assert result_data == expected_data
@@ -119,9 +121,13 @@ def test_get_products_data_for_specified_attributes(
products = Product.objects.all()
export_fields = {"id", "variants__sku"}
attribute_ids = [str(attr.pk) for attr in Attribute.objects.all()][:1]
+ warehouse_ids = []
+ channel_ids = []
# when
- result_data = get_products_data(products, export_fields, attribute_ids, [])
+ result_data = get_products_data(
+ products, export_fields, attribute_ids, warehouse_ids, channel_ids
+ )
# then
expected_data = []
@@ -155,10 +161,45 @@ def test_get_products_data_for_specified_warehouses(
export_fields = {"id", "variants__sku"}
warehouse_ids = [str(warehouse.pk) for warehouse in Warehouse.objects.all()][:2]
attribute_ids = []
+ channel_ids = []
+
+ # when
+ result_data = get_products_data(
+ products, export_fields, attribute_ids, warehouse_ids, channel_ids
+ )
+
+ # then
+ expected_data = []
+ for product in products.order_by("pk"):
+ product_data = {"id": product.pk}
+
+ for variant in product.variants.all():
+ data = {"variants__sku": variant.sku}
+ data.update(product_data)
+
+ data = add_stocks_to_expected_data(data, variant, warehouse_ids)
+
+ expected_data.append(data)
+ for res in result_data:
+ assert res in expected_data
+
+
+def test_get_products_data_for_product_without_channel(
+ product, product_with_image, variant_with_many_stocks
+):
+ # given
+ product.variants.add(variant_with_many_stocks)
+ product_with_image.channel_listings.all().delete()
+
+ products = Product.objects.all()
+ export_fields = {"id", "variants__sku"}
+ warehouse_ids = []
+ attribute_ids = []
+ channel_ids = []
# when
result_data = get_products_data(
- products, export_fields, attribute_ids, warehouse_ids
+ products, export_fields, attribute_ids, warehouse_ids, channel_ids
)
# then
@@ -178,7 +219,7 @@ def test_get_products_data_for_specified_warehouses(
assert res in expected_data
-def test_get_products_data_for_specified_warehouses_and_attributes(
+def test_get_products_data_for_specified_warehouses_channels_and_attributes(
product,
variant_with_many_stocks,
product_with_image,
@@ -191,10 +232,11 @@ def test_get_products_data_for_specified_warehouses_and_attributes(
export_fields = {"id", "variants__sku"}
warehouse_ids = [str(warehouse.pk) for warehouse in Warehouse.objects.all()]
attribute_ids = [str(attr.pk) for attr in Attribute.objects.all()]
+ channel_ids = [str(channel.pk) for channel in Channel.objects.all()]
# when
result_data = get_products_data(
- products, export_fields, attribute_ids, warehouse_ids
+ products, export_fields, attribute_ids, warehouse_ids, channel_ids
)
# then
@@ -205,6 +247,9 @@ def test_get_products_data_for_specified_warehouses_and_attributes(
product_data = add_product_attribute_data_to_expected_data(
product_data, product, attribute_ids
)
+ product_data = add_channel_to_expected_product_data(
+ product_data, product, channel_ids
+ )
for variant in product.variants.all():
data = {"variants__sku": variant.sku}
@@ -214,6 +259,7 @@ def test_get_products_data_for_specified_warehouses_and_attributes(
data = add_variant_attribute_data_to_expected_data(
data, variant, attribute_ids
)
+ data = add_channel_to_expected_variant_data(data, variant, channel_ids)
expected_data.append(data)
diff --git a/saleor/csv/tests/export/products_data/test_handle_relations_data.py b/saleor/csv/tests/export/products_data/test_handle_relations_data.py
index 13592e1868..c37f8192e5 100644
--- a/saleor/csv/tests/export/products_data/test_handle_relations_data.py
+++ b/saleor/csv/tests/export/products_data/test_handle_relations_data.py
@@ -1,11 +1,11 @@
from unittest.mock import patch
-from .....graphql.csv.enums import ProductFieldEnum
from .....product.models import Attribute, Product, ProductImage, VariantImage
from .....warehouse.models import Warehouse
+from ....utils import ProductExportFields
from ....utils.products_data import (
- ProductExportFields,
add_attribute_info_to_data,
+ add_channel_info_to_data,
add_collection_info_to_data,
add_image_uris_to_data,
add_warehouse_info_to_data,
@@ -14,6 +14,13 @@ from ....utils.products_data import (
prepare_products_relations_data,
prepare_variants_relations_data,
)
+from .utils import (
+ add_channel_to_expected_product_data,
+ add_channel_to_expected_variant_data,
+ add_product_attribute_data_to_expected_data,
+ add_stocks_to_expected_data,
+ add_variant_attribute_data_to_expected_data,
+)
@patch("saleor.csv.utils.products_data.prepare_products_relations_data")
@@ -21,18 +28,27 @@ def test_get_products_relations_data(prepare_products_data_mocked, product_list)
# given
qs = Product.objects.all()
export_fields = {
- "collections__slug" "images__image",
+ "collections__slug",
+ "images__image",
"name",
"description",
}
attribute_ids = []
+ channel_ids = []
# when
- get_products_relations_data(qs, export_fields, attribute_ids)
+ get_products_relations_data(qs, export_fields, attribute_ids, channel_ids)
# then
- prepare_products_data_mocked.called_once_with(
- qs, {"collections__slug", "images__image"}, attribute_ids
+ assert prepare_products_data_mocked.call_count == 1
+ args, kwargs = prepare_products_data_mocked.call_args
+ assert set(args[0].values_list("pk", flat=True)) == set(
+ qs.values_list("pk", flat=True)
+ )
+ assert args[1:] == (
+ {"collections__slug", "images__image"},
+ attribute_ids,
+ channel_ids,
)
@@ -44,9 +60,10 @@ def test_get_products_relations_data_no_relations_fields(
qs = Product.objects.all()
export_fields = {"name", "description"}
attribute_ids = []
+ channel_ids = []
# when
- get_products_relations_data(qs, export_fields, attribute_ids)
+ get_products_relations_data(qs, export_fields, attribute_ids, channel_ids)
# then
prepare_products_data_mocked.assert_not_called()
@@ -60,15 +77,46 @@ def test_get_products_relations_data_attribute_ids(
qs = Product.objects.all()
export_fields = {"name", "description"}
attribute_ids = list(Attribute.objects.values_list("pk", flat=True))
+ channel_ids = []
+
+ # when
+ get_products_relations_data(qs, export_fields, attribute_ids, channel_ids)
+
+ # then
+ # then
+ assert prepare_products_data_mocked.call_count == 1
+ args, kwargs = prepare_products_data_mocked.call_args
+ assert set(args[0].values_list("pk", flat=True)) == set(
+ qs.values_list("pk", flat=True)
+ )
+ assert args[1:] == (set(), attribute_ids, channel_ids)
+
+
+@patch("saleor.csv.utils.products_data.prepare_products_relations_data")
+def test_get_products_relations_data_channel_ids(
+ prepare_products_data_mocked, product_list, channel_USD, channel_PLN
+):
+ # given
+ qs = Product.objects.all()
+ export_fields = {"name", "description"}
+ attribute_ids = []
+ channel_ids = [channel_PLN.pk, channel_USD.pk]
# when
- get_products_relations_data(qs, export_fields, attribute_ids)
+ get_products_relations_data(qs, export_fields, attribute_ids, channel_ids)
# then
- prepare_products_data_mocked.called_once_with(qs, {}, attribute_ids)
+ assert prepare_products_data_mocked.call_count == 1
+ args, kwargs = prepare_products_data_mocked.call_args
+ assert set(args[0].values_list("pk", flat=True)) == set(
+ qs.values_list("pk", flat=True)
+ )
+ assert args[1:] == (set(), attribute_ids, channel_ids)
-def test_prepare_products_relations_data(product_with_image, collection_list):
+def test_prepare_products_relations_data(
+ product_with_image, collection_list, channel_USD, channel_PLN
+):
# given
pk = product_with_image.pk
collection_list[0].products.add(product_with_image)
@@ -81,9 +129,10 @@ def test_prepare_products_relations_data(product_with_image, collection_list):
str(attr.assignment.attribute.pk)
for attr in product_with_image.attributes.all()
]
+ channel_ids = [str(channel_PLN.pk), str(channel_USD.pk)]
# when
- result = prepare_products_relations_data(qs, fields, attribute_ids)
+ result = prepare_products_relations_data(qs, fields, attribute_ids, channel_ids)
# then
collections = ", ".join(
@@ -97,10 +146,12 @@ def test_prepare_products_relations_data(product_with_image, collection_list):
)
expected_result = {pk: {"collections__slug": collections, "images__image": images}}
- assigned_attribute = product_with_image.attributes.first()
- if assigned_attribute:
- header = f"{assigned_attribute.attribute.slug} (product attribute)"
- expected_result[pk][header] = assigned_attribute.values.first().slug
+ expected_result = add_product_attribute_data_to_expected_data(
+ expected_result, product_with_image, attribute_ids, pk
+ )
+ expected_result = add_channel_to_expected_product_data(
+ expected_result, product_with_image, channel_ids, pk
+ )
assert result == expected_result
@@ -115,9 +166,10 @@ def test_prepare_products_relations_data_only_fields(
qs = Product.objects.all()
fields = {"collections__slug"}
attribute_ids = []
+ channel_ids = []
# when
- result = prepare_products_relations_data(qs, fields, attribute_ids)
+ result = prepare_products_relations_data(qs, fields, attribute_ids, channel_ids)
# then
collections = ", ".join(
@@ -141,17 +193,42 @@ def test_prepare_products_relations_data_only_attributes_ids(
str(attr.assignment.attribute.pk)
for attr in product_with_image.attributes.all()
]
+ channel_ids = []
+
+ # when
+ result = prepare_products_relations_data(qs, fields, attribute_ids, channel_ids)
+
+ # then
+ expected_result = {pk: {}}
+
+ expected_result = add_product_attribute_data_to_expected_data(
+ expected_result, product_with_image, attribute_ids, pk
+ )
+
+ assert result == expected_result
+
+
+def test_prepare_products_relations_data_only_channel_ids(
+ product_with_image, collection_list, channel_PLN, channel_USD
+):
+ # given
+ pk = product_with_image.pk
+ collection_list[0].products.add(product_with_image)
+ collection_list[1].products.add(product_with_image)
+ qs = Product.objects.all()
+ fields = {"name"}
+ attribute_ids = []
+ channel_ids = [str(channel_PLN.pk), str(channel_USD.pk)]
# when
- result = prepare_products_relations_data(qs, fields, attribute_ids)
+ result = prepare_products_relations_data(qs, fields, attribute_ids, channel_ids)
# then
expected_result = {pk: {}}
- assigned_attribute = product_with_image.attributes.first()
- if assigned_attribute:
- header = f"{assigned_attribute.attribute.slug} (product attribute)"
- expected_result[pk][header] = assigned_attribute.values.first().slug
+ expected_result = add_channel_to_expected_product_data(
+ expected_result, product_with_image, channel_ids, pk
+ )
assert result == expected_result
@@ -167,13 +244,24 @@ def test_get_variants_relations_data(prepare_variants_data_mocked, product_list)
}
attribute_ids = []
warehouse_ids = []
+ channel_ids = []
# when
- get_variants_relations_data(qs, export_fields, attribute_ids, warehouse_ids)
+ get_variants_relations_data(
+ qs, export_fields, attribute_ids, warehouse_ids, channel_ids
+ )
# then
- prepare_variants_data_mocked.called_once_with(
- qs, {ProductFieldEnum.VARIANT_IMAGES.value}, attribute_ids, warehouse_ids
+ assert prepare_variants_data_mocked.call_count == 1
+ args, kwargs = prepare_variants_data_mocked.call_args
+ assert set(args[0].values_list("pk", flat=True)) == set(
+ qs.values_list("pk", flat=True)
+ )
+ assert args[1:] == (
+ {"variants__images__image"},
+ attribute_ids,
+ warehouse_ids,
+ channel_ids,
)
@@ -186,9 +274,12 @@ def test_get_variants_relations_data_no_relations_fields(
export_fields = {"name", "variants__sku"}
attribute_ids = []
warehouse_ids = []
+ channel_ids = []
# when
- get_variants_relations_data(qs, export_fields, attribute_ids, warehouse_ids)
+ get_variants_relations_data(
+ qs, export_fields, attribute_ids, warehouse_ids, channel_ids
+ )
# then
prepare_variants_data_mocked.assert_not_called()
@@ -203,12 +294,20 @@ def test_get_variants_relations_data_attribute_ids(
export_fields = {"name", "variants__sku"}
attribute_ids = list(Attribute.objects.values_list("pk", flat=True))
warehouse_ids = []
+ channel_ids = []
# when
- get_variants_relations_data(qs, export_fields, attribute_ids, warehouse_ids)
+ get_variants_relations_data(
+ qs, export_fields, attribute_ids, warehouse_ids, channel_ids
+ )
# then
- prepare_variants_data_mocked.called_once_with(qs, {}, attribute_ids, warehouse_ids)
+ assert prepare_variants_data_mocked.call_count == 1
+ args, kwargs = prepare_variants_data_mocked.call_args
+ assert set(args[0].values_list("pk", flat=True)) == set(
+ qs.values_list("pk", flat=True)
+ )
+ assert args[1:] == (set(), attribute_ids, warehouse_ids, channel_ids)
@patch("saleor.csv.utils.products_data.prepare_variants_relations_data")
@@ -220,33 +319,78 @@ def test_get_variants_relations_data_warehouse_ids(
export_fields = {"name", "variants__sku"}
attribute_ids = []
warehouse_ids = list(Warehouse.objects.values_list("pk", flat=True))
+ channel_ids = []
# when
- get_variants_relations_data(qs, export_fields, attribute_ids, warehouse_ids)
+ get_variants_relations_data(
+ qs, export_fields, attribute_ids, warehouse_ids, channel_ids
+ )
# then
- prepare_variants_data_mocked.called_once_with(qs, {}, attribute_ids, warehouse_ids)
+ assert prepare_variants_data_mocked.call_count == 1
+ args, kwargs = prepare_variants_data_mocked.call_args
+ assert set(args[0].values_list("pk", flat=True)) == set(
+ qs.values_list("pk", flat=True)
+ )
+ assert args[1:] == (set(), attribute_ids, warehouse_ids, channel_ids)
@patch("saleor.csv.utils.products_data.prepare_variants_relations_data")
-def test_get_variants_relations_data_attributes_and_warehouses_ids(
- prepare_variants_data_mocked, product_list, warehouses
+def test_get_variants_relations_data_channel_ids(
+ prepare_variants_data_mocked, product_list, channel_USD, channel_PLN
+):
+ # given
+ qs = Product.objects.all()
+ export_fields = {"name", "variants__sku"}
+ attribute_ids = []
+ warehouse_ids = []
+ channel_ids = [channel_PLN.pk, channel_USD.pk]
+
+ # when
+ get_variants_relations_data(
+ qs, export_fields, attribute_ids, warehouse_ids, channel_ids
+ )
+
+ # then
+ assert prepare_variants_data_mocked.call_count == 1
+ args, kwargs = prepare_variants_data_mocked.call_args
+ assert set(args[0].values_list("pk", flat=True)) == set(
+ qs.values_list("pk", flat=True)
+ )
+ assert args[1:] == (set(), attribute_ids, warehouse_ids, channel_ids)
+
+
+@patch("saleor.csv.utils.products_data.prepare_variants_relations_data")
+def test_get_variants_relations_data_attributes_warehouses_and_channels_ids(
+ prepare_variants_data_mocked, product_list, warehouses, channel_PLN, channel_USD
):
# given
qs = Product.objects.all()
export_fields = {"name", "description"}
attribute_ids = list(Attribute.objects.values_list("pk", flat=True))
warehouse_ids = list(Warehouse.objects.values_list("pk", flat=True))
+ channel_ids = [channel_PLN.pk, channel_USD.pk]
# when
- get_variants_relations_data(qs, export_fields, attribute_ids, warehouse_ids)
+ get_variants_relations_data(
+ qs, export_fields, attribute_ids, warehouse_ids, channel_ids
+ )
# then
- prepare_variants_data_mocked.called_once_with(qs, {}, attribute_ids, warehouse_ids)
+ assert prepare_variants_data_mocked.call_count == 1
+ args, kwargs = prepare_variants_data_mocked.call_args
+ assert set(args[0].values_list("pk", flat=True)) == set(
+ qs.values_list("pk", flat=True)
+ )
+ assert args[1:] == (set(), attribute_ids, warehouse_ids, channel_ids)
def test_prepare_variants_relations_data(
- product_with_variant_with_two_attributes, image, media_root
+ product_with_variant_with_two_attributes,
+ image,
+ media_root,
+ channel_PLN,
+ channel_USD,
):
# given
qs = Product.objects.all()
@@ -259,9 +403,12 @@ def test_prepare_variants_relations_data(
fields = {"variants__images__image"}
attribute_ids = [str(attr.pk) for attr in Attribute.objects.all()]
warehouse_ids = [str(w.pk) for w in Warehouse.objects.all()]
+ channel_ids = [str(channel_PLN.pk), str(channel_USD.pk)]
# when
- result = prepare_variants_relations_data(qs, fields, attribute_ids, warehouse_ids)
+ result = prepare_variants_relations_data(
+ qs, fields, attribute_ids, warehouse_ids, channel_ids
+ )
# then
pk = variant.pk
@@ -273,18 +420,16 @@ def test_prepare_variants_relations_data(
)
expected_result = {pk: {"variants__images__image": images}}
- for assigned_attribute in variant.attributes.all():
- header = f"{assigned_attribute.attribute.slug} (variant attribute)"
- if str(assigned_attribute.attribute.pk) in attribute_ids:
- expected_result[pk][header] = assigned_attribute.values.first().slug
+ expected_result = add_variant_attribute_data_to_expected_data(
+ expected_result, variant, attribute_ids, pk
+ )
+ expected_result = add_stocks_to_expected_data(
+ expected_result, variant, warehouse_ids, pk
+ )
- for stock in variant.stocks.all():
- if str(stock.warehouse.pk) in warehouse_ids:
- slug = stock.warehouse.slug
- warehouse_headers = [
- f"{slug} (warehouse quantity)",
- ]
- expected_result[pk][warehouse_headers[0]] = stock.quantity
+ expected_result = add_channel_to_expected_variant_data(
+ expected_result, variant, channel_ids, pk
+ )
assert result == expected_result
@@ -303,9 +448,12 @@ def test_prepare_variants_relations_data_only_fields(
fields = {"variants__images__image"}
attribute_ids = []
warehouse_ids = []
+ channel_ids = []
# when
- result = prepare_variants_relations_data(qs, fields, attribute_ids, warehouse_ids)
+ result = prepare_variants_relations_data(
+ qs, fields, attribute_ids, warehouse_ids, channel_ids
+ )
# then
pk = variant.pk
@@ -334,18 +482,20 @@ def test_prepare_variants_relations_data_attributes_ids(
fields = set()
attribute_ids = [str(attr.pk) for attr in Attribute.objects.all()]
warehouse_ids = []
+ channel_ids = []
# when
- result = prepare_variants_relations_data(qs, fields, attribute_ids, warehouse_ids)
+ result = prepare_variants_relations_data(
+ qs, fields, attribute_ids, warehouse_ids, channel_ids
+ )
# then
pk = variant.pk
expected_result = {pk: {}}
- for assigned_attribute in variant.attributes.all():
- header = f"{assigned_attribute.attribute.slug} (variant attribute)"
- if str(assigned_attribute.attribute.pk) in attribute_ids:
- expected_result[pk][header] = assigned_attribute.values.first().slug
+ expected_result = add_variant_attribute_data_to_expected_data(
+ expected_result, variant, attribute_ids, pk
+ )
assert result == expected_result
@@ -360,22 +510,48 @@ def test_prepare_variants_relations_data_warehouse_ids(
fields = set()
attribute_ids = []
warehouse_ids = [str(w.pk) for w in Warehouse.objects.all()]
+ channel_ids = []
# when
- result = prepare_variants_relations_data(qs, fields, attribute_ids, warehouse_ids)
+ result = prepare_variants_relations_data(
+ qs, fields, attribute_ids, warehouse_ids, channel_ids
+ )
# then
pk = variant.pk
expected_result = {pk: {}}
- for stock in variant.stocks.all():
- if str(stock.warehouse.pk) in warehouse_ids:
- slug = stock.warehouse.slug
- warehouse_headers = [
- f"{slug} (warehouse quantity)",
- ]
- expected_result[pk][warehouse_headers[0]] = stock.quantity
+ expected_result = add_stocks_to_expected_data(
+ expected_result, variant, warehouse_ids, pk
+ )
+
+ assert result == expected_result
+
+
+def test_prepare_variants_relations_data_channel_ids(
+ product_with_single_variant, channel_PLN, channel_USD
+):
+ # given
+ qs = Product.objects.all()
+ variant = product_with_single_variant.variants.first()
+
+ fields = set()
+ attribute_ids = []
+ warehouse_ids = []
+ channel_ids = [str(channel_PLN.pk), str(channel_USD.pk)]
+ # when
+ result = prepare_variants_relations_data(
+ qs, fields, attribute_ids, warehouse_ids, channel_ids
+ )
+
+ # then
+ pk = variant.pk
+ expected_result = {pk: {}}
+
+ expected_result = add_channel_to_expected_variant_data(
+ expected_result, variant, channel_ids, pk
+ )
assert result == expected_result
@@ -581,3 +757,68 @@ def test_add_warehouse_info_to_data_data_no_slug(product):
# then
assert result == input_data
+
+
+def test_add_channel_info_to_data(product):
+ # given
+ pk = product.pk
+ slug = "test_channel"
+ channel_data = {
+ "slug": slug,
+ "currency_code": "USD",
+ "published": True,
+ }
+ input_data = {pk: {}}
+ fields = ["currency_code", "published"]
+
+ # when
+ result = add_channel_info_to_data(product.pk, channel_data, input_data, fields)
+
+ # then
+ assert len(result[pk]) == 2
+ assert (
+ result[pk][f"{slug} (channel currency code)"] == channel_data["currency_code"]
+ )
+ assert result[pk][f"{slug} (channel published)"] == channel_data["published"]
+
+
+def test_add_channel_info_to_data_not_changed(product):
+ # given
+ pk = product.pk
+ slug = "test_channel"
+ channel_data = {
+ "slug": slug,
+ "currency_code": "USD",
+ "published": False,
+ }
+ input_data = {
+ pk: {
+ f"{slug} (channel currency code)": "PLN",
+ f"{slug} (channel published)": True,
+ }
+ }
+ fields = ["currency_code", "published"]
+
+ # when
+ result = add_channel_info_to_data(product.pk, channel_data, input_data, fields)
+
+ # then
+ assert result == input_data
+
+
+def test_add_channel_info_to_data_no_slug(product):
+ # given
+ pk = product.pk
+ channel_data = {
+ "slug": None,
+ "currency_code": None,
+ "published": None,
+ }
+ input_data = {pk: {}}
+ fields = ["currency_code"]
+
+ # when
+ result = add_channel_info_to_data(product.pk, channel_data, input_data, fields)
+
+ # then
+ assert result == input_data
diff --git a/saleor/csv/tests/export/products_data/test_prepare_headers.py b/saleor/csv/tests/export/products_data/test_prepare_headers.py
index 03733a2056..3ac514a3af 100644
--- a/saleor/csv/tests/export/products_data/test_prepare_headers.py
+++ b/saleor/csv/tests/export/products_data/test_prepare_headers.py
@@ -1,121 +1,15 @@
+from .....channel.models import Channel
from .....graphql.csv.enums import ProductFieldEnum
from .....product.models import Attribute
-from ....utils.products_data import (
+from ....utils.product_headers import (
get_attributes_headers,
+ get_channels_headers,
get_export_fields_and_headers_info,
get_product_export_fields_and_headers,
get_warehouses_headers,
)
-def test_get_export_fields_and_headers_fields_with_price():
- # given
- export_info = {
- "fields": [
- ProductFieldEnum.VARIANT_PRICE.value,
- ProductFieldEnum.COLLECTIONS.value,
- ProductFieldEnum.DESCRIPTION.value,
- ],
- "warehoses": [],
- }
-
- # when
- export_fields, file_headers = get_product_export_fields_and_headers(export_info)
-
- # then
- expected_headers = [
- "id",
- "variant price",
- "variant currency",
- "collections",
- "description",
- ]
-
- expected_fields = [
- "id",
- "variants__price_amount",
- "variants__currency",
- "collections__slug",
- "description",
- ]
-
- assert export_fields == expected_fields
- assert file_headers == expected_headers
-
-
-def test_get_export_fields_and_headers_fields_with_cost_price():
- # given
- export_info = {
- "fields": [
- ProductFieldEnum.NAME.value,
- ProductFieldEnum.COST_PRICE.value,
- ProductFieldEnum.COLLECTIONS.value,
- ],
- "warehoses": [],
- }
-
- # when
- export_fields, file_headers = get_product_export_fields_and_headers(export_info)
-
- # then
- expected_headers = [
- "id",
- "name",
- "cost price",
- "variant currency",
- "collections",
- ]
-
- expected_fields = [
- "id",
- "name",
- "variants__cost_price_amount",
- "variants__currency",
- "collections__slug",
- ]
-
- assert export_fields == expected_fields
- assert file_headers == expected_headers
-
-
-def test_get_export_fields_and_headers_fields_with_cost_price_and_price_override():
- # given
- export_info = {
- "fields": [
- ProductFieldEnum.NAME.value,
- ProductFieldEnum.VARIANT_PRICE.value,
- ProductFieldEnum.COST_PRICE.value,
- ProductFieldEnum.COLLECTIONS.value,
- ],
- "warehoses": [],
- }
-
- # when
- export_fields, file_headers = get_product_export_fields_and_headers(export_info)
-
- # then
- expected_headers = [
- "id",
- "name",
- "variant price",
- "variant currency",
- "cost price",
- "collections",
- ]
-
- expected_fields = [
- "id",
- "name",
- "variants__price_amount",
- "variants__currency",
- "variants__cost_price_amount",
- "collections__slug",
- ]
-
- assert export_fields == expected_fields
- assert file_headers == expected_headers
-
-
def test_get_export_fields_and_headers_fields_without_price():
# given
export_info = {
@@ -204,26 +98,64 @@ def test_get_warehouses_headers_lack_of_warehouse_ids():
assert warehouse_headers == []
+def test_get_channels_headers(channel_USD, channel_PLN):
+ # given
+ channel_usd_slug = channel_USD.slug
+ channel_pln_slug = channel_PLN.slug
+
+ channel_ids = [channel_USD.pk, channel_PLN.pk]
+ export_info = {"channels": channel_ids}
+
+ # when
+ channel_headers = get_channels_headers(export_info)
+
+ # then
+ expected_headers = []
+ for channel_slug in [channel_pln_slug, channel_usd_slug]:
+ for field in [
+ "product currency code",
+ "published",
+ "publication date",
+ "searchable",
+ "available for purchase",
+ "price amount",
+ "variant currency code",
+ "variant cost price",
+ ]:
+ expected_headers.append(f"{channel_slug} (channel {field})")
+ assert channel_headers == expected_headers
+
+
+def test_get_channels_headers_lack_of_channel_ids():
+ # given
+ export_info = {}
+
+ # when
+ channel_headers = get_channels_headers(export_info)
+
+ # then
+ assert channel_headers == []
+
+
def test_get_export_fields_and_headers_info(
- warehouses, product_with_multiple_values_attributes
+ warehouses, product_with_multiple_values_attributes, channel_PLN, channel_USD
):
# given
warehouse_ids = [w.pk for w in warehouses]
attribute_ids = [attr.pk for attr in Attribute.objects.all()]
+ channel_ids = [channel_PLN.pk, channel_USD.pk]
export_info = {
"fields": [
- ProductFieldEnum.VARIANT_PRICE.value,
ProductFieldEnum.COLLECTIONS.value,
ProductFieldEnum.DESCRIPTION.value,
],
"warehouses": warehouse_ids,
"attributes": attribute_ids,
+ "channels": channel_ids,
}
expected_file_headers = [
"id",
- "variant price",
- "variant currency",
"collections",
"description",
]
@@ -236,8 +168,6 @@ def test_get_export_fields_and_headers_info(
# then
expected_fields = [
"id",
- "variants__price_amount",
- "variants__currency",
"collections__slug",
"description",
]
@@ -251,12 +181,33 @@ def test_get_export_fields_and_headers_info(
variant_headers.append(f"{attr.slug} (variant attribute)")
warehouse_headers = [f"{w.slug} (warehouse quantity)" for w in warehouses]
+
+ channel_headers = []
+ for channel in Channel.objects.all().order_by("slug"):
+ slug = channel.slug
+ for field in [
+ "product currency code",
+ "published",
+ "publication date",
+ "searchable",
+ "available for purchase",
+ "price amount",
+ "variant currency code",
+ "variant cost price",
+ ]:
+ channel_headers.append(f"{slug} (channel {field})")
+
excepted_headers = (
- expected_fields + product_headers + variant_headers + warehouse_headers
+ expected_fields
+ + product_headers
+ + variant_headers
+ + warehouse_headers
+ + channel_headers
)
- expected_file_headers += product_headers + variant_headers + warehouse_headers
-
+ expected_file_headers += (
+ product_headers + variant_headers + warehouse_headers + channel_headers
+ )
assert expected_file_headers == file_headers
assert set(export_fields) == set(expected_fields)
assert data_headers == excepted_headers
diff --git a/saleor/csv/tests/export/products_data/utils.py b/saleor/csv/tests/export/products_data/utils.py
index c648cd41bc..6e90d68b33 100644
--- a/saleor/csv/tests/export/products_data/utils.py
+++ b/saleor/csv/tests/export/products_data/utils.py
@@ -1,29 +1,79 @@
-def add_product_attribute_data_to_expected_data(data, product, attribute_ids):
+def add_product_attribute_data_to_expected_data(data, product, attribute_ids, pk=None):
for assigned_attribute in product.attributes.all():
if assigned_attribute:
header = f"{assigned_attribute.attribute.slug} (product attribute)"
if str(assigned_attribute.attribute.pk) in attribute_ids:
- data[header] = assigned_attribute.values.first().slug
-
+ if pk:
+ data[pk][header] = assigned_attribute.values.first().slug
+ else:
+ data[header] = assigned_attribute.values.first().slug
return data
-def add_variant_attribute_data_to_expected_data(data, variant, attribute_ids):
+def add_variant_attribute_data_to_expected_data(data, variant, attribute_ids, pk=None):
for assigned_attribute in variant.attributes.all():
header = f"{assigned_attribute.attribute.slug} (variant attribute)"
if str(assigned_attribute.attribute.pk) in attribute_ids:
- data[header] = assigned_attribute.values.first().slug
+ if pk:
+ data[pk][header] = assigned_attribute.values.first().slug
+ else:
+ data[header] = assigned_attribute.values.first().slug
return data
-def add_stocks_to_expected_data(data, variant, warehouse_ids):
+def add_stocks_to_expected_data(data, variant, warehouse_ids, pk=None):
for stock in variant.stocks.all():
if str(stock.warehouse.pk) in warehouse_ids:
slug = stock.warehouse.slug
warehouse_headers = [
f"{slug} (warehouse quantity)",
]
- data[warehouse_headers[0]] = stock.quantity
+ if pk:
+ data[pk][warehouse_headers[0]] = stock.quantity
+ else:
+ data[warehouse_headers[0]] = stock.quantity
+
+ return data
+
+
+def add_channel_to_expected_product_data(data, product, channel_ids, pk=None):
+ for channel_listing in product.channel_listings.all():
+ if str(channel_listing.channel.pk) in channel_ids:
+ channel_slug = channel_listing.channel.slug
+ for lookup, field in [
+ ("currency_code", "product currency code"),
+ ("is_published", "published"),
+ ("publication_date", "publication date"),
+ ("visible_in_listings", "searchable"),
+ ("available_for_purchase", "available for purchase"),
+ ]:
+ header = f"{channel_slug} (channel {field})"
+ if lookup == "currency_code":
+ value = getattr(channel_listing, "currency")
+ else:
+ value = getattr(channel_listing, lookup)
+ if pk:
+ data[pk][header] = value
+ else:
+ data[header] = value
+
+ return data
+
+def add_channel_to_expected_variant_data(data, variant, channel_ids, pk=None):
+ for channel_listing in variant.channel_listings.all():
+ if str(channel_listing.channel.pk) in channel_ids:
+ channel_slug = channel_listing.channel.slug
+ price_header = f"{channel_slug} (channel price amount)"
+ currency_header = f"{channel_slug} (channel variant currency code)"
+ cost_price = f"{channel_slug} (channel variant cost price)"
+ if pk:
+ data[pk][price_header] = channel_listing.price_amount
+ data[pk][currency_header] = channel_listing.currency
+ data[pk][cost_price] = channel_listing.cost_price_amount
+ else:
+ data[price_header] = channel_listing.price_amount
+ data[currency_header] = channel_listing.currency
+ data[cost_price] = channel_listing.cost_price_amount
return data
diff --git a/saleor/csv/tests/export/test_export.py b/saleor/csv/tests/export/test_export.py
index 3b4d01c014..a273cdde0e 100644
--- a/saleor/csv/tests/export/test_export.py
+++ b/saleor/csv/tests/export/test_export.py
@@ -2,6 +2,7 @@ import shutil
from tempfile import NamedTemporaryFile
from unittest.mock import ANY, MagicMock, patch
+import graphene
import openpyxl
import petl as etl
import pytest
@@ -10,7 +11,7 @@ from freezegun import freeze_time
from ....core import JobStatus
from ....graphql.csv.enums import ProductFieldEnum
-from ....product.models import Product
+from ....product.models import Product, ProductChannelListing
from ... import FileTypes
from ...utils.export import (
append_to_file,
@@ -44,6 +45,7 @@ def test_export_products(
"fields": [ProductFieldEnum.NAME.value],
"warehouses": [],
"attributes": [],
+ "channels": [],
}
mock_file = MagicMock(spec=File)
@@ -89,7 +91,7 @@ def test_export_products_ids(
):
# given
pks = [product.pk for product in product_list[:2]]
- export_info = {"fields": [], "warehouses": [], "attributes": []}
+ export_info = {"fields": [], "warehouses": [], "attributes": [], "channels": []}
file_type = FileTypes.CSV
assert user_export_file.status == JobStatus.PENDING
@@ -120,17 +122,19 @@ def test_export_products_ids(
@patch("saleor.csv.utils.export.export_products_in_batches")
@patch("saleor.csv.utils.export.send_email_with_link_to_download_file")
@patch("saleor.csv.utils.export.save_csv_file_in_export_file")
-def test_export_products_filter(
+def test_export_products_filter_is_published(
save_file_mock,
send_email_mock,
export_products_in_batches_mock,
create_file_with_headers_mock,
product_list,
user_export_file,
+ channel_USD,
):
# given
- product_list[0].is_published = False
- product_list[0].save(update_fields=["is_published"])
+ ProductChannelListing.objects.filter(
+ product=product_list[0], channel=channel_USD
+ ).update(is_published=False)
export_info = {"fields": [], "warehouses": [], "attributes": []}
file_type = FileTypes.CSV
@@ -143,16 +147,21 @@ def test_export_products_filter(
# when
export_products(
- user_export_file, {"filter": {"is_published": True}}, export_info, file_type
+ user_export_file,
+ {"filter": {"is_published": True, "channel": channel_USD.slug}},
+ export_info,
+ file_type,
)
# then
create_file_with_headers_mock.assert_called_once_with(["id"], ";", file_type)
assert export_products_in_batches_mock.call_count == 1
- args, kwargs = export_products_in_batches_mock.call_args
+ args, _ = export_products_in_batches_mock.call_args
assert set(args[0].values_list("pk", flat=True)) == set(
- Product.objects.filter(is_published=True).values_list("pk", flat=True)
+ Product.objects.filter(
+ channel_listings__is_published=True, channel_listings__channel=channel_USD
+ ).values_list("pk", flat=True)
)
assert args[1:] == (export_info, {"id"}, ["id"], ";", mock_file, file_type,)
send_email_mock.assert_called_once_with(
@@ -161,6 +170,57 @@ def test_export_products_filter(
save_file_mock.assert_called_once_with(user_export_file, mock_file, ANY)
+@patch("saleor.csv.utils.export.create_file_with_headers")
+@patch("saleor.csv.utils.export.export_products_in_batches")
+@patch("saleor.csv.utils.export.send_email_with_link_to_download_file")
+@patch("saleor.csv.utils.export.save_csv_file_in_export_file")
+def test_export_products_filter_collections(
+ save_file_mock,
+ send_email_mock,
+ export_products_in_batches_mock,
+ create_file_with_headers_mock,
+ product_list,
+ user_export_file,
+ channel_USD,
+ collection,
+):
+ # given
+ collection.products.add(product_list[-1])
+
+ export_info = {"fields": [], "warehouses": [], "attributes": []}
+ file_type = FileTypes.CSV
+
+ assert user_export_file.status == JobStatus.PENDING
+ assert not user_export_file.content_file
+
+ mock_file = MagicMock(spec=File)
+ create_file_with_headers_mock.return_value = mock_file
+
+ # when
+ export_products(
+ user_export_file,
+ {
+ "filter": {
+ "collections": [graphene.Node.to_global_id("Collection", collection.pk)]
+ }
+ },
+ export_info,
+ file_type,
+ )
+
+ # then
+ create_file_with_headers_mock.assert_called_once_with(["id"], ";", file_type)
+
+ assert export_products_in_batches_mock.call_count == 1
+ batch_args, _ = export_products_in_batches_mock.call_args
+ assert set(batch_args[0].values_list("pk", flat=True)) == {product_list[-1].pk}
+ assert batch_args[1:] == (export_info, {"id"}, ["id"], ";", mock_file, file_type)
+ send_email_mock.assert_called_once_with(
+ user_export_file, user_export_file.user.email, "export_products_success"
+ )
+ save_file_mock.assert_called_once_with(user_export_file, mock_file, ANY)
+
+
@patch("saleor.csv.utils.export.create_file_with_headers")
@patch("saleor.csv.utils.export.export_products_in_batches")
@patch("saleor.csv.utils.export.send_email_with_link_to_download_file")
@@ -178,6 +238,7 @@ def test_export_products_by_app(
"fields": [ProductFieldEnum.NAME.value],
"warehouses": [],
"attributes": [],
+ "channels": [],
}
file_type = FileTypes.CSV
@@ -391,6 +452,7 @@ def test_export_products_in_batches_for_csv(
"fields": [ProductFieldEnum.NAME.value, ProductFieldEnum.VARIANT_SKU.value],
"warehouses": [],
"attributes": [],
+ "channels": [],
}
export_fields = ["id", "name", "variants__sku"]
expected_headers = ["id", "name", "variant sku"]
@@ -444,6 +506,7 @@ def test_export_products_in_batches_for_xlsx(
"fields": [ProductFieldEnum.NAME.value, ProductFieldEnum.VARIANT_SKU.value],
"warehouses": [],
"attributes": [],
+ "channels": [],
}
export_fields = ["id", "name", "variants__sku"]
expected_headers = ["id", "name", "variant sku"]
diff --git a/saleor/csv/tests/test_tasks.py b/saleor/csv/tests/test_tasks.py
index 517342bbe0..1cd0831fa8 100644
--- a/saleor/csv/tests/test_tasks.py
+++ b/saleor/csv/tests/test_tasks.py
@@ -22,7 +22,9 @@ def test_export_products_task(export_products_mock, user_export_file):
export_products_task(user_export_file.id, scope, export_info, file_type, delimiter)
# then
- export_products_mock.called_once_with()
+ export_products_mock.assert_called_once_with(
+ user_export_file, scope, export_info, file_type, delimiter
+ )
@patch("saleor.csv.tasks.send_export_failed_info")
@@ -61,7 +63,9 @@ def test_on_task_failure(send_export_failed_info_mock, user_export_file):
"error_type": info_type,
}
- send_export_failed_info_mock.called_once_with(user_export_file, "export_failed")
+ send_export_failed_info_mock.assert_called_once_with(
+ user_export_file, user_export_file.user.email, "export_failed"
+ )
@patch("saleor.csv.tasks.send_export_failed_info")
diff --git a/saleor/csv/utils/__init__.py b/saleor/csv/utils/__init__.py
index e69de29bb2..bf6d22af16 100644
--- a/saleor/csv/utils/__init__.py
+++ b/saleor/csv/utils/__init__.py
@@ -0,0 +1,57 @@
+class ProductExportFields:
+ """Data structure with fields for product export."""
+
+ HEADERS_TO_FIELDS_MAPPING = {
+ "fields": {
+ "id": "id",
+ "name": "name",
+ "description": "description",
+ "category": "category__slug",
+ "product type": "product_type__name",
+ "charge taxes": "charge_taxes",
+ "product weight": "product_weight",
+ "variant sku": "variants__sku",
+ "variant weight": "variant_weight",
+ },
+ "product_many_to_many": {
+ "collections": "collections__slug",
+ "product images": "images__image",
+ },
+ "variant_many_to_many": {"variant images": "variants__images__image"},
+ }
+
+ PRODUCT_ATTRIBUTE_FIELDS = {
+ "value": "attributes__values__slug",
+ "slug": "attributes__assignment__attribute__slug",
+ "attribute_pk": "attributes__assignment__attribute__pk",
+ }
+
+ PRODUCT_CHANNEL_LISTING_FIELDS = {
+ "channel_pk": "channel_listings__channel__pk",
+ "slug": "channel_listings__channel__slug",
+ "product_currency_code": "channel_listings__currency",
+ "published": "channel_listings__is_published",
+ "publication_date": "channel_listings__publication_date",
+ "searchable": "channel_listings__visible_in_listings",
+ "available for purchase": "channel_listings__available_for_purchase",
+ }
+
+ WAREHOUSE_FIELDS = {
+ "slug": "variants__stocks__warehouse__slug",
+ "quantity": "variants__stocks__quantity",
+ "warehouse_pk": "variants__stocks__warehouse__id",
+ }
+
+ VARIANT_ATTRIBUTE_FIELDS = {
+ "value": "variants__attributes__values__slug",
+ "slug": "variants__attributes__assignment__attribute__slug",
+ "attribute_pk": "variants__attributes__assignment__attribute__pk",
+ }
+
+ VARIANT_CHANNEL_LISTING_FIELDS = {
+ "channel_pk": "variants__channel_listings__channel__pk",
+ "slug": "variants__channel_listings__channel__slug",
+ "price_amount": "variants__channel_listings__price_amount",
+ "variant_currency_code": "variants__channel_listings__currency",
+ "variant_cost_price": "variants__channel_listings__cost_price_amount",
+ }
diff --git a/saleor/csv/utils/export.py b/saleor/csv/utils/export.py
index 59b517d105..5918022cf1 100644
--- a/saleor/csv/utils/export.py
+++ b/saleor/csv/utils/export.py
@@ -7,7 +7,8 @@ from django.utils import timezone
from ...product.models import Product
from .. import FileTypes
from ..emails import send_email_with_link_to_download_file
-from .products_data import get_export_fields_and_headers_info, get_products_data
+from .product_headers import get_export_fields_and_headers_info
+from .products_data import get_products_data
if TYPE_CHECKING:
# flake8: noqa
@@ -106,6 +107,7 @@ def export_products_in_batches(
):
warehouses = export_info.get("warehouses")
attributes = export_info.get("attributes")
+ channels = export_info.get("channels")
for batch_pks in queryset_in_batches(queryset):
product_batch = Product.objects.filter(pk__in=batch_pks).prefetch_related(
@@ -118,7 +120,7 @@ def export_products_in_batches(
)
export_data = get_products_data(
- product_batch, export_fields, attributes, warehouses
+ product_batch, export_fields, attributes, warehouses, channels
)
append_to_file(export_data, headers, temporary_file, file_type, delimiter)
diff --git a/saleor/csv/utils/product_headers.py b/saleor/csv/utils/product_headers.py
new file mode 100644
index 0000000000..cbe1886135
--- /dev/null
+++ b/saleor/csv/utils/product_headers.py
@@ -0,0 +1,148 @@
+from collections import ChainMap
+from typing import Dict, List, Tuple
+
+from django.db.models import Value as V
+from django.db.models.functions import Concat
+
+from ...channel.models import Channel
+from ...product.models import Attribute
+from ...warehouse.models import Warehouse
+from . import ProductExportFields
+
+
+def get_export_fields_and_headers_info(
+ export_info: Dict[str, list]
+) -> Tuple[List[str], List[str], List[str]]:
+ """Get export fields, all headers and headers mapping.
+
+ Based on export_info returns exported fields, fields to headers mapping and
+ all headers.
+ Headers contains product, variant, attribute and warehouse headers.
+ """
+ export_fields, file_headers = get_product_export_fields_and_headers(export_info)
+ attributes_headers = get_attributes_headers(export_info)
+ warehouses_headers = get_warehouses_headers(export_info)
+ channels_headers = get_channels_headers(export_info)
+
+ data_headers = (
+ export_fields + attributes_headers + warehouses_headers + channels_headers
+ )
+ file_headers += attributes_headers + warehouses_headers + channels_headers
+ return export_fields, file_headers, data_headers
+
+
+def get_product_export_fields_and_headers(
+ export_info: Dict[str, list]
+) -> Tuple[List[str], List[str]]:
+ """Get export fields from export info and prepare headers mapping.
+
+ Based on given fields headers from export info, export fields set and
+ headers mapping is prepared.
+ """
+ export_fields = ["id"]
+ file_headers = ["id"]
+
+ fields = export_info.get("fields")
+ if not fields:
+ return export_fields, file_headers
+
+ fields_mapping = dict(
+ ChainMap(
+ *reversed(
+ ProductExportFields.HEADERS_TO_FIELDS_MAPPING.values()
+ ) # type: ignore
+ )
+ )
+
+ for field in fields:
+ lookup_field = fields_mapping[field]
+ export_fields.append(lookup_field)
+ file_headers.append(field)
+
+ return export_fields, file_headers
+
+
+def get_attributes_headers(export_info: Dict[str, list]) -> List[str]:
+ """Get headers for exported attributes.
+
+ Headers are build from slug and contains information if it's a product or variant
+ attribute. Respectively for product: "slug-value (product attribute)"
+ and for variant: "slug-value (variant attribute)".
+ """
+
+ attribute_ids = export_info.get("attributes")
+ if not attribute_ids:
+ return []
+
+ attributes = Attribute.objects.filter(pk__in=attribute_ids).order_by("slug")
+
+ products_headers = (
+ attributes.filter(product_types__isnull=False)
+ .annotate(header=Concat("slug", V(" (product attribute)")))
+ .values_list("header", flat=True)
+ )
+
+ variant_headers = (
+ attributes.filter(product_variant_types__isnull=False)
+ .annotate(header=Concat("slug", V(" (variant attribute)")))
+ .values_list("header", flat=True)
+ )
+
+ return list(products_headers) + list(variant_headers)
+
+
+def get_warehouses_headers(export_info: Dict[str, list]) -> List[str]:
+ """Get headers for exported warehouses.
+
+ Headers are build from slug. Example: "slug-value (warehouse quantity)"
+ """
+ warehouse_ids = export_info.get("warehouses")
+ if not warehouse_ids:
+ return []
+
+ warehouses_headers = (
+ Warehouse.objects.filter(pk__in=warehouse_ids)
+ .order_by("slug")
+ .annotate(header=Concat("slug", V(" (warehouse quantity)")))
+ .values_list("header", flat=True)
+ )
+
+ return list(warehouses_headers)
+
+
+def get_channels_headers(export_info: Dict[str, list]) -> List[str]:
+ """Get headers for exported channels.
+
+ Headers are build from slug and exported field.
+
+ Example:
+ - currency code data header: "slug-value (channel currency code)"
+ - published data header: "slug-value (channel visible)"
+ - publication date data header: "slug-value (channel publication date)"
+
+ """
+ channel_ids = export_info.get("channels")
+ if not channel_ids:
+ return []
+
+ channels_slugs = (
+ Channel.objects.filter(pk__in=channel_ids)
+ .order_by("slug")
+ .values_list("slug", flat=True)
+ )
+
+ fields = [
+ *ProductExportFields.PRODUCT_CHANNEL_LISTING_FIELDS.keys(),
+ *ProductExportFields.VARIANT_CHANNEL_LISTING_FIELDS.keys(),
+ ]
+ channels_headers = []
+ for slug in channels_slugs:
+ channels_headers.extend(
+ [
+ f"{slug} (channel {field.replace('_', ' ')})"
+ for field in fields
+ if field not in ["slug", "channel_pk"]
+ ]
+ )
+
+ return list(channels_headers)
diff --git a/saleor/csv/utils/products_data.py b/saleor/csv/utils/products_data.py
index 1848add098..73f95e8ec8 100644
--- a/saleor/csv/utils/products_data.py
+++ b/saleor/csv/utils/products_data.py
@@ -1,171 +1,25 @@
import os
-from collections import ChainMap, defaultdict
-from typing import TYPE_CHECKING, Dict, List, Optional, Set, Tuple, Union
+from collections import defaultdict
+from typing import TYPE_CHECKING, Dict, List, Optional, Set, Union
from django.conf import settings
from django.db.models import Case, CharField, Value as V, When
from django.db.models.functions import Concat
from ...core.utils import build_absolute_uri
-from ...product.models import Attribute
-from ...warehouse.models import Warehouse
+from . import ProductExportFields
if TYPE_CHECKING:
# flake8: noqa
from django.db.models import QuerySet
-class ProductExportFields:
- """Data structure with fields for product export."""
-
- HEADERS_TO_FIELDS_MAPPING = {
- "fields": {
- "id": "id",
- "name": "name",
- "description": "description",
- "visible": "is_published",
- "available for purchase": "available_for_purchase",
- "searchable": "visible_in_listings",
- "category": "category__slug",
- "product type": "product_type__name",
- "charge taxes": "charge_taxes",
- "product weight": "product_weight",
- "variant sku": "variants__sku",
- "variant weight": "variant_weight",
- "cost price": "variants__cost_price_amount",
- "variant price": "variants__price_amount",
- "variant currency": "variants__currency",
- },
- "product_many_to_many": {
- "collections": "collections__slug",
- "product images": "images__image",
- },
- "variant_many_to_many": {"variant images": "variants__images__image",},
- }
-
- PRODUCT_ATTRIBUTE_FIELDS = {
- "value": "attributes__values__slug",
- "slug": "attributes__assignment__attribute__slug",
- "attribute_pk": "attributes__assignment__attribute__pk",
- }
-
- WAREHOUSE_FIELDS = {
- "slug": "variants__stocks__warehouse__slug",
- "quantity": "variants__stocks__quantity",
- "warehouse_pk": "variants__stocks__warehouse__id",
- }
-
- VARIANT_ATTRIBUTE_FIELDS = {
- "value": "variants__attributes__values__slug",
- "slug": "variants__attributes__assignment__attribute__slug",
- "attribute_pk": "variants__attributes__assignment__attribute__pk",
- }
-
-
-def get_export_fields_and_headers_info(
- export_info: Dict[str, list]
-) -> Tuple[List[str], List[str], List[str]]:
- """Get export fields, all headers and headers mapping.
-
- Based on export_info returns exported fields, fields to headers mapping and
- all headers.
- Headers contains product, variant, attribute and warehouse headers.
- """
- export_fields, file_headers = get_product_export_fields_and_headers(export_info)
- attributes_headers = get_attributes_headers(export_info)
- warehouses_headers = get_warehouses_headers(export_info)
-
- data_headers = export_fields + attributes_headers + warehouses_headers
- file_headers += attributes_headers + warehouses_headers
- return export_fields, file_headers, data_headers
-
-
-def get_product_export_fields_and_headers(
- export_info: Dict[str, list]
-) -> Tuple[List[str], List[str]]:
- """Get export fields from export info and prepare headers mapping.
-
- Based on given fields headers from export info, export fields set and
- headers mapping is prepared.
- """
- export_fields = ["id"]
- file_headers = ["id"]
-
- fields = export_info.get("fields")
- if not fields:
- return export_fields, file_headers
-
- fields_mapping = dict(
- ChainMap(*reversed(ProductExportFields.HEADERS_TO_FIELDS_MAPPING.values())) # type: ignore
- )
-
- for field in fields:
- lookup_field = fields_mapping[field]
- export_fields.append(lookup_field)
- file_headers.append(field)
- # if price is exported, currency is needed too
- if field == "variant price" or field == "cost price":
- lookup_field = fields_mapping["variant currency"]
- if lookup_field not in export_fields:
- export_fields.append(lookup_field)
- file_headers.append("variant currency")
-
- return export_fields, file_headers
-
-
-def get_attributes_headers(export_info: Dict[str, list]) -> List[str]:
- """Get headers for exported attributes.
-
- Headers are build from slug and contains information if it's a product or variant
- attribute. Respectively for product: "slug-value (product attribute)"
- and for variant: "slug-value (variant attribute)".
- """
-
- attribute_ids = export_info.get("attributes")
- if not attribute_ids:
- return []
-
- attributes = Attribute.objects.filter(pk__in=attribute_ids).order_by("slug")
-
- products_headers = (
- attributes.filter(product_types__isnull=False)
- .annotate(header=Concat("slug", V(" (product attribute)")))
- .values_list("header", flat=True)
- )
-
- variant_headers = (
- attributes.filter(product_variant_types__isnull=False)
- .annotate(header=Concat("slug", V(" (variant attribute)")))
- .values_list("header", flat=True)
- )
-
- return list(products_headers) + list(variant_headers)
-
-
-def get_warehouses_headers(export_info: Dict[str, list]) -> List[str]:
- """Get headers for exported warehouses.
-
- Headers are build from slug. Example: "slug-value (warehouse quantity)"
- """
- warehouse_ids = export_info.get("warehouses")
- if not warehouse_ids:
- return []
-
- warehouses_headers = (
- Warehouse.objects.filter(pk__in=warehouse_ids)
- .order_by("slug")
- .annotate(header=Concat("slug", V(" (warehouse quantity)")))
- .values_list("header", flat=True)
- )
-
- return list(warehouses_headers)
-
-
def get_products_data(
queryset: "QuerySet",
export_fields: Set[str],
attribute_ids: Optional[List[int]],
warehouse_ids: Optional[List[int]],
+ channel_ids: Optional[List[int]],
) -> List[Dict[str, Union[str, bool]]]:
"""Create data list of products and their variants with fields values.
@@ -203,11 +57,11 @@ def get_products_data(
)
products_relations_data = get_products_relations_data(
- queryset, export_fields, attribute_ids
+ queryset, export_fields, attribute_ids, channel_ids
)
variants_relations_data = get_variants_relations_data(
- queryset, export_fields, attribute_ids, warehouse_ids
+ queryset, export_fields, attribute_ids, warehouse_ids, channel_ids
)
for product_data in products_data:
@@ -227,7 +81,10 @@ def get_products_data(
def get_products_relations_data(
- queryset: "QuerySet", export_fields: Set[str], attribute_ids: Optional[List[int]]
+ queryset: "QuerySet",
+ export_fields: Set[str],
+ attribute_ids: Optional[List[int]],
+ channel_ids: Optional[List[int]],
) -> Dict[int, Dict[str, str]]:
"""Get data about product relations fields.
@@ -239,30 +96,39 @@ def get_products_relations_data(
ProductExportFields.HEADERS_TO_FIELDS_MAPPING["product_many_to_many"].values()
)
relations_fields = export_fields & many_to_many_fields
- if relations_fields or attribute_ids:
+ if relations_fields or attribute_ids or channel_ids:
return prepare_products_relations_data(
- queryset, relations_fields, attribute_ids
+ queryset, relations_fields, attribute_ids, channel_ids
)
return {}
def prepare_products_relations_data(
- queryset: "QuerySet", fields: Set[str], attribute_ids: Optional[List[int]]
+ queryset: "QuerySet",
+ fields: Set[str],
+ attribute_ids: Optional[List[int]],
+ channel_ids: Optional[List[int]],
) -> Dict[int, Dict[str, str]]:
"""Prepare data about products relation fields for given queryset.
It return dict where key is a product pk, value is a dict with relation fields data.
"""
attribute_fields = ProductExportFields.PRODUCT_ATTRIBUTE_FIELDS
+ channel_fields = ProductExportFields.PRODUCT_CHANNEL_LISTING_FIELDS.copy()
result_data: Dict[int, dict] = defaultdict(dict)
fields.add("pk")
if attribute_ids:
- fields.update(ProductExportFields.PRODUCT_ATTRIBUTE_FIELDS.values())
+ fields.update(attribute_fields.values())
+ if channel_ids:
+ fields.update(channel_fields.values())
relations_data = queryset.values(*fields)
+ channel_pk_lookup = channel_fields.pop("channel_pk")
+ channel_slug_lookup = channel_fields.pop("slug")
+
for data in relations_data.iterator():
pk = data.get("pk")
collection = data.get("collections__slug")
@@ -271,22 +137,24 @@ def prepare_products_relations_data(
result_data = add_image_uris_to_data(pk, image, "images__image", result_data)
result_data = add_collection_info_to_data(pk, collection, result_data)
- # handle attributes
- attribute_data: dict = {}
-
- attribute_pk = str(data.pop(attribute_fields["attribute_pk"], ""))
- attribute_data = {
- "slug": data.pop(attribute_fields["slug"], None),
- "value": data.pop(attribute_fields["value"], None),
- }
-
- if attribute_ids and attribute_pk in attribute_ids:
- result_data = add_attribute_info_to_data(
- pk, attribute_data, "product attribute", result_data
- )
+ result_data, data = handle_attribute_data(
+ pk, data, attribute_ids, result_data, attribute_fields, "product attribute"
+ )
+ result_data, data = handle_channel_data(
+ pk,
+ data,
+ channel_ids,
+ result_data,
+ channel_pk_lookup,
+ channel_slug_lookup,
+ channel_fields,
+ )
result: Dict[int, Dict[str, str]] = {
- pk: {header: ", ".join(sorted(values)) for header, values in data.items()}
+ pk: {
+ header: ", ".join(sorted(values)) if isinstance(values, set) else values
+ for header, values in data.items()
+ }
for pk, data in result_data.items()
}
return result
@@ -297,6 +165,7 @@ def get_variants_relations_data(
export_fields: Set[str],
attribute_ids: Optional[List[int]],
warehouse_ids: Optional[List[int]],
+ channel_ids: Optional[List[int]],
) -> Dict[int, Dict[str, str]]:
"""Get data about variants relations fields.
@@ -308,9 +177,9 @@ def get_variants_relations_data(
ProductExportFields.HEADERS_TO_FIELDS_MAPPING["variant_many_to_many"].values()
)
relations_fields = export_fields & many_to_many_fields
- if relations_fields or attribute_ids or warehouse_ids:
+ if relations_fields or attribute_ids or warehouse_ids or channel_ids:
return prepare_variants_relations_data(
- queryset, relations_fields, attribute_ids, warehouse_ids
+ queryset, relations_fields, attribute_ids, warehouse_ids, channel_ids
)
return {}
@@ -321,24 +190,31 @@ def prepare_variants_relations_data(
fields: Set[str],
attribute_ids: Optional[List[int]],
warehouse_ids: Optional[List[int]],
+ channel_ids: Optional[List[int]],
) -> Dict[int, Dict[str, str]]:
"""Prepare data about variants relation fields for given queryset.
It return dict where key is a product pk, value is a dict with relation fields data.
"""
- warehouse_fields = ProductExportFields.WAREHOUSE_FIELDS
attribute_fields = ProductExportFields.VARIANT_ATTRIBUTE_FIELDS
+ warehouse_fields = ProductExportFields.WAREHOUSE_FIELDS
+ channel_fields = ProductExportFields.VARIANT_CHANNEL_LISTING_FIELDS.copy()
result_data: Dict[int, dict] = defaultdict(dict)
fields.add("variants__pk")
if attribute_ids:
- fields.update(ProductExportFields.VARIANT_ATTRIBUTE_FIELDS.values())
+ fields.update(attribute_fields.values())
if warehouse_ids:
- fields.update(ProductExportFields.WAREHOUSE_FIELDS.values())
+ fields.update(warehouse_fields.values())
+ if channel_ids:
+ fields.update(channel_fields.values())
relations_data = queryset.values(*fields)
+ channel_pk_lookup = channel_fields.pop("channel_pk")
+ channel_slug_lookup = channel_fields.pop("slug")
+
for data in relations_data.iterator():
pk = data.get("variants__pk")
image = data.pop("variants__images__image", None)
@@ -346,30 +222,21 @@ def prepare_variants_relations_data(
result_data = add_image_uris_to_data(
pk, image, "variants__images__image", result_data
)
-
- # handle attribute and warehouse data
- attribute_data: dict = {}
- warehouse_data: dict = {}
-
- attribute_pk = str(data.pop(attribute_fields["attribute_pk"], ""))
- attribute_data = {
- "slug": data.pop(attribute_fields["slug"], None),
- "value": data.pop(attribute_fields["value"], None),
- }
-
- warehouse_pk = str(data.pop(warehouse_fields["warehouse_pk"], ""))
- warehouse_data = {
- "slug": data.pop(warehouse_fields["slug"], None),
- "qty": data.pop(warehouse_fields["quantity"], None),
- }
-
- if attribute_ids and attribute_pk in attribute_ids:
- result_data = add_attribute_info_to_data(
- pk, attribute_data, "variant attribute", result_data
- )
-
- if warehouse_ids and warehouse_pk in warehouse_ids:
- result_data = add_warehouse_info_to_data(pk, warehouse_data, result_data)
+ result_data, data = handle_attribute_data(
+ pk, data, attribute_ids, result_data, attribute_fields, "variant attribute"
+ )
+ result_data, data = handle_channel_data(
+ pk,
+ data,
+ channel_ids,
+ result_data,
+ channel_pk_lookup,
+ channel_slug_lookup,
+ channel_fields,
+ )
+ result_data, data = handle_warehouse_data(
+ pk, data, warehouse_ids, result_data, warehouse_fields
+ )
result: Dict[int, Dict[str, str]] = {
pk: {
@@ -419,6 +286,77 @@ def add_image_uris_to_data(
return result_data
+def handle_attribute_data(
+ pk: int,
+ data: dict,
+ attribute_ids: Optional[List[int]],
+ result_data: Dict[int, dict],
+ attribute_fields: dict,
+ attribute_owner: str,
+):
+ attribute_data: dict = {}
+
+ attribute_pk = str(data.pop(attribute_fields["attribute_pk"], ""))
+ attribute_data = {
+ "slug": data.pop(attribute_fields["slug"], None),
+ "value": data.pop(attribute_fields["value"], None),
+ }
+
+ if attribute_ids and attribute_pk in attribute_ids:
+ result_data = add_attribute_info_to_data(
+ pk, attribute_data, attribute_owner, result_data
+ )
+
+ return result_data, data
+
+
+def handle_channel_data(
+ pk: int,
+ data: dict,
+ channel_ids: Optional[List[int]],
+ result_data: Dict[int, dict],
+ pk_lookup: str,
+ slug_lookup: str,
+ fields: dict,
+):
+ channel_data: dict = {}
+
+ channel_pk = str(data.pop(pk_lookup, ""))
+ channel_data = {
+ "slug": data.pop(slug_lookup, None),
+ }
+ for field, lookup in fields.items():
+ channel_data[field] = data.pop(lookup, None)
+
+ if channel_ids and channel_pk in channel_ids:
+ result_data = add_channel_info_to_data(
+ pk, channel_data, result_data, list(fields.keys())
+ )
+
+ return result_data, data
+
+
+def handle_warehouse_data(
+ pk: int,
+ data: dict,
+ warehouse_ids: Optional[List[int]],
+ result_data: Dict[int, dict],
+ warehouse_fields: dict,
+):
+ warehouse_data: dict = {}
+
+ warehouse_pk = str(data.pop(warehouse_fields["warehouse_pk"], ""))
+ warehouse_data = {
+ "slug": data.pop(warehouse_fields["slug"], None),
+ "qty": data.pop(warehouse_fields["quantity"], None),
+ }
+
+ if warehouse_ids and warehouse_pk in warehouse_ids:
+ result_data = add_warehouse_info_to_data(pk, warehouse_data, result_data)
+
+ return result_data, data
+
+
def add_attribute_info_to_data(
pk: int,
attribute_data: Dict[str, Optional[Union[str]]],
@@ -430,7 +368,7 @@ def add_attribute_info_to_data(
This functions adds info about attribute to dict with variant or product data.
If attribute with given slug already exists in data, attribute value is added
to set with values.
- It returns updated data and attribute header created based on attribute slug.
+ It returns updated data.
"""
slug = attribute_data["slug"]
header = None
@@ -451,7 +389,7 @@ def add_warehouse_info_to_data(
"""Add info about stock quantity to variant data.
This functions adds info about stock quantity to dict with variant data.
- It returns updated data and warehouse header created based on warehouse slug.
+ It returns updated data.
"""
slug = warehouse_data["slug"]
@@ -461,3 +399,24 @@ def add_warehouse_info_to_data(
result_data[pk][warehouse_qty_header] = warehouse_data["qty"]
return result_data
+
+
+def add_channel_info_to_data(
+ pk: int,
+ channel_data: Dict[str, Union[Optional[str]]],
+ result_data: Dict[int, dict],
+ fields: List[str],
+) -> Dict[int, dict]:
+ """Add info about channel currency code, whether is published and publication date.
+
+ This functions adds info about channel to dict with product data.
+ It returns updated data.
+ """
+ slug = channel_data["slug"]
+ if slug:
+ for field in fields:
+ header = f"{slug} (channel {field.replace('_', ' ')})"
+ if header not in result_data[pk]:
+ result_data[pk][header] = channel_data[field]
+
+ return result_data
diff --git a/saleor/data_feeds/google_merchant.py b/saleor/data_feeds/google_merchant.py
deleted file mode 100644
index 21f7520652..0000000000
--- a/saleor/data_feeds/google_merchant.py
+++ /dev/null
@@ -1,266 +0,0 @@
-import csv
-import gzip
-from typing import Iterable
-
-from django.conf import settings
-from django.contrib.sites.models import Site
-from django.contrib.syndication.views import add_domain
-from django.core.files.storage import default_storage
-from django.utils import timezone
-from django.utils.encoding import smart_text
-from django_countries.fields import Country
-
-from ..core.taxes import charge_taxes_on_shipping
-from ..discount import DiscountInfo
-from ..discount.utils import fetch_discounts
-from ..plugins.manager import get_plugins_manager
-from ..product.models import Attribute, AttributeValue, Category, ProductVariant
-from ..warehouse.availability import is_variant_in_stock
-
-CATEGORY_SEPARATOR = " > "
-
-FILE_PATH = "google-feed.csv.gz"
-
-ATTRIBUTES = [
- "id",
- "title",
- "product_type",
- "google_product_category",
- "image_link",
- "condition",
- "availability",
- "price",
- "tax",
- "sale_price",
- "mpn",
- "brand",
- "item_group_id",
- "gender",
- "age_group",
- "color",
- "size",
- "description",
-]
-
-
-def get_feed_file_url():
- return default_storage.url(FILE_PATH)
-
-
-def get_feed_items():
- items = ProductVariant.objects.all()
- items = items.select_related("product")
- items = items.prefetch_related(
- "images",
- "product__category",
- "product__images",
- "product__product_type__product_attributes",
- "product__product_type__variant_attributes",
- )
- return items
-
-
-def item_id(item: ProductVariant):
- return item.sku
-
-
-def item_mpn(item: ProductVariant):
- return str(item.sku)
-
-
-def item_guid(item: ProductVariant):
- return item.sku
-
-
-def item_title(item: ProductVariant):
- return item.display_product()
-
-
-def item_description(item: ProductVariant):
- return item.product.plain_text_description[:100]
-
-
-def item_condition(item: ProductVariant):
- """Return a valid item condition.
-
- Allowed values: new, refurbished, and used.
- Read more:
- https://support.google.com/merchants/answer/6324469
- """
- return "new"
-
-
-def item_brand(item: ProductVariant, attributes_dict, attribute_values_dict):
- """Return an item brand.
-
- This field is required.
- Read more:
- https://support.google.com/merchants/answer/6324351?hl=en&ref_topic=6324338
- """
- brand = None
- brand_attribute_pk = attributes_dict.get("brand")
- publisher_attribute_pk = attributes_dict.get("publisher")
-
- if brand_attribute_pk:
- brand = item.attributes.get(str(brand_attribute_pk))
- if brand is None:
- brand = item.product.attributes.get(str(brand_attribute_pk))
-
- if brand is None and publisher_attribute_pk is not None:
- brand = item.attributes.get(str(publisher_attribute_pk))
- if brand is None:
- brand = item.product.attributes.get(str(publisher_attribute_pk))
-
- if brand:
- brand_name = attribute_values_dict.get(brand)
- if brand_name is not None:
- return brand_name
- return brand
-
-
-def item_tax(
- item: ProductVariant,
- discounts: Iterable[DiscountInfo],
- is_charge_taxes_on_shipping: bool,
-):
- """Return item tax.
-
- For some countries you need to set tax info
- Read more:
- https://support.google.com/merchants/answer/6324454
- """
- country = Country(settings.DEFAULT_COUNTRY)
- tax_rate = get_plugins_manager().get_tax_rate_percentage_value(
- item.product.product_type, country
- )
- if tax_rate:
- tax_ship = "yes" if is_charge_taxes_on_shipping else "no"
- return "%s::%s:%s" % (country.code, tax_rate, tax_ship)
- return None
-
-
-def item_group_id(item: ProductVariant):
- return str(item.product.pk)
-
-
-def item_image_link(item: ProductVariant, current_site):
- product_image = item.get_first_image()
- if product_image:
- image = product_image.image
- return add_domain(current_site.domain, image.url, False)
- return None
-
-
-def item_availability(item: ProductVariant):
- if is_variant_in_stock(item, settings.DEFAULT_COUNTRY):
- return "in stock"
- return "out of stock"
-
-
-def item_google_product_category(item: ProductVariant, category_paths):
- """Return a canonical product category.
-
- To have your categories accepted, please use names accepted by Google or
- write custom function which maps your category names into to Google codes.
- Read more:
- https://support.google.com/merchants/answer/6324436
- """
- category = item.product.category
- if not category:
- raise Exception(f"Item {item} does not have category")
- if category.pk in category_paths:
- return category_paths[category.pk]
- ancestors = [ancestor.name for ancestor in list(category.get_ancestors())]
- category_path = CATEGORY_SEPARATOR.join(ancestors + [category.name])
- category_paths[category.pk] = category_path
- return category_path
-
-
-def item_price(item: ProductVariant):
- price = item.get_price(discounts=None)
- return "%s %s" % (price.amount, price.currency)
-
-
-def item_sale_price(item: ProductVariant, discounts: Iterable[DiscountInfo]):
- sale_price = item.get_price(discounts=discounts)
- return "%s %s" % (sale_price.amount, sale_price.currency)
-
-
-def item_attributes(
- item: ProductVariant,
- categories,
- category_paths,
- current_site,
- discounts: Iterable[DiscountInfo],
- attributes_dict,
- attribute_values_dict,
- is_charge_taxes_on_shipping: bool,
-):
- product_data = {
- "id": item_id(item),
- "title": item_title(item),
- "description": item_description(item),
- "condition": item_condition(item),
- "mpn": item_mpn(item),
- "item_group_id": item_group_id(item),
- "availability": item_availability(item),
- "google_product_category": item_google_product_category(item, category_paths),
- }
-
- image_link = item_image_link(item, current_site)
- if image_link:
- product_data["image_link"] = image_link
-
- price = item_price(item)
- product_data["price"] = price
- sale_price = item_sale_price(item, discounts)
- if sale_price != price:
- product_data["sale_price"] = sale_price
-
- tax = item_tax(item, discounts, is_charge_taxes_on_shipping)
- if tax:
- product_data["tax"] = tax
-
- brand = item_brand(item, attributes_dict, attribute_values_dict)
- if brand:
- product_data["brand"] = brand
-
- return product_data
-
-
-def write_feed(file_obj):
- """Write feed contents info provided file object."""
- is_charge_taxes_on_shipping = charge_taxes_on_shipping()
- writer = csv.DictWriter(file_obj, ATTRIBUTES, dialect=csv.excel_tab)
- writer.writeheader()
- categories = Category.objects.all()
- discounts = fetch_discounts(timezone.now())
- attributes_dict = {a.slug: a.pk for a in Attribute.objects.all()}
- attribute_values_dict = {
- smart_text(a.pk): smart_text(a) for a in AttributeValue.objects.all()
- }
- category_paths = {}
- current_site = Site.objects.get_current()
- for item in get_feed_items():
- item_data = item_attributes(
- item,
- categories,
- category_paths,
- current_site,
- discounts,
- attributes_dict,
- attribute_values_dict,
- is_charge_taxes_on_shipping,
- )
- writer.writerow(item_data)
-
-
-def update_feed(file_path=FILE_PATH):
- """Save updated feed into path provided as argument.
-
- Default path is defined in module as FILE_PATH.
- """
- with default_storage.open(file_path, "wb") as output_file:
- output = gzip.open(output_file, "wt")
- write_feed(output)
- output.close()
diff --git a/saleor/data_feeds/management/commands/update_feeds.py b/saleor/data_feeds/management/commands/update_feeds.py
deleted file mode 100644
index d971ba687f..0000000000
--- a/saleor/data_feeds/management/commands/update_feeds.py
+++ /dev/null
@@ -1,10 +0,0 @@
-from django.core.management import BaseCommand
-
-from ...google_merchant import update_feed
-
-
-class Command(BaseCommand):
- help = "Update Google merchant feed"
-
- def handle(self, *args, **options):
- update_feed()
diff --git a/saleor/data_feeds/tests/test_data_feeds.py b/saleor/data_feeds/tests/test_data_feeds.py
deleted file mode 100644
index 6e43d19386..0000000000
--- a/saleor/data_feeds/tests/test_data_feeds.py
+++ /dev/null
@@ -1,95 +0,0 @@
-import csv
-from io import StringIO
-from unittest.mock import Mock
-
-from django.utils.encoding import smart_text
-from django_prices_vatlayer.models import VAT
-
-from ...core.taxes import charge_taxes_on_shipping
-from ...product.models import AttributeValue, Category
-from ..google_merchant import (
- get_feed_items,
- item_attributes,
- item_availability,
- item_google_product_category,
- item_tax,
- write_feed,
-)
-
-
-def test_saleor_feed_items(product, discount_info, site_settings):
- is_charge_taxes_on_shipping = charge_taxes_on_shipping()
- valid_variant = product.variants.first()
- items = get_feed_items()
- assert len(items) == 1
- categories = Category.objects.all()
- discounts = [discount_info]
- category_paths = {}
- attributes_dict = {}
- current_site = site_settings.site
- attribute_values_dict = {
- smart_text(a.pk): smart_text(a) for a in AttributeValue.objects.all()
- }
- attributes = item_attributes(
- items[0],
- categories,
- category_paths,
- current_site,
- discounts,
- attributes_dict,
- attribute_values_dict,
- is_charge_taxes_on_shipping,
- )
- assert attributes.get("mpn") == valid_variant.sku
- assert attributes.get("availability") == "in stock"
- assert attributes.get("tax") is None
- assert attributes.get("price") == "10.000 USD"
- assert attributes.get("sale_price") == "5.000 USD"
-
-
-def test_saleor_get_feed_items_having_no_stock_info(variant, site_settings):
- variant.stocks.all().delete()
- assert item_availability(variant) == "out of stock"
-
-
-def test_category_formatter(db):
- main_category = Category(name="Main", slug="main")
- main_category.save()
- main_category_item = Mock(product=Mock(category=main_category))
- sub_category = Category(name="Sub", slug="sub", parent=main_category)
- sub_category.save()
- sub_category_item = Mock(product=Mock(category=sub_category))
- assert item_google_product_category(main_category_item, {}) == "Main"
- assert item_google_product_category(sub_category_item, {}) == "Main > Sub"
-
-
-def test_tax_formatter(variant, vatlayer, tax_rates):
- discounts = []
- VAT.objects.create(country_code="US", data=tax_rates)
- is_charge_taxes_on_shipping = charge_taxes_on_shipping()
- item_tax_value = item_tax(variant, discounts, is_charge_taxes_on_shipping)
- assert item_tax_value == "US::23:yes"
-
-
-def test_write_feed(product, monkeypatch):
- buffer = StringIO()
- write_feed(buffer)
- buffer.seek(0)
- dialect = csv.Sniffer().sniff(buffer.getvalue())
- assert dialect.delimiter == csv.excel_tab.delimiter
- assert dialect.quotechar == csv.excel_tab.quotechar
- assert dialect.escapechar == csv.excel_tab.escapechar
- assert csv.Sniffer().has_header(buffer.getvalue())
- lines = [line for line in csv.reader(buffer, dialect=csv.excel_tab)]
- assert len(lines) == 2
- header = lines[0]
- google_required_fields = [
- "id",
- "title",
- "image_link",
- "availability",
- "price",
- "condition",
- ]
- for field in google_required_fields:
- assert field in header
diff --git a/saleor/data_feeds/urls.py b/saleor/data_feeds/urls.py
deleted file mode 100644
index b97e5b8229..0000000000
--- a/saleor/data_feeds/urls.py
+++ /dev/null
@@ -1,12 +0,0 @@
-from django.conf.urls import url
-from django.views.generic.base import RedirectView
-
-from .google_merchant import get_feed_file_url
-
-urlpatterns = [
- url(
- r"google/$",
- RedirectView.as_view(get_redirect_url=get_feed_file_url, permanent=True),
- name="google-feed",
- )
-]
diff --git a/saleor/demo/views.py b/saleor/demo/views.py
index 430e22b198..2fef3f97d0 100644
--- a/saleor/demo/views.py
+++ b/saleor/demo/views.py
@@ -1,3 +1,4 @@
+from django.conf import settings
from django.shortcuts import render
from ..graphql.views import API_PATH, GraphQLView
@@ -11,7 +12,7 @@ EXAMPLE_QUERY = """# Welcome to Saleor GraphQL API!
# Here is an example query to fetch a list of products:
#
{
- products(first: 5) {
+ products(first: 5, channel: "%(channel_slug)s") {
edges {
node {
id
@@ -21,7 +22,9 @@ EXAMPLE_QUERY = """# Welcome to Saleor GraphQL API!
}
}
}
-"""
+""" % {
+ "channel_slug": settings.DEFAULT_CHANNEL_SLUG
+}
class DemoGraphQLView(GraphQLView):
diff --git a/saleor/discount/__init__.py b/saleor/discount/__init__.py
index 74030bbba3..4d428c9dc1 100644
--- a/saleor/discount/__init__.py
+++ b/saleor/discount/__init__.py
@@ -1,11 +1,11 @@
from dataclasses import dataclass
-from typing import TYPE_CHECKING, List, Set, Union
+from typing import TYPE_CHECKING, Dict, Iterable, List, Set, Union
from django.conf import settings
if TYPE_CHECKING:
# flake8: noqa
- from .models import Sale, Voucher
+ from .models import Sale, Voucher, SaleChannelListing
class DiscountValueType:
@@ -13,7 +13,7 @@ class DiscountValueType:
PERCENTAGE = "percentage"
CHOICES = [
- (FIXED, settings.DEFAULT_CURRENCY),
+ (FIXED, "fixed"),
(PERCENTAGE, "%"),
]
@@ -33,6 +33,7 @@ class VoucherType:
@dataclass
class DiscountInfo:
sale: Union["Sale", "Voucher"]
+ channel_listings: Dict[str, "SaleChannelListing"]
product_ids: Union[List[int], Set[int]]
category_ids: Union[List[int], Set[int]]
collection_ids: Union[List[int], Set[int]]
diff --git a/saleor/discount/error_codes.py b/saleor/discount/error_codes.py
index dfa2720473..ebb05bb40a 100644
--- a/saleor/discount/error_codes.py
+++ b/saleor/discount/error_codes.py
@@ -8,3 +8,5 @@ class DiscountErrorCode(Enum):
NOT_FOUND = "not_found"
REQUIRED = "required"
UNIQUE = "unique"
+ CANNOT_MANAGE_PRODUCT_WITHOUT_VARIANT = "cannot_manage_product_without_variant"
+ DUPLICATED_INPUT_ITEM = "duplicated_input_item"
diff --git a/saleor/discount/migrations/0002_voucher.py b/saleor/discount/migrations/0002_voucher.py
index 977dde877e..405fb4940d 100644
--- a/saleor/discount/migrations/0002_voucher.py
+++ b/saleor/discount/migrations/0002_voucher.py
@@ -3,9 +3,9 @@
from __future__ import unicode_literals
import datetime
+import os
import django.db.models.deletion
-from django.conf import settings
from django.db import migrations, models
@@ -61,7 +61,7 @@ class Migration(migrations.Migration):
"discount_value_type",
models.CharField(
choices=[
- ("fixed", settings.DEFAULT_CURRENCY),
+ ("fixed", os.environ.get("DEFAULT_CURRENCY", "USD")),
("percentage", "%"),
],
default="fixed",
diff --git a/saleor/discount/migrations/0003_auto_20160207_0534.py b/saleor/discount/migrations/0003_auto_20160207_0534.py
index c3ef6e8166..4a5b2dee0c 100644
--- a/saleor/discount/migrations/0003_auto_20160207_0534.py
+++ b/saleor/discount/migrations/0003_auto_20160207_0534.py
@@ -3,8 +3,8 @@
from __future__ import unicode_literals
import datetime
+import os
-from django.conf import settings
from django.db import migrations, models
@@ -17,7 +17,10 @@ class Migration(migrations.Migration):
model_name="sale",
name="type",
field=models.CharField(
- choices=[("fixed", settings.DEFAULT_CURRENCY), ("percentage", "%")],
+ choices=[
+ ("fixed", os.environ.get("DEFAULT_CURRENCY", "USD")),
+ ("percentage", "%"),
+ ],
default="fixed",
max_length=10,
),
@@ -40,7 +43,10 @@ class Migration(migrations.Migration):
model_name="voucher",
name="discount_value_type",
field=models.CharField(
- choices=[("fixed", settings.DEFAULT_CURRENCY), ("percentage", "%")],
+ choices=[
+ ("fixed", os.environ.get("DEFAULT_CURRENCY", "USD")),
+ ("percentage", "%"),
+ ],
default="fixed",
max_length=10,
verbose_name="discount type",
diff --git a/saleor/discount/migrations/0004_auto_20170206_0407.py b/saleor/discount/migrations/0004_auto_20170206_0407.py
index 56ca2d62b6..99ee61e8f4 100644
--- a/saleor/discount/migrations/0004_auto_20170206_0407.py
+++ b/saleor/discount/migrations/0004_auto_20170206_0407.py
@@ -2,8 +2,9 @@
# Generated by Django 1.10.5 on 2017-02-06 10:07
from __future__ import unicode_literals
+import os
+
import django.db.models.deletion
-from django.conf import settings
from django.db import migrations, models
@@ -43,7 +44,10 @@ class Migration(migrations.Migration):
model_name="sale",
name="type",
field=models.CharField(
- choices=[("fixed", settings.DEFAULT_CURRENCY), ("percentage", "%")],
+ choices=[
+ ("fixed", os.environ.get("DEFAULT_CURRENCY", "USD")),
+ ("percentage", "%"),
+ ],
default="fixed",
max_length=10,
verbose_name="type",
diff --git a/saleor/discount/migrations/0007_auto_20180108_0814.py b/saleor/discount/migrations/0007_auto_20180108_0814.py
index 1e9719cfe3..7afdeb68a7 100644
--- a/saleor/discount/migrations/0007_auto_20180108_0814.py
+++ b/saleor/discount/migrations/0007_auto_20180108_0814.py
@@ -3,9 +3,9 @@
from __future__ import unicode_literals
import datetime
+import os
import django.db.models.deletion
-from django.conf import settings
from django.db import migrations, models
@@ -31,7 +31,10 @@ class Migration(migrations.Migration):
model_name="sale",
name="type",
field=models.CharField(
- choices=[("fixed", settings.DEFAULT_CURRENCY), ("percentage", "%")],
+ choices=[
+ ("fixed", os.environ.get("DEFAULT_CURRENCY", "USD")),
+ ("percentage", "%"),
+ ],
default="fixed",
max_length=10,
),
@@ -70,7 +73,10 @@ class Migration(migrations.Migration):
model_name="voucher",
name="discount_value_type",
field=models.CharField(
- choices=[("fixed", settings.DEFAULT_CURRENCY), ("percentage", "%")],
+ choices=[
+ ("fixed", os.environ.get("DEFAULT_CURRENCY", "USD")),
+ ("percentage", "%"),
+ ],
default="fixed",
max_length=10,
),
diff --git a/saleor/discount/migrations/0017_django_price_2.py b/saleor/discount/migrations/0017_django_price_2.py
index 50b5bcd69f..585fe547ab 100644
--- a/saleor/discount/migrations/0017_django_price_2.py
+++ b/saleor/discount/migrations/0017_django_price_2.py
@@ -1,5 +1,7 @@
# Generated by Django 2.2.4 on 2019-08-14 09:13
+import os
+
from django.conf import settings
from django.db import migrations, models
@@ -18,7 +20,7 @@ class Migration(migrations.Migration):
model_name="voucher",
name="currency",
field=models.CharField(
- default=settings.DEFAULT_CURRENCY,
+ default=os.environ.get("DEFAULT_CURRENCY", "USD"),
max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH,
),
),
diff --git a/saleor/discount/migrations/0022_sale_channel_listing.py b/saleor/discount/migrations/0022_sale_channel_listing.py
new file mode 100644
index 0000000000..8084fed42a
--- /dev/null
+++ b/saleor/discount/migrations/0022_sale_channel_listing.py
@@ -0,0 +1,83 @@
+# Generated by Django 3.1 on 2020-09-16 11:23
+
+import os
+
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+from django.utils.text import slugify
+
+
+def migrate_sale_data(apps, schema):
+ Channel = apps.get_model("channel", "Channel")
+ Sale = apps.get_model("discount", "Sale")
+ SaleChannelListing = apps.get_model("discount", "SaleChannelListing")
+
+ currency = os.environ.get("DEFAULT_CURRENCY", "USD")
+ if Sale.objects.exists():
+ channel, _ = Channel.objects.get_or_create(
+ slug=slugify(settings.DEFAULT_CHANNEL_SLUG),
+ defaults={"name": f"Channel {currency}", "currency": currency},
+ )
+ for sale in Sale.objects.iterator():
+ SaleChannelListing.objects.create(
+ sale=sale, channel=channel, discount_value=sale.value, currency=currency
+ )
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("channel", "0001_initial"),
+ ("discount", "0021_auto_20200902_1249"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="SaleChannelListing",
+ fields=[
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ (
+ "discount_value",
+ models.DecimalField(decimal_places=3, default=0, max_digits=12),
+ ),
+ ("currency", models.CharField(max_length=3)),
+ (
+ "channel",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="sale_listings",
+ to="channel.channel",
+ ),
+ ),
+ (
+ "sale",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="channel_listings",
+ to="discount.sale",
+ ),
+ ),
+ ],
+ options={"ordering": ("pk",), "unique_together": {("sale", "channel")}},
+ ),
+ migrations.RunPython(migrate_sale_data, migrations.RunPython.noop),
+ migrations.RemoveField(model_name="sale", name="value",),
+ migrations.AlterField(
+ model_name="sale",
+ name="type",
+ field=models.CharField(
+ choices=[("fixed", "fixed"), ("percentage", "%")],
+ default="fixed",
+ max_length=10,
+ ),
+ ),
+ ]
diff --git a/saleor/discount/migrations/0023_voucher_channel_listing.py b/saleor/discount/migrations/0023_voucher_channel_listing.py
new file mode 100644
index 0000000000..2441d48c53
--- /dev/null
+++ b/saleor/discount/migrations/0023_voucher_channel_listing.py
@@ -0,0 +1,97 @@
+# Generated by Django 3.1 on 2020-09-21 08:26
+
+import django.db.models.deletion
+from django.db import migrations, models
+from django.utils.text import slugify
+
+
+def migrate_voucher_data(apps, schema_editor):
+ Channel = apps.get_model("channel", "Channel")
+ Voucher = apps.get_model("discount", "Voucher")
+ VoucherChannelListing = apps.get_model("discount", "VoucherChannelListing")
+
+ if Voucher.objects.exists():
+ channels_dict = {}
+
+ for voucher in Voucher.objects.iterator():
+ currency = voucher.currency
+ channel = channels_dict.get(currency)
+ if not channel:
+ name = f"Channel {currency}"
+ channel, _ = Channel.objects.get_or_create(
+ currency_code=currency,
+ defaults={"name": name, "slug": slugify(name)},
+ )
+ channels_dict[currency] = channel
+ VoucherChannelListing.objects.create(
+ voucher=voucher,
+ channel=channel,
+ currency=currency,
+ discount_value=voucher.discount_value,
+ min_spent_amount=voucher.min_spent_amount,
+ )
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("discount", "0022_sale_channel_listing"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="VoucherChannelListing",
+ fields=[
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ (
+ "discount_value",
+ models.DecimalField(decimal_places=3, max_digits=12),
+ ),
+ ("currency", models.CharField(max_length=3)),
+ (
+ "min_spent_amount",
+ models.DecimalField(
+ blank=True, decimal_places=3, max_digits=12, null=True
+ ),
+ ),
+ (
+ "channel",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="voucher_listings",
+ to="channel.channel",
+ ),
+ ),
+ (
+ "voucher",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="channel_listings",
+ to="discount.voucher",
+ ),
+ ),
+ ],
+ options={"ordering": ("pk",), "unique_together": {("voucher", "channel")}},
+ ),
+ migrations.RunPython(migrate_voucher_data, migrations.RunPython.noop),
+ migrations.RemoveField(model_name="voucher", name="currency",),
+ migrations.RemoveField(model_name="voucher", name="discount_value",),
+ migrations.RemoveField(model_name="voucher", name="min_spent_amount",),
+ migrations.AlterField(
+ model_name="voucher",
+ name="discount_value_type",
+ field=models.CharField(
+ choices=[("fixed", "fixed"), ("percentage", "%")],
+ default="fixed",
+ max_length=10,
+ ),
+ ),
+ ]
diff --git a/saleor/discount/models.py b/saleor/discount/models.py
index 00b4d83782..895929479c 100644
--- a/saleor/discount/models.py
+++ b/saleor/discount/models.py
@@ -10,6 +10,7 @@ from django_prices.models import MoneyField
from django_prices.templatetags.prices import amount
from prices import Money, fixed_discount, percentage_discount
+from ..channel.models import Channel
from ..core.permissions import DiscountPermissions
from ..core.utils.translations import TranslationProxy
from . import DiscountValueType, VoucherType
@@ -38,6 +39,12 @@ class VoucherQueryset(models.QuerySet):
start_date__lte=date,
)
+ def active_in_channel(self, date, channel_slug: str):
+ return self.active(date).filter(
+ channel_listings__channel__slug=channel_slug,
+ channel_listings__channel__is_active=True,
+ )
+
def expired(self, date):
return self.filter(
Q(used__gte=F("usage_limit")) | Q(end_date__lt=date), start_date__lt=date
@@ -64,25 +71,9 @@ class Voucher(models.Model):
choices=DiscountValueType.CHOICES,
default=DiscountValueType.FIXED,
)
- discount_value = models.DecimalField(
- max_digits=settings.DEFAULT_MAX_DIGITS,
- decimal_places=settings.DEFAULT_DECIMAL_PLACES,
- )
- discount = MoneyField(amount_field="discount_value", currency_field="currency")
# not mandatory fields, usage depends on type
countries = CountryField(multiple=True, blank=True)
- currency = models.CharField(
- max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH,
- default=settings.DEFAULT_CURRENCY,
- )
- min_spent_amount = models.DecimalField(
- max_digits=settings.DEFAULT_MAX_DIGITS,
- decimal_places=settings.DEFAULT_DECIMAL_PLACES,
- blank=True,
- null=True,
- )
- min_spent = MoneyField(amount_field="min_spent_amount", currency_field="currency")
min_checkout_items_quantity = models.PositiveIntegerField(null=True, blank=True)
products = models.ManyToManyField("product.Product", blank=True)
collections = models.ManyToManyField("product.Collection", blank=True)
@@ -94,21 +85,6 @@ class Voucher(models.Model):
class Meta:
ordering = ("code",)
- def __str__(self):
- if self.name:
- return self.name
- discount = "%s %s" % (
- self.discount_value,
- self.get_discount_value_type_display(),
- )
- if self.type == VoucherType.SHIPPING:
- if self.is_free:
- return "Free shipping"
- return f"{discount} off shipping"
- if self.type == VoucherType.SPECIFIC_PRODUCT:
- return f"%{discount} off specific products"
- return f"{discount} off"
-
@property
def is_free(self):
return (
@@ -116,25 +92,36 @@ class Voucher(models.Model):
and self.discount_value_type == DiscountValueType.PERCENTAGE
)
- def get_discount(self):
+ def get_discount(self, channel: Channel):
+ voucher_channel_listing = self.channel_listings.filter(channel=channel).first()
+ if not voucher_channel_listing:
+ raise NotApplicable("This voucher is not assigned to this channel")
if self.discount_value_type == DiscountValueType.FIXED:
- discount_amount = Money(self.discount_value, settings.DEFAULT_CURRENCY)
+ discount_amount = Money(
+ voucher_channel_listing.discount_value, voucher_channel_listing.currency
+ )
return partial(fixed_discount, discount=discount_amount)
if self.discount_value_type == DiscountValueType.PERCENTAGE:
- return partial(percentage_discount, percentage=self.discount_value)
+ return partial(
+ percentage_discount, percentage=voucher_channel_listing.discount_value
+ )
raise NotImplementedError("Unknown discount type")
- def get_discount_amount_for(self, price: Money):
- discount = self.get_discount()
+ def get_discount_amount_for(self, price: Money, channel: Channel):
+ discount = self.get_discount(channel)
after_discount = discount(price)
if after_discount.amount < 0:
return price
return price - after_discount
- def validate_min_spent(self, value: Money):
- if self.min_spent and value < self.min_spent:
- msg = f"This offer is only valid for orders over {amount(self.min_spent)}."
- raise NotApplicable(msg, min_spent=self.min_spent)
+ def validate_min_spent(self, value: Money, channel: Channel):
+ voucher_channel_listing = self.channel_listings.filter(channel=channel).first()
+ if not voucher_channel_listing:
+ raise NotApplicable("This voucher is not assigned to this channel")
+ min_spent = voucher_channel_listing.min_spent
+ if min_spent and value < min_spent:
+ msg = f"This offer is only valid for orders over {amount(min_spent)}."
+ raise NotApplicable(msg, min_spent=min_spent)
def validate_min_checkout_items_quantity(self, quantity):
min_checkout_items_quantity = self.min_checkout_items_quantity
@@ -156,6 +143,40 @@ class Voucher(models.Model):
raise NotApplicable(msg)
+class VoucherChannelListing(models.Model):
+ voucher = models.ForeignKey(
+ Voucher,
+ null=False,
+ blank=False,
+ related_name="channel_listings",
+ on_delete=models.CASCADE,
+ )
+ channel = models.ForeignKey(
+ Channel,
+ null=False,
+ blank=False,
+ related_name="voucher_listings",
+ on_delete=models.CASCADE,
+ )
+ discount_value = models.DecimalField(
+ max_digits=settings.DEFAULT_MAX_DIGITS,
+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,
+ )
+ discount = MoneyField(amount_field="discount_value", currency_field="currency")
+ currency = models.CharField(max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH,)
+ min_spent_amount = models.DecimalField(
+ max_digits=settings.DEFAULT_MAX_DIGITS,
+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,
+ blank=True,
+ null=True,
+ )
+ min_spent = MoneyField(amount_field="min_spent_amount", currency_field="currency")
+
+ class Meta:
+ unique_together = (("voucher", "channel"),)
+ ordering = ("pk",)
+
+
class VoucherCustomer(models.Model):
voucher = models.ForeignKey(
Voucher, related_name="customers", on_delete=models.CASCADE
@@ -200,11 +221,6 @@ class Sale(models.Model):
choices=DiscountValueType.CHOICES,
default=DiscountValueType.FIXED,
)
- value = models.DecimalField(
- max_digits=settings.DEFAULT_MAX_DIGITS,
- decimal_places=settings.DEFAULT_DECIMAL_PLACES,
- default=0,
- )
products = models.ManyToManyField("product.Product", blank=True)
categories = models.ManyToManyField("product.Category", blank=True)
collections = models.ManyToManyField("product.Collection", blank=True)
@@ -225,24 +241,53 @@ class Sale(models.Model):
)
def __repr__(self):
- return "Sale(name=%r, value=%r, type=%s)" % (
- str(self.name),
- self.value,
- self.get_type_display(),
- )
+ return "Sale(name=%r, type=%s)" % (str(self.name), self.get_type_display(),)
def __str__(self):
return self.name
- def get_discount(self):
+ def get_discount(self, sale_channel_listing):
+ if not sale_channel_listing:
+ raise NotApplicable("This sale is not assigned to this channel.")
if self.type == DiscountValueType.FIXED:
- discount_amount = Money(self.value, settings.DEFAULT_CURRENCY)
+ discount_amount = Money(
+ sale_channel_listing.discount_value, sale_channel_listing.currency
+ )
return partial(fixed_discount, discount=discount_amount)
if self.type == DiscountValueType.PERCENTAGE:
- return partial(percentage_discount, percentage=self.value)
+ return partial(
+ percentage_discount, percentage=sale_channel_listing.discount_value,
+ )
raise NotImplementedError("Unknown discount type")
+class SaleChannelListing(models.Model):
+ sale = models.ForeignKey(
+ Sale,
+ null=False,
+ blank=False,
+ related_name="channel_listings",
+ on_delete=models.CASCADE,
+ )
+ channel = models.ForeignKey(
+ Channel,
+ null=False,
+ blank=False,
+ related_name="sale_listings",
+ on_delete=models.CASCADE,
+ )
+ discount_value = models.DecimalField(
+ max_digits=settings.DEFAULT_MAX_DIGITS,
+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,
+ default=0,
+ )
+ currency = models.CharField(max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH,)
+
+ class Meta:
+ unique_together = [["sale", "channel"]]
+ ordering = ("pk",)
+
+
class SaleTranslation(models.Model):
language_code = models.CharField(max_length=10)
name = models.CharField(max_length=255, null=True, blank=True)
diff --git a/saleor/discount/tests/test_discounts.py b/saleor/discount/tests/test_discounts.py
index d5b1bc45f3..2ce8d596f9 100644
--- a/saleor/discount/tests/test_discounts.py
+++ b/saleor/discount/tests/test_discounts.py
@@ -6,9 +6,16 @@ from django.utils import timezone
from prices import Money
from ...checkout.utils import get_voucher_discount_for_checkout
-from ...product.models import Product, ProductVariant
+from ...product.models import Product, ProductVariant, ProductVariantChannelListing
from .. import DiscountInfo, DiscountValueType, VoucherType
-from ..models import NotApplicable, Sale, Voucher, VoucherCustomer
+from ..models import (
+ NotApplicable,
+ Sale,
+ SaleChannelListing,
+ Voucher,
+ VoucherChannelListing,
+ VoucherCustomer,
+)
from ..templatetags.voucher import discount_as_negative
from ..utils import (
add_voucher_usage_by_customer,
@@ -24,15 +31,38 @@ from ..utils import (
"min_spent_amount, value",
[(Money(5, "USD"), Money(10, "USD")), (Money(10, "USD"), Money(10, "USD"))],
)
-def test_valid_voucher_min_spent_amount(min_spent_amount, value):
- voucher = Voucher(
+def test_valid_voucher_min_spent_amount(min_spent_amount, value, channel_USD):
+ voucher = Voucher.objects.create(
code="unique",
type=VoucherType.SHIPPING,
discount_value_type=DiscountValueType.FIXED,
+ )
+ VoucherChannelListing.objects.create(
+ voucher=voucher,
+ channel=channel_USD,
discount=Money(10, "USD"),
min_spent=min_spent_amount,
)
- voucher.validate_min_spent(value)
+
+ voucher.validate_min_spent(value, channel_USD)
+
+
+def test_valid_voucher_min_spent_amount_voucher_not_assigned_to_channel(
+ channel_USD, channel_PLN
+):
+ voucher = Voucher.objects.create(
+ code="unique",
+ type=VoucherType.SHIPPING,
+ discount_value_type=DiscountValueType.FIXED,
+ )
+ VoucherChannelListing.objects.create(
+ voucher=voucher,
+ channel=channel_USD,
+ discount=Money(10, channel_USD.currency_code),
+ min_spent=(Money(5, channel_USD.currency_code)),
+ )
+ with pytest.raises(NotApplicable):
+ voucher.validate_min_spent(Money(10, channel_PLN.currency_code), channel_PLN)
def test_valid_voucher_min_checkout_items_quantity(voucher):
@@ -50,46 +80,102 @@ def test_valid_voucher_min_checkout_items_quantity(voucher):
@pytest.mark.integration
@pytest.mark.django_db(transaction=True)
-def test_variant_discounts(product):
+def test_variant_discounts(product, channel_USD):
variant = product.variants.get()
- low_sale = Sale(type=DiscountValueType.FIXED, value=5)
+ low_sale = Sale.objects.create(type=DiscountValueType.FIXED)
+ low_sale_channel_listing = SaleChannelListing.objects.create(
+ sale=low_sale,
+ discount_value=5,
+ currency=channel_USD.currency_code,
+ channel=channel_USD,
+ )
low_discount = DiscountInfo(
sale=low_sale,
+ channel_listings={channel_USD.slug: low_sale_channel_listing},
product_ids={product.id},
category_ids=set(),
collection_ids=set(),
)
- sale = Sale(type=DiscountValueType.FIXED, value=8)
+ sale = Sale.objects.create(type=DiscountValueType.FIXED)
+ sale_channel_listing = SaleChannelListing.objects.create(
+ sale=sale,
+ discount_value=8,
+ currency=channel_USD.currency_code,
+ channel=channel_USD,
+ )
discount = DiscountInfo(
- sale=sale, product_ids={product.id}, category_ids=set(), collection_ids=set()
+ sale=sale,
+ channel_listings={channel_USD.slug: sale_channel_listing},
+ product_ids={product.id},
+ category_ids=set(),
+ collection_ids=set(),
+ )
+ high_sale = Sale.objects.create(type=DiscountValueType.FIXED)
+ high_sale_channel_listing = SaleChannelListing.objects.create(
+ sale=high_sale,
+ discount_value=50,
+ currency=channel_USD.currency_code,
+ channel=channel_USD,
)
- high_sale = Sale(type=DiscountValueType.FIXED, value=50)
high_discount = DiscountInfo(
sale=high_sale,
+ channel_listings={channel_USD.slug: high_sale_channel_listing},
product_ids={product.id},
category_ids=set(),
collection_ids=set(),
)
- final_price = variant.get_price(discounts=[low_discount, discount, high_discount])
+ final_price = variant.get_price(
+ channel_USD.slug, discounts=[low_discount, discount, high_discount]
+ )
assert final_price == Money(0, "USD")
@pytest.mark.integration
@pytest.mark.django_db(transaction=True)
-def test_percentage_discounts(product):
+def test_percentage_discounts(product, channel_USD):
variant = product.variants.get()
- sale = Sale(type=DiscountValueType.PERCENTAGE, value=50)
+ sale = Sale.objects.create(type=DiscountValueType.PERCENTAGE)
+ sale_cahnnel_listing = SaleChannelListing.objects.create(
+ sale=sale,
+ discount_value=50,
+ currency=channel_USD.currency_code,
+ channel=channel_USD,
+ )
discount = DiscountInfo(
- sale=sale, product_ids={product.id}, category_ids=set(), collection_ids={}
+ sale=sale,
+ channel_listings={channel_USD.slug: sale_cahnnel_listing},
+ product_ids={product.id},
+ category_ids=set(),
+ collection_ids=set(),
)
- final_price = variant.get_price(discounts=[discount])
+ final_price = variant.get_price(channel_USD.slug, discounts=[discount])
assert final_price == Money(5, "USD")
-def test_voucher_queryset_active(voucher):
+def test_voucher_queryset_active(voucher, channel_USD):
+ vouchers = Voucher.objects.all()
+ assert vouchers.count() == 1
+ active_vouchers = Voucher.objects.active_in_channel(
+ date=timezone.now() - timedelta(days=1), channel_slug=channel_USD.slug
+ )
+ assert active_vouchers.count() == 0
+
+
+def test_voucher_queryset_active_in_channel(voucher, channel_USD):
+ vouchers = Voucher.objects.all()
+ assert vouchers.count() == 1
+ active_vouchers = Voucher.objects.active_in_channel(
+ date=timezone.now(), channel_slug=channel_USD.slug
+ )
+ assert active_vouchers.count() == 1
+
+
+def test_voucher_queryset_active_in_other_channel(voucher, channel_PLN):
vouchers = Voucher.objects.all()
assert vouchers.count() == 1
- active_vouchers = Voucher.objects.active(date=timezone.now() - timedelta(days=1))
+ active_vouchers = Voucher.objects.active_in_channel(
+ date=timezone.now(), channel_slug=channel_PLN.slug
+ )
assert active_vouchers.count() == 0
@@ -113,22 +199,26 @@ def test_specific_products_voucher_checkout_discount(
expected_value,
apply_once_per_order,
checkout_with_item,
+ channel_USD,
):
discounts = []
monkeypatch.setattr(
"saleor.checkout.utils.get_prices_of_discounted_specific_product",
- lambda lines, discounts, discounted_products: (
+ lambda lines, discounts, channel, discounted_products: (
Money(price, "USD") for price in prices
),
)
- voucher = Voucher(
+ voucher = Voucher.objects.create(
code="unique",
type=VoucherType.SPECIFIC_PRODUCT,
discount_value_type=discount_type,
- discount_value=discount_value,
apply_once_per_order=apply_once_per_order,
)
- voucher.save()
+ VoucherChannelListing.objects.create(
+ voucher=voucher,
+ channel=channel_USD,
+ discount=Money(discount_value, channel_USD.currency_code),
+ )
checkout = checkout_with_item
discount = get_voucher_discount_for_checkout(
voucher, checkout, list(checkout), discounts
@@ -136,7 +226,7 @@ def test_specific_products_voucher_checkout_discount(
assert discount == Money(expected_value, "USD")
-def test_sale_applies_to_correct_products(product_type, category):
+def test_sale_applies_to_correct_products(product_type, category, channel_USD):
product = Product.objects.create(
name="Test Product",
slug="test-product",
@@ -145,8 +235,12 @@ def test_sale_applies_to_correct_products(product_type, category):
product_type=product_type,
category=category,
)
- variant = ProductVariant.objects.create(
- product=product, sku="firstvar", price_amount=Decimal(10)
+ variant = ProductVariant.objects.create(product=product, sku="firstvar")
+ variant_channel_listing = ProductVariantChannelListing.objects.create(
+ variant=variant,
+ channel=channel_USD,
+ price_amount=Decimal(10),
+ currency=channel_USD.currency_code,
)
product2 = Product.objects.create(
name="Second product",
@@ -155,42 +249,67 @@ def test_sale_applies_to_correct_products(product_type, category):
product_type=product_type,
category=category,
)
- sec_variant = ProductVariant.objects.create(
- product=product2, sku="secvar", pk=111, price_amount=Decimal(10)
+ sec_variant = ProductVariant.objects.create(product=product2, sku="secvar", pk=111)
+ ProductVariantChannelListing.objects.create(
+ variant=sec_variant,
+ channel=channel_USD,
+ price_amount=Decimal(10),
+ currency=channel_USD.currency_code,
+ )
+ sale = Sale.objects.create(name="Test sale", type=DiscountValueType.FIXED)
+ sale_channel_listing = SaleChannelListing.objects.create(
+ sale=sale,
+ currency=channel_USD.currency_code,
+ channel=channel_USD,
+ discount_value=3,
)
- sale = Sale(name="Test sale", value=3, type=DiscountValueType.FIXED)
discount = DiscountInfo(
- sale=sale, product_ids={product.id}, category_ids=set(), collection_ids=set()
+ sale=sale,
+ channel_listings={channel_USD.slug: sale_channel_listing},
+ product_ids={product.id},
+ category_ids=set(),
+ collection_ids=set(),
+ )
+ product_discount = get_product_discount_on_sale(
+ variant.product, set(), discount, channel_USD
)
- product_discount = get_product_discount_on_sale(variant.product, set(), discount)
- discounted_price = product_discount(variant.price)
+
+ discounted_price = product_discount(variant_channel_listing.price)
assert discounted_price == Money(7, "USD")
with pytest.raises(NotApplicable):
- get_product_discount_on_sale(sec_variant.product, set(), discount)
+ get_product_discount_on_sale(sec_variant.product, set(), discount, channel_USD)
-def test_increase_voucher_usage():
+def test_increase_voucher_usage(channel_USD):
voucher = Voucher.objects.create(
code="unique",
type=VoucherType.ENTIRE_ORDER,
discount_value_type=DiscountValueType.FIXED,
- discount_value=10,
usage_limit=100,
)
+ VoucherChannelListing.objects.create(
+ voucher=voucher,
+ channel=channel_USD,
+ discount=Money(10, channel_USD.currency_code),
+ )
increase_voucher_usage(voucher)
voucher.refresh_from_db()
assert voucher.used == 1
-def test_decrease_voucher_usage():
+def test_decrease_voucher_usage(channel_USD):
voucher = Voucher.objects.create(
code="unique",
type=VoucherType.ENTIRE_ORDER,
discount_value_type=DiscountValueType.FIXED,
- discount_value=10,
usage_limit=100,
used=10,
)
+ VoucherChannelListing.objects.create(
+ voucher=voucher,
+ channel=channel_USD,
+ discount=Money(10, channel_USD.currency_code),
+ )
decrease_voucher_usage(voucher)
voucher.refresh_from_db()
assert voucher.used == 9
@@ -240,18 +359,24 @@ def test_validate_voucher(
total_quantity,
min_checkout_items_quantity,
discount_value_type,
+ channel_USD,
):
voucher = Voucher.objects.create(
code="unique",
- currency="USD",
type=VoucherType.ENTIRE_ORDER,
discount_value_type=discount_value_type,
- discount_value=50,
- min_spent_amount=min_spent_amount,
min_checkout_items_quantity=min_checkout_items_quantity,
)
+ VoucherChannelListing.objects.create(
+ voucher=voucher,
+ channel=channel_USD,
+ discount=Money(50, channel_USD.currency_code),
+ min_spent_amount=min_spent_amount,
+ )
total_price = Money(total, "USD")
- validate_voucher(voucher, total_price, total_quantity, "[email protected]")
+ validate_voucher(
+ voucher, total_price, total_quantity, "[email protected]", channel_USD
+ )
@pytest.mark.parametrize(
@@ -270,27 +395,35 @@ def test_validate_voucher_not_applicable(
min_checkout_items_quantity,
discount_value,
discount_value_type,
+ channel_USD,
):
voucher = Voucher.objects.create(
code="unique",
- currency="USD",
type=VoucherType.ENTIRE_ORDER,
discount_value_type=discount_value_type,
- discount_value=discount_value,
- min_spent_amount=min_spent_amount,
min_checkout_items_quantity=min_checkout_items_quantity,
)
+ VoucherChannelListing.objects.create(
+ voucher=voucher,
+ channel=channel_USD,
+ discount=Money(50, channel_USD.currency_code),
+ min_spent_amount=min_spent_amount,
+ )
total_price = Money(total, "USD")
with pytest.raises(NotApplicable):
- validate_voucher(voucher, total_price, total_quantity, "[email protected]")
+ validate_voucher(
+ voucher, total_price, total_quantity, "[email protected]", channel_USD
+ )
-def test_validate_voucher_not_applicable_once_per_customer(voucher, customer_user):
+def test_validate_voucher_not_applicable_once_per_customer(
+ voucher, customer_user, channel_USD
+):
voucher.apply_once_per_customer = True
voucher.save()
VoucherCustomer.objects.create(voucher=voucher, customer_email=customer_user.email)
with pytest.raises(NotApplicable):
- validate_voucher(voucher, 0, 0, customer_user.email)
+ validate_voucher(voucher, 0, 0, customer_user.email, channel_USD)
date_time_now = timezone.now()
@@ -322,9 +455,15 @@ date_time_now = timezone.now()
(date_time_now + timedelta(weeks=10), date_time_now, None, True),
),
)
-def test_sale_active(current_date, start_date, end_date, is_active):
- Sale.objects.create(
- type=DiscountValueType.FIXED, value=5, start_date=start_date, end_date=end_date
+def test_sale_active(current_date, start_date, end_date, is_active, channel_USD):
+ sale = Sale.objects.create(
+ type=DiscountValueType.FIXED, start_date=start_date, end_date=end_date
+ )
+ SaleChannelListing.objects.create(
+ sale=sale,
+ currency=channel_USD.currency_code,
+ channel=channel_USD,
+ discount_value=5,
)
sale_is_active = Sale.objects.active(date=current_date).exists()
assert is_active == sale_is_active
@@ -346,3 +485,44 @@ def test_discount_as_negative_for_html():
discount = Money(10, "USD")
result = discount_as_negative(discount, True)
assert result == '-<span class="currency">$</span>10.00'
+
+
+def test_get_fixed_sale_discount(sale):
+ # given
+ sale.type = DiscountValueType.FIXED
+ channel_listing = sale.channel_listings.get()
+
+ # when
+ result = sale.get_discount(channel_listing).keywords
+
+ # then
+ assert result["discount"] == Money(
+ channel_listing.discount_value, channel_listing.currency
+ )
+
+
+def test_get_percentage_sale_discount(sale):
+ # given
+ sale.type = DiscountValueType.PERCENTAGE
+ channel_listing = sale.channel_listings.get()
+
+ # when
+ result = sale.get_discount(channel_listing).keywords
+
+ # then
+ assert result["percentage"] == channel_listing.discount_value
+
+
+def test_get_unknown_sale_discount(sale):
+ sale.type = "unknown"
+ channel_listing = sale.channel_listings.get()
+
+ with pytest.raises(NotImplementedError):
+ sale.get_discount(channel_listing)
+
+
+def test_get_not_applicable_sale_discount(sale, channel_PLN):
+ sale.type = DiscountValueType.PERCENTAGE
+
+ with pytest.raises(NotApplicable):
+ sale.get_discount(None)
diff --git a/saleor/discount/utils.py b/saleor/discount/utils.py
index 300bee71b5..6f86516f46 100644
--- a/saleor/discount/utils.py
+++ b/saleor/discount/utils.py
@@ -6,13 +6,15 @@ from django.db.models import F
from django.utils import timezone
from prices import Money
+from ..channel.models import Channel
from ..checkout import calculations
from ..core.taxes import zero_money
from . import DiscountInfo
-from .models import NotApplicable, Sale, VoucherCustomer
+from .models import NotApplicable, Sale, SaleChannelListing, VoucherCustomer
if TYPE_CHECKING:
# flake8: noqa
+ from ..channel.models import Channel
from ..checkout.models import Checkout, CheckoutLine
from ..order.models import Order
from ..product.models import Collection, Product
@@ -49,7 +51,10 @@ def remove_voucher_usage_by_customer(voucher: "Voucher", customer_email: str) ->
def get_product_discount_on_sale(
- product: "Product", product_collections: Set[int], discount: DiscountInfo
+ product: "Product",
+ product_collections: Set[int],
+ discount: DiscountInfo,
+ channel: "Channel",
):
"""Return discount value if product is on sale or raise NotApplicable."""
is_product_on_sale = (
@@ -58,7 +63,8 @@ def get_product_discount_on_sale(
or product_collections.intersection(discount.collection_ids)
)
if is_product_on_sale:
- return discount.sale.get_discount()
+ sale_channel_listing = discount.channel_listings.get(channel.slug)
+ return discount.sale.get_discount(sale_channel_listing) # type: ignore
raise NotApplicable("Discount not applicable for this product")
@@ -66,13 +72,16 @@ def get_product_discounts(
*,
product: "Product",
collections: Iterable["Collection"],
- discounts: Iterable[DiscountInfo]
+ discounts: Iterable[DiscountInfo],
+ channel: "Channel"
) -> Money:
"""Return discount values for all discounts applicable to a product."""
product_collections = set(pc.id for pc in collections)
for discount in discounts or []:
try:
- yield get_product_discount_on_sale(product, product_collections, discount)
+ yield get_product_discount_on_sale(
+ product, product_collections, discount, channel
+ )
except NotApplicable:
pass
@@ -82,13 +91,17 @@ def calculate_discounted_price(
product: "Product",
price: Money,
collections: Iterable["Collection"],
- discounts: Optional[Iterable[DiscountInfo]]
+ discounts: Optional[Iterable[DiscountInfo]],
+ channel: "Channel"
) -> Money:
"""Return minimum product's price of all prices with discounts applied."""
if discounts:
discount_prices = list(
get_product_discounts(
- product=product, collections=collections, discounts=discounts
+ product=product,
+ collections=collections,
+ discounts=discounts,
+ channel=channel,
)
)
if discount_prices:
@@ -131,7 +144,9 @@ def validate_voucher_for_checkout(
)
customer_email = checkout.get_customer_email()
- validate_voucher(voucher, subtotal.gross, checkout.quantity, customer_email)
+ validate_voucher(
+ voucher, subtotal.gross, checkout.quantity, customer_email, checkout.channel,
+ )
def validate_voucher_in_order(order: "Order"):
@@ -140,33 +155,43 @@ def validate_voucher_in_order(order: "Order"):
customer_email = order.get_customer_email()
if not order.voucher:
return
- validate_voucher(order.voucher, subtotal.gross, quantity, customer_email)
+ validate_voucher(
+ order.voucher, subtotal.gross, quantity, customer_email, order.channel
+ )
def validate_voucher(
- voucher: "Voucher", total_price: Money, quantity: int, customer_email: str
+ voucher: "Voucher",
+ total_price: Money,
+ quantity: int,
+ customer_email: str,
+ channel: Channel,
) -> None:
- voucher.validate_min_spent(total_price)
+ voucher.validate_min_spent(total_price, channel)
voucher.validate_min_checkout_items_quantity(quantity)
if voucher.apply_once_per_customer:
voucher.validate_once_per_customer(customer_email)
-def get_products_voucher_discount(voucher: "Voucher", prices: Iterable[Money]) -> Money:
+def get_products_voucher_discount(
+ voucher: "Voucher", prices: Iterable[Money], channel: Channel
+) -> Money:
"""Calculate discount value for a voucher of product or category type."""
if voucher.apply_once_per_order:
- return voucher.get_discount_amount_for(min(prices))
- discounts = (voucher.get_discount_amount_for(price) for price in prices)
- total_amount = sum(discounts, zero_money(voucher.currency))
+ return voucher.get_discount_amount_for(min(prices), channel)
+ discounts = (voucher.get_discount_amount_for(price, channel) for price in prices)
+ total_amount = sum(discounts, zero_money(channel.currency_code))
return total_amount
-def _fetch_categories(sale_pks: Iterable[str]) -> Dict[int, Set[int]]:
+def fetch_categories(sale_pks: Iterable[str]) -> Dict[int, Set[int]]:
from ..product.models import Category
- categories = Sale.categories.through.objects.filter(
- sale_id__in=sale_pks
- ).values_list("sale_id", "category_id")
+ categories = (
+ Sale.categories.through.objects.filter(sale_id__in=sale_pks)
+ .order_by("id")
+ .values_list("sale_id", "category_id")
+ )
category_map: Dict[int, Set[int]] = defaultdict(set)
for sale_pk, category_pk in categories:
category_map[sale_pk].add(category_pk)
@@ -180,19 +205,23 @@ def _fetch_categories(sale_pks: Iterable[str]) -> Dict[int, Set[int]]:
return subcategory_map
-def _fetch_collections(sale_pks: Iterable[str]) -> Dict[int, Set[int]]:
- collections = Sale.collections.through.objects.filter(
- sale_id__in=sale_pks
- ).values_list("sale_id", "collection_id")
+def fetch_collections(sale_pks: Iterable[str]) -> Dict[int, Set[int]]:
+ collections = (
+ Sale.collections.through.objects.filter(sale_id__in=sale_pks)
+ .order_by("id")
+ .values_list("sale_id", "collection_id")
+ )
collection_map: Dict[int, Set[int]] = defaultdict(set)
for sale_pk, collection_pk in collections:
collection_map[sale_pk].add(collection_pk)
return collection_map
-def _fetch_products(sale_pks: Iterable[str]) -> Dict[int, Set[int]]:
- products = Sale.products.through.objects.filter(sale_id__in=sale_pks).values_list(
- "sale_id", "product_id"
+def fetch_products(sale_pks: Iterable[str]) -> Dict[int, Set[int]]:
+ products = (
+ Sale.products.through.objects.filter(sale_id__in=sale_pks)
+ .order_by("id")
+ .values_list("sale_id", "product_id")
)
product_map: Dict[int, Set[int]] = defaultdict(set)
for sale_pk, product_pk in products:
@@ -200,17 +229,30 @@ def _fetch_products(sale_pks: Iterable[str]) -> Dict[int, Set[int]]:
return product_map
+def fetch_sale_channel_listings(sale_pks: Iterable[str],):
+ channel_listings = SaleChannelListing.objects.filter(sale_id__in=sale_pks).annotate(
+ channel_slug=F("channel__slug")
+ )
+ channel_listings_map: Dict[int, Dict[str, SaleChannelListing]] = defaultdict(dict)
+ for channel_listing in channel_listings:
+ sale_id_row = channel_listings_map[channel_listing.sale_id]
+ sale_id_row[channel_listing.channel_slug] = channel_listing
+ return channel_listings_map
+
+
def fetch_discounts(date: datetime.date) -> List[DiscountInfo]:
sales = list(Sale.objects.active(date))
pks = {s.pk for s in sales}
- collections = _fetch_collections(pks)
- products = _fetch_products(pks)
- categories = _fetch_categories(pks)
+ collections = fetch_collections(pks)
+ channel_listings = fetch_sale_channel_listings(pks)
+ products = fetch_products(pks)
+ categories = fetch_categories(pks)
return [
DiscountInfo(
sale=sale,
category_ids=categories[sale.pk],
+ channel_listings=channel_listings[sale.pk],
collection_ids=collections[sale.pk],
product_ids=products[sale.pk],
)
diff --git a/saleor/giftcard/migrations/0002_auto_20190814_0413.py b/saleor/giftcard/migrations/0002_auto_20190814_0413.py
index 1eed2448c8..7a5b77ab9f 100644
--- a/saleor/giftcard/migrations/0002_auto_20190814_0413.py
+++ b/saleor/giftcard/migrations/0002_auto_20190814_0413.py
@@ -1,5 +1,7 @@
# Generated by Django 2.2.4 on 2019-08-14 09:13
+import os
+
from django.conf import settings
from django.db import migrations, models
@@ -23,7 +25,7 @@ class Migration(migrations.Migration):
model_name="giftcard",
name="currency",
field=models.CharField(
- default=settings.DEFAULT_CURRENCY,
+ default=os.environ.get("DEFAULT_CURRENCY", "USD"),
max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH,
),
),
diff --git a/saleor/giftcard/models.py b/saleor/giftcard/models.py
index b8629c616a..b7749230de 100644
--- a/saleor/giftcard/models.py
+++ b/saleor/giftcard/models.py
@@ -1,3 +1,4 @@
+import os
from datetime import date
from django.conf import settings
@@ -34,7 +35,7 @@ class GiftCard(models.Model):
currency = models.CharField(
max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH,
- default=settings.DEFAULT_CURRENCY,
+ default=os.environ.get("DEFAULT_CURRENCY", "USD"),
)
initial_balance_amount = models.DecimalField(
diff --git a/saleor/graphql/account/filters.py b/saleor/graphql/account/filters.py
index c5b5d8dade..0a4ffee641 100644
--- a/saleor/graphql/account/filters.py
+++ b/saleor/graphql/account/filters.py
@@ -1,9 +1,9 @@
import django_filters
-from django.db.models import Count, Sum
+from django.db.models import Count
from ...account.models import User
from ..core.filters import EnumFilter, ObjectTypeFilter
-from ..core.types.common import DateRangeInput, IntRangeInput, PriceRangeInput
+from ..core.types.common import DateRangeInput, IntRangeInput
from ..utils.filters import filter_by_query_param, filter_range_field
from .enums import StaffMemberStatus
@@ -12,11 +12,6 @@ def filter_date_joined(qs, _, value):
return filter_range_field(qs, "date_joined__date", value)
-def filter_money_spent(qs, _, value):
- qs = qs.annotate(money_spent=Sum("orders__total_gross_amount"))
- return filter_range_field(qs, "money_spent", value)
-
-
def filter_number_of_orders(qs, _, value):
qs = qs.annotate(total_orders=Count("orders"))
return filter_range_field(qs, "total_orders", value)
@@ -61,9 +56,6 @@ class CustomerFilter(django_filters.FilterSet):
date_joined = ObjectTypeFilter(
input_class=DateRangeInput, method=filter_date_joined
)
- money_spent = ObjectTypeFilter(
- input_class=PriceRangeInput, method=filter_money_spent
- )
number_of_orders = ObjectTypeFilter(
input_class=IntRangeInput, method=filter_number_of_orders
)
@@ -76,7 +68,6 @@ class CustomerFilter(django_filters.FilterSet):
model = User
fields = [
"date_joined",
- "money_spent",
"number_of_orders",
"placed_orders",
"search",
diff --git a/saleor/graphql/account/sorters.py b/saleor/graphql/account/sorters.py
index 7c2dcf51f8..17c640cc14 100644
--- a/saleor/graphql/account/sorters.py
+++ b/saleor/graphql/account/sorters.py
@@ -18,7 +18,7 @@ class UserSortField(graphene.Enum):
raise ValueError("Unsupported enum value: %s" % self.value)
@staticmethod
- def qs_with_order_count(queryset: QuerySet) -> QuerySet:
+ def qs_with_order_count(queryset: QuerySet, **_kwargs) -> QuerySet:
return queryset.annotate(order_count=Count("orders__id"))
diff --git a/saleor/graphql/account/tests/test_account.py b/saleor/graphql/account/tests/test_account.py
index 8a43753bd4..3199d45061 100644
--- a/saleor/graphql/account/tests/test_account.py
+++ b/saleor/graphql/account/tests/test_account.py
@@ -13,7 +13,6 @@ from django.core.files import File
from django.core.validators import URLValidator
from django.test import override_settings
from freezegun import freeze_time
-from prices import Money
from ....account import events as account_events
from ....account.error_codes import AccountErrorCode
@@ -608,6 +607,20 @@ def test_me_query_checkout(user_api_client, checkout):
assert data["checkout"]["token"] == str(checkout.token)
+def test_me_query_checkout_with_inactive_channel(user_api_client, checkout):
+ user = user_api_client.user
+ channel = checkout.channel
+ channel.is_active = False
+ channel.save()
+ checkout.user = user
+ checkout.save()
+
+ response = user_api_client.post_graphql(ME_QUERY)
+ content = get_graphql_content(response)
+ data = content["data"]["me"]
+ assert not data["checkout"]
+
+
def test_me_with_cancelled_fulfillments(
user_api_client, fulfilled_order_with_cancelled_fulfillment
):
@@ -3445,11 +3458,12 @@ def test_query_customers_with_filter_placed_orders(
staff_api_client,
permission_manage_users,
customer_user,
+ channel_USD,
):
- Order.objects.create(user=customer_user)
+ Order.objects.create(user=customer_user, channel=channel_USD)
second_customer = User.objects.create(email="[email protected]")
with freeze_time("2012-01-14 11:00:00"):
- Order.objects.create(user=second_customer)
+ Order.objects.create(user=second_customer, channel=channel_USD)
variables = {"filter": customer_filter}
response = staff_api_client.post_graphql(
query_customer_with_filter, variables, permissions=[permission_manage_users]
@@ -3505,60 +3519,18 @@ def test_query_customers_with_filter_placed_orders_(
staff_api_client,
permission_manage_users,
customer_user,
+ channel_USD,
):
Order.objects.bulk_create(
[
- Order(user=customer_user, token=str(uuid.uuid4())),
- Order(user=customer_user, token=str(uuid.uuid4())),
- Order(user=customer_user, token=str(uuid.uuid4())),
+ Order(user=customer_user, token=str(uuid.uuid4()), channel=channel_USD),
+ Order(user=customer_user, token=str(uuid.uuid4()), channel=channel_USD),
+ Order(user=customer_user, token=str(uuid.uuid4()), channel=channel_USD),
]
)
second_customer = User.objects.create(email="[email protected]")
with freeze_time("2012-01-14 11:00:00"):
- Order.objects.create(user=second_customer)
- variables = {"filter": customer_filter}
- response = staff_api_client.post_graphql(
- query_customer_with_filter, variables, permissions=[permission_manage_users]
- )
- content = get_graphql_content(response)
- users = content["data"]["customers"]["edges"]
-
- assert len(users) == count
-
-
- "customer_filter, count",
- [
- ({"moneySpent": {"gte": 16, "lte": 25}}, 1),
- ({"moneySpent": {"gte": 15, "lte": 26}}, 2),
- ({"moneySpent": {"gte": 0}}, 2),
- ({"moneySpent": {"lte": 16}}, 1),
- ],
-)
-def test_query_customers_with_filter_placed_orders__(
- customer_filter,
- count,
- query_customer_with_filter,
- staff_api_client,
- permission_manage_users,
- customer_user,
-):
- second_customer = User.objects.create(email="[email protected]")
- Order.objects.bulk_create(
- [
- Order(
- user=customer_user,
- token=str(uuid.uuid4()),
- total_gross=Money(15, "USD"),
- ),
- Order(
- user=second_customer,
- token=str(uuid.uuid4()),
- total_gross=Money(25, "USD"),
- ),
- ]
- )
-
+ Order.objects.create(user=second_customer, channel=channel_USD)
variables = {"filter": customer_filter}
response = staff_api_client.post_graphql(
query_customer_with_filter, variables, permissions=[permission_manage_users]
@@ -3596,7 +3568,7 @@ QUERY_CUSTOMERS_WITH_SORT = """
],
)
def test_query_customers_with_sort(
- customer_sort, result_order, staff_api_client, permission_manage_users,
+ customer_sort, result_order, staff_api_client, permission_manage_users, channel_USD
):
User.objects.bulk_create(
[
@@ -3623,7 +3595,9 @@ def test_query_customers_with_sort(
),
]
)
- Order.objects.create(user=User.objects.get(email="[email protected]"))
+ Order.objects.create(
+ user=User.objects.get(email="[email protected]"), channel=channel_USD
+ )
variables = {"sort_by": customer_sort}
staff_api_client.user.user_permissions.add(permission_manage_users)
response = staff_api_client.post_graphql(QUERY_CUSTOMERS_WITH_SORT, variables)
@@ -3818,7 +3792,7 @@ QUERY_STAFF_USERS_WITH_SORT = """
],
)
def test_query_staff_members_with_sort(
- customer_sort, result_order, staff_api_client, permission_manage_staff
+ customer_sort, result_order, staff_api_client, permission_manage_staff, channel_USD
):
User.objects.bulk_create(
[
@@ -3845,7 +3819,9 @@ def test_query_staff_members_with_sort(
),
]
)
- Order.objects.create(user=User.objects.get(email="[email protected]"))
+ Order.objects.create(
+ user=User.objects.get(email="[email protected]"), channel=channel_USD
+ )
variables = {"sort_by": customer_sort}
staff_api_client.user.user_permissions.add(permission_manage_staff)
response = staff_api_client.post_graphql(QUERY_STAFF_USERS_WITH_SORT, variables)
diff --git a/saleor/graphql/account/tests/test_pagination.py b/saleor/graphql/account/tests/test_pagination.py
index b74d6995d4..b5150a1c62 100644
--- a/saleor/graphql/account/tests/test_pagination.py
+++ b/saleor/graphql/account/tests/test_pagination.py
@@ -222,8 +222,11 @@ def test_query_customers_pagination_with_sort(
staff_api_client,
permission_manage_users,
customers_for_pagination,
+ channel_USD,
):
- Order.objects.create(user=User.objects.get(email="[email protected]"))
+ Order.objects.create(
+ user=User.objects.get(email="[email protected]"), channel=channel_USD
+ )
page_size = 2
variables = {"first": page_size, "after": None, "sortBy": customer_sort}
staff_api_client.user.user_permissions.add(permission_manage_users)
diff --git a/saleor/graphql/account/types.py b/saleor/graphql/account/types.py
index cc7dedb197..f818d92998 100644
--- a/saleor/graphql/account/types.py
+++ b/saleor/graphql/account/types.py
@@ -252,7 +252,7 @@ class User(CountableDjangoObjectType):
@staticmethod
def resolve_checkout(root: models.User, _info, **_kwargs):
- return get_user_checkout(root)[0]
+ return get_user_checkout(root)
@staticmethod
def resolve_gift_cards(root: models.User, info, **_kwargs):
diff --git a/saleor/graphql/api.py b/saleor/graphql/api.py
index 40a3a0caa5..a2f3a3b99f 100644
--- a/saleor/graphql/api.py
+++ b/saleor/graphql/api.py
@@ -2,6 +2,7 @@ from graphene_federation import build_schema
from .account.schema import AccountMutations, AccountQueries
from .app.schema import AppMutations, AppQueries
+from .channel.schema import ChannelMutations, ChannelQueries
from .checkout.schema import CheckoutMutations, CheckoutQueries
from .core.schema import CoreMutations, CoreQueries
from .csv.schema import CsvMutations, CsvQueries
@@ -25,6 +26,7 @@ from .webhook.schema import WebhookMutations, WebhookQueries
class Query(
AccountQueries,
AppQueries,
+ ChannelQueries,
CheckoutQueries,
CoreQueries,
CsvQueries,
@@ -49,6 +51,7 @@ class Query(
class Mutation(
AccountMutations,
AppMutations,
+ ChannelMutations,
CheckoutMutations,
CoreMutations,
CsvMutations,
diff --git a/saleor/graphql/channel/__init__.py b/saleor/graphql/channel/__init__.py
new file mode 100644
index 0000000000..cabf463fd7
--- /dev/null
+++ b/saleor/graphql/channel/__init__.py
@@ -0,0 +1,18 @@
+from dataclasses import dataclass
+from typing import Generic, Optional, TypeVar
+
+from django.db.models import QuerySet
+
+N = TypeVar("N")
+
+
+@dataclass
+class ChannelContext(Generic[N]):
+ node: N
+ channel_slug: Optional[str]
+
+
+@dataclass
+class ChannelQsContext:
+ qs: QuerySet
+ channel_slug: Optional[str]
diff --git a/saleor/graphql/channel/dataloaders.py b/saleor/graphql/channel/dataloaders.py
new file mode 100644
index 0000000000..15c053715c
--- /dev/null
+++ b/saleor/graphql/channel/dataloaders.py
@@ -0,0 +1,64 @@
+from ...channel.models import Channel
+from ..checkout.dataloaders import CheckoutByIdLoader, CheckoutLineByIdLoader
+from ..core.dataloaders import DataLoader
+from ..order.dataloaders import OrderByIdLoader, OrderLineByIdLoader
+
+
+class ChannelByIdLoader(DataLoader):
+ context_key = "channel_by_id"
+
+ def batch_load(self, keys):
+ channels = Channel.objects.in_bulk(keys)
+ return [channels.get(channel_id) for channel_id in keys]
+
+
+class ChannelBySlugLoader(DataLoader):
+ context_key = "channel_by_slug"
+
+ def batch_load(self, keys):
+ channels = Channel.objects.in_bulk(keys, field_name="slug")
+ return [channels.get(slug) for slug in keys]
+
+
+class ChannelByCheckoutLineIDLoader(DataLoader):
+ context_key = "channel_by_checkout_line"
+
+ def batch_load(self, keys):
+ def channel_by_lines(checkout_lines):
+ checkout_ids = [line.checkout_id for line in checkout_lines]
+
+ def channels_by_checkout(checkouts):
+ channel_ids = [checkout.channel_id for checkout in checkouts]
+
+ return ChannelByIdLoader(self.context).load_many(channel_ids)
+
+ return (
+ CheckoutByIdLoader(self.context)
+ .load_many(checkout_ids)
+ .then(channels_by_checkout)
+ )
+
+ return (
+ CheckoutLineByIdLoader(self.context).load_many(keys).then(channel_by_lines)
+ )
+
+
+class ChannelByOrderLineIdLoader(DataLoader):
+ context_key = "channel_by_orderline"
+
+ def batch_load(self, keys):
+ def channel_by_lines(order_lines):
+ order_ids = [line.order_id for line in order_lines]
+
+ def channels_by_checkout(orders):
+ channel_ids = [order.channel_id for order in orders]
+
+ return ChannelByIdLoader(self.context).load_many(channel_ids)
+
+ return (
+ OrderByIdLoader(self.context)
+ .load_many(order_ids)
+ .then(channels_by_checkout)
+ )
+
+ return OrderLineByIdLoader(self.context).load_many(keys).then(channel_by_lines)
diff --git a/saleor/graphql/channel/filters.py b/saleor/graphql/channel/filters.py
new file mode 100644
index 0000000000..a5f07ec740
--- /dev/null
+++ b/saleor/graphql/channel/filters.py
@@ -0,0 +1,14 @@
+from typing import Dict
+
+from graphql.error import GraphQLError
+
+LACK_OF_CHANNEL_IN_FILTERING_MSG = (
+ "You must provide a `channel` filter parameter to properly filter data."
+)
+
+
+def get_channel_slug_from_filter_data(filter_data: Dict):
+ channel_slug = filter_data.get("channel", None)
+ if not channel_slug:
+ raise GraphQLError(LACK_OF_CHANNEL_IN_FILTERING_MSG)
+ return channel_slug
diff --git a/saleor/graphql/channel/mutations.py b/saleor/graphql/channel/mutations.py
new file mode 100644
index 0000000000..1b713b46fd
--- /dev/null
+++ b/saleor/graphql/channel/mutations.py
@@ -0,0 +1,323 @@
+import datetime
+from typing import DefaultDict, Dict, Iterable, List
+
+import graphene
+from django.core.exceptions import ValidationError
+from django.db import transaction
+from django.utils.text import slugify
+
+from ...channel import models
+from ...checkout.models import Checkout
+from ...core.permissions import ChannelPermissions
+from ...order.models import Order
+from ..core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation
+from ..core.types.common import ChannelError, ChannelErrorCode
+from ..core.utils import get_duplicated_values, get_duplicates_ids
+from ..utils import resolve_global_ids_to_primary_keys
+from .types import Channel
+
+
+class ChannelInput(graphene.InputObjectType):
+ is_active = graphene.Boolean(description="isActive flag.")
+
+
+class ChannelCreateInput(ChannelInput):
+ name = graphene.String(description="Name of the channel.", required=True)
+ slug = graphene.String(description="Slug of the channel.", required=True)
+ currency_code = graphene.String(
+ description="Currency of the channel.", required=True
+ )
+
+
+class ChannelCreate(ModelMutation):
+ class Arguments:
+ input = ChannelCreateInput(
+ required=True, description="Fields required to create channel."
+ )
+
+ class Meta:
+ description = "Creates new channel."
+ model = models.Channel
+ permissions = (ChannelPermissions.MANAGE_CHANNELS,)
+ error_type_class = ChannelError
+ error_type_field = "channel_errors"
+
+ @classmethod
+ def get_type_for_model(cls):
+ return Channel
+
+ @classmethod
+ def clean_input(cls, info, instance, data, input_cls=None):
+ cleaned_input = super().clean_input(info, instance, data)
+ slug = cleaned_input.get("slug")
+ if slug:
+ cleaned_input["slug"] = slugify(slug)
+
+ return cleaned_input
+
+
+class ChannelUpdateInput(ChannelInput):
+ name = graphene.String(description="Name of the channel.")
+ slug = graphene.String(description="Slug of the channel.")
+
+
+class ChannelUpdate(ModelMutation):
+ class Arguments:
+ id = graphene.ID(required=True, description="ID of a channel to update.")
+ input = ChannelUpdateInput(
+ description="Fields required to update a channel.", required=True
+ )
+
+ class Meta:
+ description = "Update a channel."
+ model = models.Channel
+ permissions = (ChannelPermissions.MANAGE_CHANNELS,)
+ error_type_class = ChannelError
+ error_type_field = "channel_errors"
+
+ @classmethod
+ def clean_input(cls, info, instance, data, input_cls=None):
+ cleaned_input = super().clean_input(info, instance, data)
+ slug = cleaned_input.get("slug")
+ if slug:
+ cleaned_input["slug"] = slugify(slug)
+
+ return cleaned_input
+
+
+class ChannelDeleteInput(graphene.InputObjectType):
+ target_channel = graphene.ID(
+ required=True,
+ description="ID of channel to migrate orders from origin channel.",
+ )
+
+
+class ChannelDelete(ModelDeleteMutation):
+ class Arguments:
+ id = graphene.ID(required=True, description="ID of a channel to delete.")
+ input = ChannelDeleteInput(
+ required=True, description="Fields required to delete a channel."
+ )
+
+ class Meta:
+ description = (
+ "Delete a channel. Orders associated with the deleted "
+ "channel will be moved to the target channel. "
+ "Checkouts, product availability, and pricing will be removed."
+ )
+ model = models.Channel
+ permissions = (ChannelPermissions.MANAGE_CHANNELS,)
+ error_type_class = ChannelError
+ error_type_field = "channel_errors"
+
+ @classmethod
+ def validate_input(cls, origin_channel, target_channel):
+ if origin_channel.id == target_channel.id:
+ raise ValidationError(
+ {
+ "target_channel": ValidationError(
+ "channelID and targetChannelID cannot be the same. "
+ "Use different target channel ID.",
+ code=ChannelErrorCode.CHANNEL_TARGET_ID_MUST_BE_DIFFERENT,
+ )
+ }
+ )
+ origin_channel_currency = origin_channel.currency_code
+ target_channel_currency = target_channel.currency_code
+ if origin_channel_currency != target_channel_currency:
+ raise ValidationError(
+ {
+ "target_channel": ValidationError(
+ f"Cannot migrate from {origin_channel_currency} "
+ f"to {target_channel_currency}. "
+ "Migration are allowed between the same currency",
+ code=ChannelErrorCode.CHANNELS_CURRENCY_MUST_BE_THE_SAME,
+ )
+ }
+ )
+
+ @classmethod
+ def perform_delete(cls, origin_channel, target_channel):
+ cls.validate_input(origin_channel, target_channel)
+
+ with transaction.atomic():
+ origin_channel_id = origin_channel.id
+ cls.migrate_orders_to_target_channel(origin_channel_id, target_channel.id)
+ cls.delete_checkouts(origin_channel_id)
+
+ @classmethod
+ def migrate_orders_to_target_channel(cls, origin_channel, target_channel):
+ Order.objects.select_for_update().filter(channel_id=origin_channel).update(
+ channel=target_channel
+ )
+
+ @classmethod
+ def delete_checkouts(cls, origin_channel):
+ Checkout.objects.select_for_update().filter(channel_id=origin_channel).delete()
+
+ @classmethod
+ def perform_mutation(cls, _root, info, **data):
+ origin_channel = cls.get_node_or_error(info, data["id"], only_type=Channel)
+ target_channel = cls.get_node_or_error(
+ info, data["input"]["target_channel"], only_type=Channel
+ )
+
+ cls.perform_delete(origin_channel, target_channel)
+
+ return super().perform_mutation(_root, info, **data)
+
+
+ErrorType = DefaultDict[str, List[ValidationError]]
+
+
+class BaseChannelListingMutation(BaseMutation):
+ """Base channel listing mutation with basic channel validation."""
+
+ class Meta:
+ abstract = True
+
+ @classmethod
+ def validate_duplicated_channel_ids(
+ cls,
+ add_channels_ids: Iterable[str],
+ remove_channels_ids: Iterable[str],
+ errors: ErrorType,
+ error_code,
+ ):
+ duplicated_ids = get_duplicates_ids(add_channels_ids, remove_channels_ids)
+ if duplicated_ids:
+ error_msg = (
+ "The same object cannot be in both lists "
+ "for adding and removing items."
+ )
+ errors["input"].append(
+ ValidationError(
+ error_msg,
+ code=error_code,
+ params={"channels": list(duplicated_ids)},
+ )
+ )
+
+ @classmethod
+ def validate_duplicated_channel_values(
+ cls, channels_ids: Iterable[str], field_name: str, errors: ErrorType, error_code
+ ):
+ duplicates = get_duplicated_values(channels_ids)
+ if duplicates:
+ errors[field_name].append(
+ ValidationError(
+ "Duplicated channel ID.",
+ code=error_code,
+ params={"channels": duplicates},
+ )
+ )
+
+ @classmethod
+ def clean_channels(cls, info, input, errors: ErrorType, error_code) -> Dict:
+ add_channels = input.get("add_channels", [])
+ add_channels_ids = [channel["channel_id"] for channel in add_channels]
+ remove_channels_ids = input.get("remove_channels", [])
+ cls.validate_duplicated_channel_ids(
+ add_channels_ids, remove_channels_ids, errors, error_code
+ )
+ cls.validate_duplicated_channel_values(
+ add_channels_ids, "add_channels", errors, error_code
+ )
+ cls.validate_duplicated_channel_values(
+ remove_channels_ids, "remove_channels", errors, error_code
+ )
+
+ if errors:
+ return {}
+ channels_to_add: List["models.Channel"] = []
+ if add_channels_ids:
+ channels_to_add = cls.get_nodes_or_error( # type: ignore
+ add_channels_ids, "channel_id", Channel
+ )
+ _, remove_channels_pks = resolve_global_ids_to_primary_keys(
+ remove_channels_ids, Channel
+ )
+
+ cleaned_input = {"add_channels": [], "remove_channels": remove_channels_pks}
+
+ for channel_listing, channel in zip(add_channels, channels_to_add):
+ channel_listing["channel"] = channel
+ cleaned_input["add_channels"].append(channel_listing)
+
+ return cleaned_input
+
+ @classmethod
+ def clean_publication_date(cls, cleaned_input):
+ for add_channel in cleaned_input.get("add_channels", []):
+ is_published = add_channel.get("is_published")
+ publication_date = add_channel.get("publication_date")
+ if is_published and not publication_date:
+ add_channel["publication_date"] = datetime.date.today()
+
+
+class ChannelActivate(BaseMutation):
+ channel = graphene.Field(Channel, description="Activated channel.")
+
+ class Arguments:
+ id = graphene.ID(required=True, description="ID of the channel to activate.")
+
+ class Meta:
+ description = "Activate a channel."
+ permissions = (ChannelPermissions.MANAGE_CHANNELS,)
+ error_type_class = ChannelError
+ error_type_field = "channel_errors"
+
+ @classmethod
+ def clean_channel_availability(cls, channel):
+ if channel.is_active:
+ raise ValidationError(
+ {
+ "id": ValidationError(
+ "This channel is already activated.",
+ code=ChannelErrorCode.INVALID,
+ )
+ }
+ )
+
+ @classmethod
+ def perform_mutation(cls, _root, info, **data):
+ channel = cls.get_node_or_error(info, data["id"], only_type=Channel)
+ cls.clean_channel_availability(channel)
+ channel.is_active = True
+ channel.save(update_fields=["is_active"])
+
+ return ChannelActivate(channel=channel)
+
+
+class ChannelDeactivate(BaseMutation):
+ channel = graphene.Field(Channel, description="Deactivated channel.")
+
+ class Arguments:
+ id = graphene.ID(required=True, description="ID of the channel to deactivate.")
+
+ class Meta:
+ description = "Deactivate a channel."
+ permissions = (ChannelPermissions.MANAGE_CHANNELS,)
+ error_type_class = ChannelError
+ error_type_field = "channel_errors"
+
+ @classmethod
+ def clean_channel_availability(cls, channel):
+ if channel.is_active is False:
+ raise ValidationError(
+ {
+ "id": ValidationError(
+ "This channel is already deactivated.",
+ code=ChannelErrorCode.INVALID,
+ )
+ }
+ )
+
+ @classmethod
+ def perform_mutation(cls, _root, info, **data):
+ channel = cls.get_node_or_error(info, data["id"], only_type=Channel)
+ cls.clean_channel_availability(channel)
+ channel.is_active = False
+ channel.save(update_fields=["is_active"])
+
+ return ChannelDeactivate(channel=channel)
diff --git a/saleor/graphql/channel/resolvers.py b/saleor/graphql/channel/resolvers.py
new file mode 100644
index 0000000000..d0b8c68386
--- /dev/null
+++ b/saleor/graphql/channel/resolvers.py
@@ -0,0 +1,12 @@
+import graphene
+
+from ...channel import models
+from .types import Channel
+
+
+def resolve_channel(info, id):
+ return graphene.Node.get_node_from_global_id(info, id, Channel)
+
+
+def resolve_channels():
+ return models.Channel.objects.all()
diff --git a/saleor/graphql/channel/schema.py b/saleor/graphql/channel/schema.py
new file mode 100644
index 0000000000..f3740df1e1
--- /dev/null
+++ b/saleor/graphql/channel/schema.py
@@ -0,0 +1,40 @@
+import graphene
+
+from ...core.permissions import ChannelPermissions
+from ..decorators import permission_required
+from .mutations import (
+ ChannelActivate,
+ ChannelCreate,
+ ChannelDeactivate,
+ ChannelDelete,
+ ChannelUpdate,
+)
+from .resolvers import resolve_channel, resolve_channels
+from .types import Channel
+
+
+class ChannelQueries(graphene.ObjectType):
+ channel = graphene.Field(
+ Channel,
+ id=graphene.Argument(graphene.ID, description="ID of the channel."),
+ description="Look up a channel by ID.",
+ )
+ channels = graphene.List(
+ graphene.NonNull(Channel), description="List of all channels."
+ )
+
+ @permission_required(ChannelPermissions.MANAGE_CHANNELS)
+ def resolve_channel(self, info, id=None, **kwargs):
+ return resolve_channel(info, id)
+
+ @permission_required(ChannelPermissions.MANAGE_CHANNELS)
+ def resolve_channels(self, _info, **kwargs):
+ return resolve_channels()
+
+
+class ChannelMutations(graphene.ObjectType):
+ channel_create = ChannelCreate.Field()
+ channel_update = ChannelUpdate.Field()
+ channel_delete = ChannelDelete.Field()
+ channel_activate = ChannelActivate.Field()
+ channel_deactivate = ChannelDeactivate.Field()
diff --git a/saleor/graphql/channel/sorters.py b/saleor/graphql/channel/sorters.py
new file mode 100644
index 0000000000..bbd782b886
--- /dev/null
+++ b/saleor/graphql/channel/sorters.py
@@ -0,0 +1,8 @@
+from graphql.error import GraphQLError
+
+LACK_OF_CHANNEL_IN_SORTING_MSG = "You must provide a `channel` as a sorting parameter."
+
+
+def validate_channel_slug(channel_slug: str):
+ if not channel_slug:
+ raise GraphQLError(LACK_OF_CHANNEL_IN_SORTING_MSG)
diff --git a/saleor/data_feeds/tests/__init__.py b/saleor/graphql/channel/tests/__init__.py
similarity index 100%
rename from saleor/data_feeds/tests/__init__.py
rename to saleor/graphql/channel/tests/__init__.py
diff --git a/saleor/graphql/channel/tests/fixtures.py b/saleor/graphql/channel/tests/fixtures.py
new file mode 100644
index 0000000000..cfbe3ec7f5
--- /dev/null
+++ b/saleor/graphql/channel/tests/fixtures.py
@@ -0,0 +1,26 @@
+import pytest
+from django.conf import settings
+
+from ....channel.models import Channel
+
+
+def channel_USD(db):
+ slug = settings.DEFAULT_CHANNEL_SLUG
+ return Channel.objects.create(
+ name="Main Channel", slug=slug, currency_code="USD", is_active=True
+ )
+
+
+def other_channel_USD(db):
+ return Channel.objects.create(
+ name="Other Channel USD", slug="other-usd", currency_code="USD", is_active=True
+ )
+
+
+def channel_PLN(db):
+ return Channel.objects.create(
+ name="Channel PLN", slug="c-pln", currency_code="PLN", is_active=True
+ )
diff --git a/saleor/graphql/channel/tests/test_base_channel_listing.py b/saleor/graphql/channel/tests/test_base_channel_listing.py
new file mode 100644
index 0000000000..15be608134
--- /dev/null
+++ b/saleor/graphql/channel/tests/test_base_channel_listing.py
@@ -0,0 +1,129 @@
+from collections import defaultdict
+
+import graphene
+
+from ....shipping.error_codes import ShippingErrorCode
+from ..mutations import BaseChannelListingMutation
+
+
+def test_validate_duplicated_channel_ids(channel_PLN, channel_USD):
+ # given
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ second_channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ errors = defaultdict(list)
+
+ # when
+ result = BaseChannelListingMutation.validate_duplicated_channel_ids(
+ [channel_id],
+ [second_channel_id],
+ errors,
+ ShippingErrorCode.DUPLICATED_INPUT_ITEM.value,
+ )
+
+ # then
+ assert result is None
+ assert errors["input"] == []
+
+
+def test_validate_duplicated_channel_ids_with_duplicates(channel_PLN):
+ # given
+ channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ second_channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ error_code = ShippingErrorCode.DUPLICATED_INPUT_ITEM.value
+ errors = defaultdict(list)
+
+ # when
+ result = BaseChannelListingMutation.validate_duplicated_channel_ids(
+ [channel_id], [second_channel_id], errors, error_code
+ )
+
+ # then
+ assert result is None
+ assert errors["input"][0].code == error_code
+
+
+def test_validate_duplicated_channel_values(channel_PLN, channel_USD):
+ # given
+ channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ second_channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ error_code = ShippingErrorCode.DUPLICATED_INPUT_ITEM.value
+ errors = defaultdict(list)
+ field = "add_channels"
+
+ # when
+ result = BaseChannelListingMutation.validate_duplicated_channel_values(
+ [channel_id, second_channel_id], field, errors, error_code
+ )
+
+ # then
+ assert result is None
+ assert errors[field] == []
+
+
+def test_validate_duplicated_channel_values_with_duplicates(channel_PLN):
+ # given
+ channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ second_channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ error_code = ShippingErrorCode.DUPLICATED_INPUT_ITEM.value
+ errors = defaultdict(list)
+ field = "add_channels"
+
+ # when
+ result = BaseChannelListingMutation.validate_duplicated_channel_values(
+ [channel_id, second_channel_id], field, errors, error_code
+ )
+
+ # then
+ assert result is None
+ assert errors[field][0].code == error_code
+
+
+def test_clean_channels_add_channels(channel_PLN):
+ # given
+ channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ error_code = ShippingErrorCode.DUPLICATED_INPUT_ITEM.value
+ errors = defaultdict(list)
+
+ # when
+ result = BaseChannelListingMutation.clean_channels(
+ None, {"add_channels": [{"channel_id": channel_id}]}, errors, error_code
+ )
+
+ # then
+ assert result == {
+ "add_channels": [{"channel_id": channel_id, "channel": channel_PLN}],
+ "remove_channels": [],
+ }
+ assert errors["input"] == []
+
+
+def test_clean_channels_remove_channels(channel_PLN):
+ # given
+ channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ error_code = ShippingErrorCode.DUPLICATED_INPUT_ITEM.value
+ errors = defaultdict(list)
+
+ # when
+ result = BaseChannelListingMutation.clean_channels(
+ None, {"remove_channels": [channel_id]}, errors, error_code
+ )
+
+ # then
+ assert result == {"add_channels": [], "remove_channels": [str(channel_PLN.id)]}
+ assert errors["input"] == []
+
+
+def test_test_clean_channels_with_errors(channel_PLN):
+ # given
+ channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ error_code = ShippingErrorCode.DUPLICATED_INPUT_ITEM.value
+ errors = defaultdict(list)
+
+ # when
+ result = BaseChannelListingMutation.clean_channels(
+ None, {"remove_channels": [channel_id, channel_id]}, errors, error_code
+ )
+
+ # then
+ assert result == {}
+ assert errors["remove_channels"][0].code == error_code
diff --git a/saleor/graphql/channel/tests/test_channel_availability.py b/saleor/graphql/channel/tests/test_channel_availability.py
new file mode 100644
index 0000000000..e284dbd4cc
--- /dev/null
+++ b/saleor/graphql/channel/tests/test_channel_availability.py
@@ -0,0 +1,129 @@
+import graphene
+
+from ....channel.error_codes import ChannelErrorCode
+from ...tests.utils import get_graphql_content
+
+CHANNEL_ACTIVATE_MUTATION = """
+ mutation ActivateChannel($id: ID!) {
+ channelActivate(id: $id){
+ channel {
+ id
+ name
+ isActive
+ }
+ channelErrors{
+ field
+ code
+ message
+ }
+ }
+ }
+"""
+
+
+def test_channel_activate_mutation(
+ permission_manage_channels, staff_api_client, channel_USD
+):
+ # given
+ channel_USD.is_active = False
+ channel_USD.save()
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+
+ variables = {"id": channel_id}
+ # when
+ response = staff_api_client.post_graphql(
+ CHANNEL_ACTIVATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_channels,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["channelActivate"]
+ assert not data["channelErrors"]
+ assert data["channel"]["name"] == channel_USD.name
+ assert data["channel"]["isActive"] is True
+
+
+def test_channel_activate_mutation_on_activated_channel(
+ permission_manage_channels, staff_api_client, channel_USD
+):
+ # given
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+
+ variables = {"id": channel_id}
+ # when
+ response = staff_api_client.post_graphql(
+ CHANNEL_ACTIVATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_channels,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["channelActivate"]
+ assert data["channelErrors"][0]["field"] == "id"
+ assert data["channelErrors"][0]["code"] == ChannelErrorCode.INVALID.name
+
+
+CHANNEL_DEACTIVATE_MUTATION = """
+ mutation DeactivateChannel($id: ID!) {
+ channelDeactivate(id: $id){
+ channel {
+ id
+ name
+ isActive
+ }
+ channelErrors{
+ field
+ code
+ message
+ }
+ }
+ }
+"""
+
+
+def test_channel_deactivate_mutation(
+ permission_manage_channels, staff_api_client, channel_USD
+):
+ # given
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+
+ variables = {"id": channel_id}
+ # when
+ response = staff_api_client.post_graphql(
+ CHANNEL_DEACTIVATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_channels,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["channelDeactivate"]
+ assert not data["channelErrors"]
+ assert data["channel"]["name"] == channel_USD.name
+ assert data["channel"]["isActive"] is False
+
+
+def test_channel_deactivate_mutation_on_deactivated_channel(
+ permission_manage_channels, staff_api_client, channel_USD
+):
+ # given
+ channel_USD.is_active = False
+ channel_USD.save()
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+
+ variables = {"id": channel_id}
+ # when
+ response = staff_api_client.post_graphql(
+ CHANNEL_DEACTIVATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_channels,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["channelDeactivate"]
+ assert data["channelErrors"][0]["field"] == "id"
+ assert data["channelErrors"][0]["code"] == ChannelErrorCode.INVALID.name
diff --git a/saleor/graphql/channel/tests/test_channel_create_mutations.py b/saleor/graphql/channel/tests/test_channel_create_mutations.py
new file mode 100644
index 0000000000..82cc50309d
--- /dev/null
+++ b/saleor/graphql/channel/tests/test_channel_create_mutations.py
@@ -0,0 +1,154 @@
+from django.utils.text import slugify
+
+from ....channel.error_codes import ChannelErrorCode
+from ....channel.models import Channel
+from ...tests.utils import assert_no_permission, get_graphql_content
+
+CHANNEL_CREATE_MUTATION = """
+ mutation CreateChannel($input: ChannelCreateInput!){
+ channelCreate(input: $input){
+ channel{
+ id
+ name
+ slug
+ currencyCode
+ }
+ channelErrors{
+ field
+ code
+ message
+ }
+ }
+ }
+"""
+
+
+def test_channel_create_mutation_as_staff_user(
+ permission_manage_channels, staff_api_client,
+):
+ # given
+ name = "testName"
+ slug = "test_slug"
+ currency_code = "USD"
+ variables = {"input": {"name": name, "slug": slug, "currencyCode": currency_code}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ CHANNEL_CREATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_channels,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["channelCreate"]
+ assert not data["channelErrors"]
+ channel_data = data["channel"]
+ channel = Channel.objects.get()
+ assert channel_data["name"] == channel.name == name
+ assert channel_data["slug"] == channel.slug == slug
+ assert channel_data["currencyCode"] == channel.currency_code == currency_code
+
+
+def test_channel_create_mutation_as_app(
+ permission_manage_channels, app_api_client,
+):
+ # given
+ name = "testName"
+ slug = "test_slug"
+ currency_code = "USD"
+ variables = {"input": {"name": name, "slug": slug, "currencyCode": currency_code}}
+
+ # when
+ response = app_api_client.post_graphql(
+ CHANNEL_CREATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_channels,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["channelCreate"]
+ assert not data["channelErrors"]
+ channel_data = data["channel"]
+ channel = Channel.objects.get()
+ assert channel_data["name"] == channel.name == name
+ assert channel_data["slug"] == channel.slug == slug
+ assert channel_data["currencyCode"] == channel.currency_code == currency_code
+
+
+def test_channel_create_mutation_as_customer(user_api_client):
+ # given
+ name = "testName"
+ slug = "test_slug"
+ currency_code = "USD"
+ variables = {"input": {"name": name, "slug": slug, "currencyCode": currency_code}}
+
+ # when
+ response = user_api_client.post_graphql(
+ CHANNEL_CREATE_MUTATION, variables=variables, permissions=(),
+ )
+
+ # then
+ assert_no_permission(response)
+
+
+def test_channel_create_mutation_as_anonymous(api_client):
+ # given
+ name = "testName"
+ slug = "test_slug"
+ currency_code = "USD"
+ variables = {"input": {"name": name, "slug": slug, "currencyCode": currency_code}}
+
+ # when
+ response = api_client.post_graphql(
+ CHANNEL_CREATE_MUTATION, variables=variables, permissions=(),
+ )
+
+ # then
+ assert_no_permission(response)
+
+
+def test_channel_create_mutation_slugify_slug_field(
+ permission_manage_channels, staff_api_client,
+):
+ # given
+ name = "testName"
+ slug = "Invalid slug"
+ currency_code = "USD"
+ variables = {"input": {"name": name, "slug": slug, "currencyCode": currency_code}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ CHANNEL_CREATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_channels,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ channel_data = content["data"]["channelCreate"]["channel"]
+ assert channel_data["slug"] == slugify(slug)
+
+
+def test_channel_create_mutation_with_duplicated_slug(
+ permission_manage_channels, staff_api_client, channel_USD
+):
+ # given
+ name = "New Channel"
+ slug = channel_USD.slug
+ currency_code = "USD"
+ variables = {"input": {"name": name, "slug": slug, "currencyCode": currency_code}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ CHANNEL_CREATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_channels,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ error = content["data"]["channelCreate"]["channelErrors"][0]
+ assert error["field"] == "slug"
+ assert error["code"] == ChannelErrorCode.UNIQUE.name
diff --git a/saleor/graphql/channel/tests/test_channel_delete_mutations.py b/saleor/graphql/channel/tests/test_channel_delete_mutations.py
new file mode 100644
index 0000000000..817fd6aa7f
--- /dev/null
+++ b/saleor/graphql/channel/tests/test_channel_delete_mutations.py
@@ -0,0 +1,161 @@
+import graphene
+
+from ....channel.error_codes import ChannelErrorCode
+from ....checkout.models import Checkout
+from ...tests.utils import assert_no_permission, get_graphql_content
+
+CHANNEL_DELETE_MUTATION = """
+ mutation deleteChannel($id: ID!,$input: ChannelDeleteInput!){
+ channelDelete(id: $id, input: $input){
+ channel{
+ id
+ name
+ slug
+ currencyCode
+ }
+ channelErrors{
+ field
+ code
+ message
+ }
+ }
+ }
+"""
+
+
+def test_channel_delete_mutation_as_staff_user(
+ order_list,
+ checkout,
+ permission_manage_channels,
+ staff_api_client,
+ channel_USD,
+ other_channel_USD,
+ product,
+):
+ # given
+ order = order_list[0]
+ order.channel = channel_USD
+ order.save()
+
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ channel_target_id = graphene.Node.to_global_id("Channel", other_channel_USD.id)
+ variables = {"id": channel_id, "input": {"targetChannel": channel_target_id}}
+ assert Checkout.objects.first() is not None
+ # when
+ response = staff_api_client.post_graphql(
+ CHANNEL_DELETE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_channels,),
+ )
+ get_graphql_content(response)
+ order.refresh_from_db()
+
+ assert order.channel == other_channel_USD
+ assert Checkout.objects.first() is None
+
+
+def test_channel_delete_mutation_with_the_same_channel_and_target_channel_id(
+ permission_manage_channels, staff_api_client, channel_USD
+):
+ # given
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {"id": channel_id, "input": {"targetChannel": channel_id}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ CHANNEL_DELETE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_channels,),
+ )
+ content = get_graphql_content(response)
+ error = content["data"]["channelDelete"]["channelErrors"][0]
+
+ assert error["field"] == "targetChannel"
+ assert error["code"] == ChannelErrorCode.CHANNEL_TARGET_ID_MUST_BE_DIFFERENT.name
+
+
+def test_channel_delete_mutation_with_different_currency(
+ permission_manage_channels, staff_api_client, channel_USD, channel_PLN
+):
+ # given
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ target_channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ variables = {"id": channel_id, "input": {"targetChannel": target_channel_id}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ CHANNEL_DELETE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_channels,),
+ )
+ content = get_graphql_content(response)
+ error = content["data"]["channelDelete"]["channelErrors"][0]
+
+ assert error["field"] == "targetChannel"
+ assert error["code"] == ChannelErrorCode.CHANNELS_CURRENCY_MUST_BE_THE_SAME.name
+
+
+def test_channel_delete_mutation_as_app(
+ permission_manage_channels,
+ app_api_client,
+ order_list,
+ channel_USD,
+ other_channel_USD,
+ checkout,
+):
+ # given
+ order = order_list[0]
+ order.channel = channel_USD
+ order.save()
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ channel_target_id = graphene.Node.to_global_id("Channel", other_channel_USD.id)
+ variables = {"id": channel_id, "input": {"targetChannel": channel_target_id}}
+ assert Checkout.objects.first() is not None
+
+ # when
+ response = app_api_client.post_graphql(
+ CHANNEL_DELETE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_channels,),
+ )
+
+ get_graphql_content(response)
+ order.refresh_from_db()
+
+ # then
+ assert order.channel == other_channel_USD
+ assert Checkout.objects.first() is None
+
+
+def test_channel_delete_mutation_as_customer(
+ user_api_client, channel_USD, other_channel_USD
+):
+ # given
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ channel_target_id = graphene.Node.to_global_id("Channel", other_channel_USD.id)
+ variables = {"id": channel_id, "input": {"targetChannel": channel_target_id}}
+
+ # when
+ response = user_api_client.post_graphql(
+ CHANNEL_DELETE_MUTATION, variables=variables, permissions=(),
+ )
+
+ # then
+ assert_no_permission(response)
+
+
+def test_channel_delete_mutation_as_anonymous(
+ api_client, channel_USD, other_channel_USD
+):
+ # given
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ channel_target_id = graphene.Node.to_global_id("Channel", other_channel_USD.id)
+ variables = {"id": channel_id, "input": {"targetChannel": channel_target_id}}
+
+ # when
+ response = api_client.post_graphql(
+ CHANNEL_DELETE_MUTATION, variables=variables, permissions=(),
+ )
+
+ # then
+ assert_no_permission(response)
diff --git a/saleor/graphql/channel/tests/test_channel_queries.py b/saleor/graphql/channel/tests/test_channel_queries.py
new file mode 100644
index 0000000000..260c6cda22
--- /dev/null
+++ b/saleor/graphql/channel/tests/test_channel_queries.py
@@ -0,0 +1,161 @@
+import graphene
+
+from ...tests.utils import assert_no_permission, get_graphql_content
+
+QUERY_CHANNELS = """
+query {
+ channels {
+ name
+ slug
+ currencyCode
+ }
+}
+"""
+
+
+def test_query_channels_as_staff_user(
+ staff_api_client, permission_manage_channels, channel_USD, channel_PLN
+):
+ # given
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_CHANNELS, {}, permissions=(permission_manage_channels,)
+ )
+ content = get_graphql_content(response)
+
+ # then
+ channels = content["data"]["channels"]
+ assert len(channels) == 2
+ assert {
+ "slug": channel_PLN.slug,
+ "name": channel_PLN.name,
+ "currencyCode": channel_PLN.currency_code,
+ } in channels
+ assert {
+ "slug": channel_USD.slug,
+ "name": channel_USD.name,
+ "currencyCode": channel_USD.currency_code,
+ } in channels
+
+
+def test_query_channels_as_app(
+ app_api_client, permission_manage_channels, channel_USD, channel_PLN
+):
+ # given
+
+ # when
+ response = app_api_client.post_graphql(
+ QUERY_CHANNELS, {}, permissions=(permission_manage_channels,)
+ )
+ content = get_graphql_content(response)
+
+ # then
+ channels = content["data"]["channels"]
+ assert len(channels) == 2
+ assert {
+ "slug": channel_PLN.slug,
+ "name": channel_PLN.name,
+ "currencyCode": channel_PLN.currency_code,
+ } in channels
+ assert {
+ "slug": channel_USD.slug,
+ "name": channel_USD.name,
+ "currencyCode": channel_USD.currency_code,
+ } in channels
+
+
+def test_query_channels_as_customer(user_api_client, channel_USD, channel_PLN):
+ # given
+
+ # when
+ response = user_api_client.post_graphql(QUERY_CHANNELS, {})
+
+ # then
+ assert_no_permission(response)
+
+
+def test_query_channels_as_anonymous(api_client, channel_USD, channel_PLN):
+ # given
+
+ # when
+ response = api_client.post_graphql(QUERY_CHANNELS, {})
+
+ # then
+ assert_no_permission(response)
+
+
+QUERY_CHANNEL = """
+query getChannel($id: ID!){
+ channel(id: $id){
+ id
+ name
+ slug
+ currencyCode
+ }
+}
+"""
+
+
+def test_query_channel_as_staff_user(
+ staff_api_client, permission_manage_channels, channel_USD
+):
+ # given
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {"id": channel_id}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_CHANNEL, variables, permissions=(permission_manage_channels,)
+ )
+ content = get_graphql_content(response)
+
+ # then
+ channel_data = content["data"]["channel"]
+ assert channel_data["id"] == channel_id
+ assert channel_data["name"] == channel_USD.name
+ assert channel_data["slug"] == channel_USD.slug
+ assert channel_data["currencyCode"] == channel_USD.currency_code
+
+
+def test_query_channel_as_app(app_api_client, permission_manage_channels, channel_USD):
+ # given
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {"id": channel_id}
+
+ # when
+ response = app_api_client.post_graphql(
+ QUERY_CHANNEL, variables, permissions=(permission_manage_channels,)
+ )
+ content = get_graphql_content(response)
+
+ # then
+ channel_data = content["data"]["channel"]
+ assert channel_data["id"] == channel_id
+ assert channel_data["name"] == channel_USD.name
+ assert channel_data["slug"] == channel_USD.slug
+ assert channel_data["currencyCode"] == channel_USD.currency_code
+
+
+def test_query_channel_as_customer(user_api_client, channel_USD):
+ # given
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {"id": channel_id}
+
+ # when
+ response = user_api_client.post_graphql(QUERY_CHANNEL, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_query_channel_as_anonymous(api_client, channel_USD):
+ # given
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {"id": channel_id}
+
+ # when
+ response = api_client.post_graphql(QUERY_CHANNEL, variables)
+
+ # then
+ assert_no_permission(response)
diff --git a/saleor/graphql/channel/tests/test_channel_update_mutations.py b/saleor/graphql/channel/tests/test_channel_update_mutations.py
new file mode 100644
index 0000000000..5463781a79
--- /dev/null
+++ b/saleor/graphql/channel/tests/test_channel_update_mutations.py
@@ -0,0 +1,208 @@
+import graphene
+from django.utils.text import slugify
+
+from ....channel.error_codes import ChannelErrorCode
+from ...tests.utils import assert_no_permission, get_graphql_content
+
+CHANNEL_UPDATE_MUTATION = """
+ mutation UpdateChannel($id: ID!,$input: ChannelUpdateInput!){
+ channelUpdate(id: $id, input: $input){
+ channel{
+ id
+ name
+ slug
+ currencyCode
+ }
+ channelErrors{
+ field
+ code
+ message
+ }
+ }
+ }
+"""
+
+
+def test_channel_update_mutation_as_staff_user(
+ permission_manage_channels, staff_api_client, channel_USD
+):
+ # given
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ name = "newName"
+ slug = "new_slug"
+ variables = {"id": channel_id, "input": {"name": name, "slug": slug}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ CHANNEL_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_channels,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["channelUpdate"]
+ assert not data["channelErrors"]
+ channel_data = data["channel"]
+ channel_USD.refresh_from_db()
+ assert channel_data["name"] == channel_USD.name == name
+ assert channel_data["slug"] == channel_USD.slug == slug
+ assert channel_data["currencyCode"] == channel_USD.currency_code == "USD"
+
+
+def test_channel_update_mutation_as_app(
+ permission_manage_channels, app_api_client, channel_USD
+):
+ # given
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ name = "newName"
+ slug = "new_slug"
+ variables = {"id": channel_id, "input": {"name": name, "slug": slug}}
+
+ # when
+ response = app_api_client.post_graphql(
+ CHANNEL_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_channels,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["channelUpdate"]
+ assert not data["channelErrors"]
+ channel_data = data["channel"]
+ channel_USD.refresh_from_db()
+ assert channel_data["name"] == channel_USD.name == name
+ assert channel_data["slug"] == channel_USD.slug == slug
+ assert channel_data["currencyCode"] == channel_USD.currency_code == "USD"
+
+
+def test_channel_update_mutation_as_customer(user_api_client, channel_USD):
+ # given
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ name = "newName"
+ slug = "new_slug"
+ variables = {"id": channel_id, "input": {"name": name, "slug": slug}}
+
+ # when
+ response = user_api_client.post_graphql(
+ CHANNEL_UPDATE_MUTATION, variables=variables, permissions=(),
+ )
+
+ # then
+ assert_no_permission(response)
+
+
+def test_channel_update_mutation_as_anonymous(api_client, channel_USD):
+ # given
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ name = "newName"
+ slug = "new_slug"
+ variables = {"id": channel_id, "input": {"name": name, "slug": slug}}
+
+ # when
+ response = api_client.post_graphql(
+ CHANNEL_UPDATE_MUTATION, variables=variables, permissions=(),
+ )
+
+ # then
+ assert_no_permission(response)
+
+
+def test_channel_update_mutation_slugify_slug_field(
+ permission_manage_channels, staff_api_client, channel_USD
+):
+ # given
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ name = "testName"
+ slug = "Invalid slug"
+ variables = {"id": channel_id, "input": {"name": name, "slug": slug}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ CHANNEL_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_channels,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ channel_data = content["data"]["channelUpdate"]["channel"]
+ assert channel_data["slug"] == slugify(slug)
+
+
+def test_channel_update_mutation_with_duplicated_slug(
+ permission_manage_channels, staff_api_client, channel_USD, channel_PLN
+):
+ # given
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ name = "New Channel"
+ slug = channel_PLN.slug
+ variables = {"id": channel_id, "input": {"name": name, "slug": slug}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ CHANNEL_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_channels,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ error = content["data"]["channelUpdate"]["channelErrors"][0]
+ assert error["field"] == "slug"
+ assert error["code"] == ChannelErrorCode.UNIQUE.name
+
+
+def test_channel_update_mutation_only_name(
+ permission_manage_channels, staff_api_client, channel_USD
+):
+ # given
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ name = "newName"
+ slug = channel_USD.slug
+ variables = {"id": channel_id, "input": {"name": name}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ CHANNEL_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_channels,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["channelUpdate"]
+ assert not data["channelErrors"]
+ channel_data = data["channel"]
+ channel_USD.refresh_from_db()
+ assert channel_data["name"] == channel_USD.name == name
+ assert channel_data["slug"] == channel_USD.slug == slug
+ assert channel_data["currencyCode"] == channel_USD.currency_code == "USD"
+
+
+def test_channel_update_mutation_only_slug(
+ permission_manage_channels, staff_api_client, channel_USD
+):
+ # given
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ name = channel_USD.name
+ slug = "new_slug"
+ variables = {"id": channel_id, "input": {"slug": slug}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ CHANNEL_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_channels,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["channelUpdate"]
+ assert not data["channelErrors"]
+ channel_data = data["channel"]
+ channel_USD.refresh_from_db()
+ assert channel_data["name"] == channel_USD.name == name
+ assert channel_data["slug"] == channel_USD.slug == slug
+ assert channel_data["currencyCode"] == channel_USD.currency_code == "USD"
diff --git a/saleor/graphql/channel/types.py b/saleor/graphql/channel/types.py
new file mode 100644
index 0000000000..cc18e8e53d
--- /dev/null
+++ b/saleor/graphql/channel/types.py
@@ -0,0 +1,65 @@
+from graphene import relay
+from graphene.types.resolver import get_default_resolver
+from graphene_django import DjangoObjectType
+
+from ...channel import models
+from ..core.connection import CountableDjangoObjectType
+from ..meta.types import ObjectWithMetadata
+from ..translations.resolvers import resolve_translation
+from . import ChannelContext
+
+
+class ChannelContextType(DjangoObjectType):
+ """A Graphene type that supports resolvers' root as ChannelContext objects."""
+
+ class Meta:
+ abstract = True
+
+ @staticmethod
+ def resolver_with_context(
+ attname, default_value, root: ChannelContext, info, **args
+ ):
+ resolver = get_default_resolver()
+ return resolver(attname, default_value, root.node, info, **args)
+
+ @staticmethod
+ def resolve_id(root: ChannelContext, _info):
+ return root.node.pk
+
+ @classmethod
+ def is_type_of(cls, root: ChannelContext, info):
+ return super().is_type_of(root.node, info)
+
+ @staticmethod
+ def resolve_translation(root: ChannelContext, info, language_code):
+ # Resolver for TranslationField; needs to be manually specified.
+ return resolve_translation(root.node, info, language_code)
+
+
+class ChannelContextTypeWithMetadata(ChannelContextType):
+ """A Graphene type for that uses ChannelContext as root in resolvers.
+
+ Same as ChannelContextType, but for types that implement ObjectWithMetadata
+ interface.
+ """
+
+ class Meta:
+ abstract = True
+
+ @staticmethod
+ def resolve_metadata(root: ChannelContext, info):
+ # Used in metadata API to resolve metadata fields from an instance.
+ return ObjectWithMetadata.resolve_metadata(root.node, info)
+
+ @staticmethod
+ def resolve_private_metadata(root: ChannelContext, info):
+ # Used in metadata API to resolve private metadata fields from an instance.
+ return ObjectWithMetadata.resolve_private_metadata(root.node, info)
+
+
+class Channel(CountableDjangoObjectType):
+ class Meta:
+ description = "Represents channel."
+ model = models.Channel
+ interfaces = [relay.Node]
+ only_fields = ["id", "name", "slug", "currency_code", "is_active"]
diff --git a/saleor/graphql/channel/utils.py b/saleor/graphql/channel/utils.py
new file mode 100644
index 0000000000..5388bb7bd3
--- /dev/null
+++ b/saleor/graphql/channel/utils.py
@@ -0,0 +1,27 @@
+from django.utils.functional import SimpleLazyObject
+from graphql.error import GraphQLError
+
+from ...channel.exceptions import ChannelNotDefined, NoDefaultChannel
+from ...channel.models import Channel
+from ...channel.utils import get_default_channel
+
+
+def get_default_channel_slug_or_graphql_error() -> SimpleLazyObject:
+ """Return a default channel slug in lazy way or a GraphQL error.
+
+ Utility to get the default channel in GraphQL query resolvers.
+ """
+ return SimpleLazyObject(lambda: get_default_channel_or_graphql_error().slug)
+
+
+def get_default_channel_or_graphql_error() -> Channel:
+ """Return a default channel or a GraphQL error.
+
+ Utility to get the default channel in GraphQL query resolvers.
+ """
+ try:
+ channel = get_default_channel()
+ except (ChannelNotDefined, NoDefaultChannel) as e:
+ raise GraphQLError(str(e))
+ else:
+ return channel
diff --git a/saleor/graphql/checkout/dataloaders.py b/saleor/graphql/checkout/dataloaders.py
index 3f76740927..beff859174 100644
--- a/saleor/graphql/checkout/dataloaders.py
+++ b/saleor/graphql/checkout/dataloaders.py
@@ -1,9 +1,25 @@
from collections import defaultdict
-from ...checkout.models import CheckoutLine
+from ...checkout.models import Checkout, CheckoutLine
from ..core.dataloaders import DataLoader
+class CheckoutByIdLoader(DataLoader):
+ context_key = "checkout_by_id"
+
+ def batch_load(self, keys):
+ checkouts = Checkout.objects.in_bulk(keys)
+ return [checkouts.get(checkout_id) for checkout_id in keys]
+
+
+class CheckoutLineByIdLoader(DataLoader):
+ context_key = "checkout_line_by_id"
+
+ def batch_load(self, keys):
+ checkout_lines = CheckoutLine.objects.in_bulk(keys)
+ return [checkout_lines.get(line_id) for line_id in keys]
+
+
class CheckoutLinesByCheckoutTokenLoader(DataLoader):
context_key = "checkoutlines_by_checkout"
diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.py
index e6b4a9e349..8799ccfbab 100644
--- a/saleor/graphql/checkout/mutations.py
+++ b/saleor/graphql/checkout/mutations.py
@@ -6,6 +6,9 @@ from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.db import transaction
from django.db.models import Prefetch
+from ...channel.exceptions import ChannelNotDefined
+from ...channel.models import Channel
+from ...channel.utils import get_default_channel
from ...checkout import models
from ...checkout.complete_checkout import complete_checkout
from ...checkout.error_codes import CheckoutErrorCode
@@ -127,12 +130,18 @@ def check_lines_quantity(variants, quantities, country):
raise ValidationError({"quantity": ValidationError(message, code=e.code)})
-def validate_variants_available_for_purchase(variants):
- not_available_variants = [
- variant.pk
- for variant in variants
- if not variant.product.is_available_for_purchase()
- ]
+def validate_variants_available_for_purchase(variants, channel_id):
+ not_available_variants = []
+ for variant in variants:
+ product_channel_listing = variant.product.channel_listings.filter(
+ channel_id=channel_id
+ ).first()
+ if not (
+ product_channel_listing
+ and product_channel_listing.is_available_for_purchase()
+ ):
+ not_available_variants.append(variant.pk)
+
if not_available_variants:
variant_ids = [
graphene.Node.to_global_id("ProductVariant", pk)
@@ -155,6 +164,9 @@ class CheckoutLineInput(graphene.InputObjectType):
class CheckoutCreateInput(graphene.InputObjectType):
+ channel = graphene.String(
+ description="Slug of a channel in which to create a checkout."
+ )
lines = graphene.List(
CheckoutLineInput,
description=(
@@ -198,7 +210,7 @@ class CheckoutCreate(ModelMutation, I18nMixin):
@classmethod
def process_checkout_lines(
- cls, lines, country
+ cls, lines, country, channel_id
) -> Tuple[List[product_models.ProductVariant], List[int]]:
variant_ids = [line.get("variant_id") for line in lines]
variants = cls.get_nodes_or_error(
@@ -211,7 +223,7 @@ class CheckoutCreate(ModelMutation, I18nMixin):
)
quantities = [line.get("quantity") for line in lines]
- validate_variants_available_for_purchase(variants)
+ validate_variants_available_for_purchase(variants, channel_id)
check_lines_quantity(variants, quantities, country)
return variants, quantities
@@ -232,11 +244,56 @@ 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):
cleaned_input = super().clean_input(info, instance, data)
user = info.context.user
country = info.context.country.code
+ channel = cls.clean_channel(cleaned_input.get("channel"))
+ cleaned_input["channel"] = channel
+ cleaned_input["currency"] = channel.currency_code
# set country to one from shipping address
shipping_address = cleaned_input.get("shipping_address")
@@ -251,7 +308,7 @@ class CheckoutCreate(ModelMutation, I18nMixin):
(
cleaned_input["variants"],
cleaned_input["quantities"],
- ) = cls.process_checkout_lines(lines, country)
+ ) = cls.process_checkout_lines(lines, country, cleaned_input["channel"].id)
cleaned_input["shipping_address"] = cls.retrieve_shipping_address(user, data)
cleaned_input["billing_address"] = cls.retrieve_billing_address(user, data)
@@ -319,7 +376,7 @@ class CheckoutCreate(ModelMutation, I18nMixin):
# `perform_mutation` is overridden to properly get or create a checkout
# instance here and abort mutation if needed.
if user.is_authenticated:
- checkout, _ = get_user_checkout(user)
+ checkout = get_user_checkout(user)
if checkout is not None:
# If user has an active checkout, return it without any
@@ -329,7 +386,6 @@ class CheckoutCreate(ModelMutation, I18nMixin):
checkout = models.Checkout(user=user)
else:
checkout = models.Checkout()
-
cleaned_input = cls.clean_input(info, checkout, data.get("input"))
checkout = cls.construct_instance(checkout, cleaned_input)
cls.clean_instance(info, checkout)
@@ -369,7 +425,7 @@ class CheckoutLinesAdd(BaseMutation):
quantities = [line.get("quantity") for line in lines]
check_lines_quantity(variants, quantities, checkout.get_country())
- validate_variants_available_for_purchase(variants)
+ validate_variants_available_for_purchase(variants, checkout.channel_id)
if variants and quantities:
for variant, quantity in zip(variants, quantities):
@@ -626,7 +682,6 @@ class CheckoutBillingAddressUpdate(CheckoutShippingAddressUpdate):
checkout = cls.get_node_or_error(
info, checkout_id, only_type=Checkout, field="checkout_id"
)
-
billing_address = cls.validate_address(
billing_address, instance=checkout.billing_address, info=info
)
@@ -694,7 +749,6 @@ class CheckoutShippingMethodUpdate(BaseMutation):
)
}
)
-
if not checkout.is_shipping_required():
raise ValidationError(
{
@@ -818,6 +872,15 @@ class CheckoutComplete(BaseMutation):
order = order_models.Order.objects.get_by_checkout_token(checkout_token)
if order:
+ if not order.channel.is_active:
+ raise ValidationError(
+ {
+ "channel": ValidationError(
+ "Cannot complete checkout with inactive channel.",
+ code=CheckoutErrorCode.CHANNEL_INACTIVE.value,
+ )
+ }
+ )
# The order is already created. We return it as a success
# checkoutComplete response. Order is anonymized for not logged in
# user
diff --git a/saleor/graphql/checkout/resolvers.py b/saleor/graphql/checkout/resolvers.py
index e8a3ccb0d9..e02920461d 100644
--- a/saleor/graphql/checkout/resolvers.py
+++ b/saleor/graphql/checkout/resolvers.py
@@ -8,24 +8,30 @@ def resolve_checkout_lines():
return queryset
-def resolve_checkouts():
+def resolve_checkouts(channel_slug):
queryset = models.Checkout.objects.all()
+ if channel_slug:
+ queryset = queryset.filter(channel__slug=channel_slug)
return queryset
-def resolve_checkout(info, token):
- checkout = models.Checkout.objects.filter(token=token).first()
+def resolve_checkout(info, token, channel_slug):
+ checkout = models.Checkout.objects.filter(
+ token=token, channel__slug=channel_slug
+ ).first()
if checkout is None:
return None
- # resolve checkout for anonymous customer
- if not checkout.user:
- return checkout
+ # resolve checkout in active channel
+ if checkout.channel.is_active:
+ # resolve checkout for anonymous customer
+ if not checkout.user:
+ return checkout
- # resolve checkout for logged-in customer
- if checkout.user == info.context.user:
- return checkout
+ # resolve checkout for logged-in customer
+ if checkout.user == info.context.user:
+ return checkout
# resolve checkout for staff user
requester = get_user_or_app_from_context(info.context)
diff --git a/saleor/graphql/checkout/schema.py b/saleor/graphql/checkout/schema.py
index 3848c2480d..d15bab3451 100644
--- a/saleor/graphql/checkout/schema.py
+++ b/saleor/graphql/checkout/schema.py
@@ -1,7 +1,11 @@
import graphene
from ...core.permissions import CheckoutPermissions
-from ..core.fields import BaseDjangoConnectionField, PrefetchingConnectionField
+from ..core.fields import (
+ BaseDjangoConnectionField,
+ FieldWithChannel,
+ PrefetchingConnectionField,
+)
from ..core.scalars import UUID
from ..decorators import permission_required
from ..payment.mutations import CheckoutPaymentCreate
@@ -25,13 +29,19 @@ from .types import Checkout, CheckoutLine
class CheckoutQueries(graphene.ObjectType):
- checkout = graphene.Field(
+ checkout = FieldWithChannel(
Checkout,
- description="Look up a checkout by token.",
+ description="Look up a checkout by token and slug of channel.",
token=graphene.Argument(UUID, description="The checkout's token."),
)
# FIXME we could optimize the below field
- checkouts = BaseDjangoConnectionField(Checkout, description="List of checkouts.")
+ checkouts = BaseDjangoConnectionField(
+ Checkout,
+ description="List of checkouts.",
+ channel=graphene.String(
+ description="Slug of a channel for which the data should be returned."
+ ),
+ )
checkout_line = graphene.Field(
CheckoutLine,
id=graphene.Argument(graphene.ID, description="ID of the checkout line."),
@@ -41,12 +51,12 @@ class CheckoutQueries(graphene.ObjectType):
CheckoutLine, description="List of checkout lines."
)
- def resolve_checkout(self, info, token):
- return resolve_checkout(info, token)
+ def resolve_checkout(self, info, token, channel):
+ return resolve_checkout(info, token, channel)
@permission_required(CheckoutPermissions.MANAGE_CHECKOUTS)
- def resolve_checkouts(self, *_args, **_kwargs):
- resolve_checkouts()
+ def resolve_checkouts(self, *_args, channel=None, **_kwargs):
+ return resolve_checkouts(channel)
def resolve_checkout_line(self, info, id):
return graphene.Node.get_node_from_global_id(info, id, CheckoutLine)
diff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
index 383f775a00..a97946b3a0 100644
--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
@@ -90,12 +90,11 @@ FRAGMENT_ADDRESS = """
FRAGMENT_SHIPPING_METHOD = """
fragment ShippingMethod on ShippingMethod {
- id
- name
- price {
- currency
- amount
- }
+ id
+ name
+ price {
+ amount
+ }
}
"""
@@ -160,6 +159,7 @@ def test_create_checkout(
api_client,
graphql_address_data,
stock,
+ channel_USD,
product_with_default_variant,
product_with_single_variant,
product_with_two_variants,
@@ -181,10 +181,10 @@ def test_create_checkout(
}
"""
)
-
checkout_counts = Checkout.objects.count()
variables = {
"checkoutInput": {
+ "channel": channel_USD.slug,
"email": "[email protected]",
"shippingAddress": graphql_address_data,
"lines": [
diff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.py
index daeb7e8fad..d72ecad89b 100644
--- a/saleor/graphql/checkout/tests/test_checkout.py
+++ b/saleor/graphql/checkout/tests/test_checkout.py
@@ -1,4 +1,6 @@
+import datetime
import uuid
+import warnings
from decimal import Decimal
from unittest import mock
from unittest.mock import ANY, patch
@@ -10,6 +12,7 @@ from django.test import override_settings
from prices import Money, TaxedMoney
from ....account.models import User
+from ....channel.utils import DEPRECATION_WARNING_MESSAGE
from ....checkout import calculations
from ....checkout.checkout_cleaner import (
clean_checkout_payment,
@@ -23,6 +26,7 @@ from ....payment import TransactionKind
from ....payment.interface import GatewayResponse
from ....plugins.manager import PluginsManager
from ....plugins.tests.sample_plugins import ActiveDummyPaymentGateway
+from ....product.models import ProductChannelListing
from ....warehouse.models import Stock
from ...tests.utils import assert_no_permission, get_graphql_content
from ..mutations import (
@@ -75,7 +79,6 @@ def test_update_checkout_shipping_method_if_invalid(
shipping_method.shipping_zone = shipping_zone_without_countries
shipping_method.save(update_fields=["shipping_zone"])
-
update_checkout_shipping_method_if_invalid(checkout, list(checkout), None)
assert checkout.shipping_method == other_shipping_method
@@ -110,18 +113,23 @@ MUTATION_CHECKOUT_CREATE = """
@mock.patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay")
def test_checkout_create_triggers_webhooks(
- mocked_webhook_trigger, user_api_client, stock, graphql_address_data, settings
+ mocked_webhook_trigger,
+ user_api_client,
+ stock,
+ graphql_address_data,
+ settings,
+ channel_USD,
):
"""Create checkout object using GraphQL API."""
settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
variant = stock.product_variant
variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
- test_email = "[email protected]"
shipping_address = graphql_address_data
variables = {
"checkoutInput": {
+ "channel": channel_USD.slug,
"lines": [{"quantity": 1, "variantId": variant_id}],
- "email": test_email,
+ "email": user_api_client.user.email,
"shippingAddress": shipping_address,
}
}
@@ -132,7 +140,292 @@ def test_checkout_create_triggers_webhooks(
assert mocked_webhook_trigger.called
-def test_checkout_create(api_client, stock, graphql_address_data, settings):
+def test_checkout_create_with_default_channel(
+ api_client, stock, graphql_address_data, channel_USD
+):
+ variant = stock.product_variant
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ test_email = "[email protected]"
+ shipping_address = graphql_address_data
+ variables = {
+ "checkoutInput": {
+ "lines": [{"quantity": 1, "variantId": variant_id}],
+ "email": test_email,
+ "shippingAddress": shipping_address,
+ }
+ }
+ assert not Checkout.objects.exists()
+ with warnings.catch_warnings(record=True) as warns:
+ response = api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)
+ content = get_graphql_content(response)["data"]["checkoutCreate"]
+
+ assert content["created"] is True
+
+ new_checkout = Checkout.objects.first()
+
+ assert new_checkout.channel == channel_USD
+
+ assert any(
+ [str(warning.message) == DEPRECATION_WARNING_MESSAGE for warning in warns]
+ )
+
+
+def test_checkout_create_with_inactive_channel(
+ api_client, stock, graphql_address_data, channel_USD
+):
+ channel = channel_USD
+ channel.is_active = False
+ channel.save()
+
+ variant = stock.product_variant
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ test_email = "[email protected]"
+ shipping_address = graphql_address_data
+ variables = {
+ "checkoutInput": {
+ "channel": channel.slug,
+ "lines": [{"quantity": 1, "variantId": variant_id}],
+ "email": test_email,
+ "shippingAddress": shipping_address,
+ }
+ }
+
+ response = api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)
+
+ error = get_graphql_content(response)["data"]["checkoutCreate"]["checkoutErrors"][0]
+
+ assert error["field"] == "channel"
+ assert error["code"] == CheckoutErrorCode.CHANNEL_INACTIVE.name
+
+
+def test_checkout_create_with_inactive_default_channel(
+ api_client, stock, graphql_address_data, channel_USD
+):
+ channel_USD.is_active = False
+ channel_USD.save()
+
+ variant = stock.product_variant
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ test_email = "[email protected]"
+ shipping_address = graphql_address_data
+ variables = {
+ "checkoutInput": {
+ "lines": [{"quantity": 1, "variantId": variant_id}],
+ "email": test_email,
+ "shippingAddress": shipping_address,
+ }
+ }
+
+ assert not Checkout.objects.exists()
+ with warnings.catch_warnings(record=True) as warns:
+ response = api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)
+ content = get_graphql_content(response)["data"]["checkoutCreate"]
+
+ assert content["created"] is True
+
+ new_checkout = Checkout.objects.first()
+
+ assert new_checkout.channel == channel_USD
+
+ assert any(
+ [str(warning.message) == DEPRECATION_WARNING_MESSAGE for warning in warns]
+ )
+
+
+def test_checkout_create_with_inactive_and_active_default_channel(
+ api_client, stock, graphql_address_data, channel_USD, channel_PLN
+):
+ channel_PLN.is_active = False
+ channel_PLN.save()
+
+ variant = stock.product_variant
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ test_email = "[email protected]"
+ shipping_address = graphql_address_data
+ variables = {
+ "checkoutInput": {
+ "lines": [{"quantity": 1, "variantId": variant_id}],
+ "email": test_email,
+ "shippingAddress": shipping_address,
+ }
+ }
+
+ assert not Checkout.objects.exists()
+ with warnings.catch_warnings(record=True) as warns:
+ response = api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)
+ content = get_graphql_content(response)["data"]["checkoutCreate"]
+
+ assert content["created"] is True
+
+ new_checkout = Checkout.objects.first()
+
+ assert new_checkout.channel == channel_USD
+
+ assert any(
+ [str(warning.message) == DEPRECATION_WARNING_MESSAGE for warning in warns]
+ )
+
+
+def test_checkout_create_with_inactive_and_two_active_default_channel(
+ api_client, stock, graphql_address_data, channel_USD, channel_PLN, other_channel_USD
+):
+ channel_USD.is_active = False
+ channel_USD.save()
+
+ variant = stock.product_variant
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ test_email = "[email protected]"
+ shipping_address = graphql_address_data
+ variables = {
+ "checkoutInput": {
+ "lines": [{"quantity": 1, "variantId": variant_id}],
+ "email": test_email,
+ "shippingAddress": shipping_address,
+ }
+ }
+
+ response = api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)
+
+ error = get_graphql_content(response)["data"]["checkoutCreate"]["checkoutErrors"][0]
+
+ assert error["field"] == "channel"
+ assert error["code"] == CheckoutErrorCode.MISSING_CHANNEL_SLUG.name
+
+
+def test_checkout_create_with_many_active_default_channel(
+ api_client, stock, graphql_address_data, channel_USD, channel_PLN
+):
+ variant = stock.product_variant
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ test_email = "[email protected]"
+ shipping_address = graphql_address_data
+ variables = {
+ "checkoutInput": {
+ "lines": [{"quantity": 1, "variantId": variant_id}],
+ "email": test_email,
+ "shippingAddress": shipping_address,
+ }
+ }
+
+ response = api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)
+
+ error = get_graphql_content(response)["data"]["checkoutCreate"]["checkoutErrors"][0]
+
+ assert error["field"] == "channel"
+ assert error["code"] == CheckoutErrorCode.MISSING_CHANNEL_SLUG.name
+
+
+def test_checkout_create_with_many_inactive_default_channel(
+ api_client, stock, graphql_address_data, channel_USD, channel_PLN
+):
+ channel_USD.is_active = False
+ channel_USD.save()
+ channel_PLN.is_active = False
+ channel_PLN.save()
+ variant = stock.product_variant
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ test_email = "[email protected]"
+ shipping_address = graphql_address_data
+ variables = {
+ "checkoutInput": {
+ "lines": [{"quantity": 1, "variantId": variant_id}],
+ "email": test_email,
+ "shippingAddress": shipping_address,
+ }
+ }
+
+ response = api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)
+
+ error = get_graphql_content(response)["data"]["checkoutCreate"]["checkoutErrors"][0]
+
+ assert error["field"] == "channel"
+ assert error["code"] == CheckoutErrorCode.MISSING_CHANNEL_SLUG.name
+
+
+def test_checkout_create_with_multiple_channel_without_channel_slug(
+ api_client, stock, graphql_address_data, channel_USD, channel_PLN
+):
+ variant = stock.product_variant
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ test_email = "[email protected]"
+ shipping_address = graphql_address_data
+ variables = {
+ "checkoutInput": {
+ "lines": [{"quantity": 1, "variantId": variant_id}],
+ "email": test_email,
+ "shippingAddress": shipping_address,
+ }
+ }
+
+ response = api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)
+
+ error = get_graphql_content(response)["data"]["checkoutCreate"]["checkoutErrors"][0]
+
+ assert error["field"] == "channel"
+ assert error["code"] == CheckoutErrorCode.MISSING_CHANNEL_SLUG.name
+
+
+def test_checkout_create_with_multiple_channel_with_channel_slug(
+ api_client, stock, graphql_address_data, channel_USD, channel_PLN
+):
+ variant = stock.product_variant
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ test_email = "[email protected]"
+ shipping_address = graphql_address_data
+ variables = {
+ "checkoutInput": {
+ "channel": channel_USD.slug,
+ "lines": [{"quantity": 1, "variantId": variant_id}],
+ "email": test_email,
+ "shippingAddress": shipping_address,
+ }
+ }
+ assert not Checkout.objects.exists()
+
+ response = api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)
+
+ content = get_graphql_content(response)["data"]["checkoutCreate"]
+
+ assert content["created"] is True
+
+ new_checkout = Checkout.objects.first()
+ assert new_checkout is not None
+ assert new_checkout.channel == channel_USD
+ checkout_data = content["checkout"]
+ assert checkout_data["token"] == str(new_checkout.token)
+ assert new_checkout.lines.count() == 1
+ checkout_line = new_checkout.lines.first()
+ assert checkout_line.variant == variant
+ assert checkout_line.quantity == 1
+
+
+def test_checkout_create_with_inactive_channel_slug(
+ api_client, stock, graphql_address_data, channel_USD
+):
+ channel = channel_USD
+ channel.is_active = False
+ channel.save()
+ variant = stock.product_variant
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ test_email = "[email protected]"
+ shipping_address = graphql_address_data
+ variables = {
+ "checkoutInput": {
+ "channel": channel_USD.slug,
+ "lines": [{"quantity": 1, "variantId": variant_id}],
+ "email": test_email,
+ "shippingAddress": shipping_address,
+ }
+ }
+ response = api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)
+
+ error = get_graphql_content(response)["data"]["checkoutCreate"]["checkoutErrors"][0]
+
+ assert error["field"] == "channel"
+ assert error["code"] == CheckoutErrorCode.CHANNEL_INACTIVE.name
+
+
+def test_checkout_create(api_client, stock, graphql_address_data, channel_USD):
"""Create checkout object using GraphQL API."""
variant = stock.product_variant
variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
@@ -140,6 +433,7 @@ def test_checkout_create(api_client, stock, graphql_address_data, settings):
shipping_address = graphql_address_data
variables = {
"checkoutInput": {
+ "channel": channel_USD.slug,
"lines": [{"quantity": 1, "variantId": variant_id}],
"email": test_email,
"shippingAddress": shipping_address,
@@ -176,8 +470,32 @@ def test_checkout_create(api_client, stock, graphql_address_data, settings):
assert new_checkout.shipping_address.city == shipping_address["city"].upper()
+def test_checkout_create_with_invalid_channel_slug(
+ api_client, stock, graphql_address_data, channel_USD
+):
+ variant = stock.product_variant
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ test_email = "[email protected]"
+ invalid_slug = "invalid-slug"
+ shipping_address = graphql_address_data
+ variables = {
+ "checkoutInput": {
+ "channel": invalid_slug,
+ "lines": [{"quantity": 1, "variantId": variant_id}],
+ "email": test_email,
+ "shippingAddress": shipping_address,
+ }
+ }
+ response = api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)
+ content = get_graphql_content(response)["data"]["checkoutCreate"]
+ error = content["checkoutErrors"][0]
+
+ assert error["code"] == CheckoutErrorCode.NOT_FOUND.name
+ assert error["field"] == "channel"
+
+
def test_checkout_create_multiple_warehouse(
- api_client, variant_with_many_stocks, graphql_address_data
+ api_client, variant_with_many_stocks, graphql_address_data, channel_USD
):
variant = variant_with_many_stocks
variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
@@ -185,6 +503,7 @@ def test_checkout_create_multiple_warehouse(
shipping_address = graphql_address_data
variables = {
"checkoutInput": {
+ "channel": channel_USD.slug,
"lines": [{"quantity": 4, "variantId": variant_id}],
"email": test_email,
"shippingAddress": shipping_address,
@@ -207,13 +526,14 @@ def test_checkout_create_multiple_warehouse(
assert checkout_line.quantity == 4
-def test_checkout_create_with_null_as_addresses(api_client, stock):
+def test_checkout_create_with_null_as_addresses(api_client, stock, channel_USD):
"""Create checkout object using GraphQL API."""
variant = stock.product_variant
variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
test_email = "[email protected]"
variables = {
"checkoutInput": {
+ "channel": channel_USD.slug,
"lines": [{"quantity": 1, "variantId": variant_id}],
"email": test_email,
"shippingAddress": None,
@@ -240,7 +560,7 @@ def test_checkout_create_with_null_as_addresses(api_client, stock):
def test_checkout_create_with_variant_without_inventory_tracking(
- api_client, variant_without_inventory_tracking
+ api_client, variant_without_inventory_tracking, channel_USD
):
"""Create checkout object using GraphQL API."""
variant = variant_without_inventory_tracking
@@ -248,6 +568,7 @@ def test_checkout_create_with_variant_without_inventory_tracking(
test_email = "[email protected]"
variables = {
"checkoutInput": {
+ "channel": channel_USD.slug,
"lines": [{"quantity": 1, "variantId": variant_id}],
"email": test_email,
"shippingAddress": None,
@@ -293,6 +614,7 @@ def test_checkout_create_cannot_add_invalid_quantities(
stock,
graphql_address_data,
quantity,
+ channel_USD,
expected_error_message,
error_code,
):
@@ -305,6 +627,7 @@ def test_checkout_create_cannot_add_invalid_quantities(
"lines": [{"quantity": quantity, "variantId": variant_id}],
"email": test_email,
"shippingAddress": shipping_address,
+ "channel": channel_USD.slug,
}
}
assert not Checkout.objects.exists()
@@ -328,7 +651,12 @@ def test_checkout_create_reuse_checkout(checkout, user_api_client, stock):
variant = stock.product_variant
variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
- variables = {"checkoutInput": {"lines": [{"quantity": 1, "variantId": variant_id}]}}
+ variables = {
+ "checkoutInput": {
+ "lines": [{"quantity": 1, "variantId": variant_id}],
+ "channel": checkout.channel.slug,
+ },
+ }
response = user_api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)
content = get_graphql_content(response)["data"]["checkoutCreate"]
@@ -344,11 +672,12 @@ def test_checkout_create_reuse_checkout(checkout, user_api_client, stock):
assert checkout_data["lines"] == []
-def test_checkout_create_required_email(api_client, stock):
+def test_checkout_create_required_email(api_client, stock, channel_USD):
variant = stock.product_variant
variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
variables = {
"checkoutInput": {
+ "channel": channel_USD.slug,
"lines": [{"quantity": 1, "variantId": variant_id}],
"email": "",
}
@@ -367,7 +696,7 @@ def test_checkout_create_required_email(api_client, stock):
def test_checkout_create_required_country_shipping_address(
- api_client, stock, graphql_address_data
+ api_client, stock, graphql_address_data, channel_USD
):
variant = stock.product_variant
variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
@@ -378,6 +707,7 @@ def test_checkout_create_required_country_shipping_address(
"lines": [{"quantity": 1, "variantId": variant_id}],
"email": "[email protected]",
"shippingAddress": shipping_address,
+ "channel": channel_USD.slug,
}
}
@@ -390,7 +720,7 @@ def test_checkout_create_required_country_shipping_address(
def test_checkout_create_required_country_billing_address(
- api_client, stock, graphql_address_data
+ api_client, stock, graphql_address_data, channel_USD
):
variant = stock.product_variant
variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
@@ -401,6 +731,7 @@ def test_checkout_create_required_country_billing_address(
"lines": [{"quantity": 1, "variantId": variant_id}],
"email": "[email protected]",
"billingAddress": billing_address,
+ "channel": channel_USD.slug,
}
}
@@ -412,10 +743,17 @@ def test_checkout_create_required_country_billing_address(
assert checkout_errors[0]["code"] == CheckoutErrorCode.REQUIRED.name
-def test_checkout_create_default_email_for_logged_in_customer(user_api_client, stock):
+def test_checkout_create_default_email_for_logged_in_customer(
+ user_api_client, stock, channel_USD
+):
variant = stock.product_variant
variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
- variables = {"checkoutInput": {"lines": [{"quantity": 1, "variantId": variant_id}]}}
+ variables = {
+ "checkoutInput": {
+ "lines": [{"quantity": 1, "variantId": variant_id}],
+ "channel": channel_USD.slug,
+ }
+ }
response = user_api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)
customer = user_api_client.user
content = get_graphql_content(response)
@@ -427,11 +765,12 @@ def test_checkout_create_default_email_for_logged_in_customer(user_api_client, s
assert new_checkout.email == customer.email
-def test_checkout_create_logged_in_customer(user_api_client, stock):
+def test_checkout_create_logged_in_customer(user_api_client, stock, channel_USD):
variant = stock.product_variant
variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
variables = {
"checkoutInput": {
+ "channel": channel_USD.slug,
"email": user_api_client.user.email,
"lines": [{"quantity": 1, "variantId": variant_id}],
}
@@ -459,13 +798,16 @@ def test_checkout_create_logged_in_customer(user_api_client, stock):
assert customer.email == new_checkout.email
-def test_checkout_create_logged_in_customer_custom_email(user_api_client, stock):
+def test_checkout_create_logged_in_customer_custom_email(
+ user_api_client, stock, channel_USD
+):
variant = stock.product_variant
variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
customer = user_api_client.user
custom_email = "[email protected]"
variables = {
"checkoutInput": {
+ "channel": channel_USD.slug,
"lines": [{"quantity": 1, "variantId": variant_id}],
"email": custom_email,
}
@@ -484,7 +826,7 @@ def test_checkout_create_logged_in_customer_custom_email(user_api_client, stock)
def test_checkout_create_logged_in_customer_custom_addresses(
- user_api_client, stock, graphql_address_data
+ user_api_client, stock, graphql_address_data, channel_USD
):
variant = stock.product_variant
variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
@@ -492,6 +834,7 @@ def test_checkout_create_logged_in_customer_custom_addresses(
billing_address = graphql_address_data
variables = {
"checkoutInput": {
+ "channel": channel_USD.slug,
"email": user_api_client.user.email,
"lines": [{"quantity": 1, "variantId": variant_id}],
"shippingAddress": shipping_address,
@@ -517,7 +860,7 @@ def test_checkout_create_logged_in_customer_custom_addresses(
def test_checkout_create_check_lines_quantity_multiple_warehouse(
- user_api_client, variant_with_many_stocks, graphql_address_data
+ user_api_client, variant_with_many_stocks, graphql_address_data, channel_USD
):
variant = variant_with_many_stocks
@@ -529,6 +872,7 @@ def test_checkout_create_check_lines_quantity_multiple_warehouse(
"lines": [{"quantity": 16, "variantId": variant_id}],
"email": test_email,
"shippingAddress": shipping_address,
+ "channel": channel_USD.slug,
}
}
assert not Checkout.objects.exists()
@@ -546,6 +890,7 @@ def test_checkout_create_sets_country_from_shipping_address_country(
user_api_client,
variant_with_many_stocks_different_shipping_zones,
graphql_address_data,
+ channel_USD,
):
variant = variant_with_many_stocks_different_shipping_zones
variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
@@ -556,6 +901,7 @@ def test_checkout_create_sets_country_from_shipping_address_country(
shipping_address["postalCode"] = 10001
variables = {
"checkoutInput": {
+ "channel": channel_USD.slug,
"lines": [{"quantity": 1, "variantId": variant_id}],
"email": test_email,
"shippingAddress": shipping_address,
@@ -575,6 +921,7 @@ def test_checkout_create_check_lines_quantity_for_zone_insufficient_stocks(
user_api_client,
variant_with_many_stocks_different_shipping_zones,
graphql_address_data,
+ channel_USD,
):
"""Check if insufficient stock exception will be raised.
If item from checkout will not have enough quantity in correct shipping zone for
@@ -594,6 +941,7 @@ def test_checkout_create_check_lines_quantity_for_zone_insufficient_stocks(
"lines": [{"quantity": 1, "variantId": variant_id}],
"email": test_email,
"shippingAddress": shipping_address,
+ "channel": channel_USD.slug,
}
}
assert not Checkout.objects.exists()
@@ -607,7 +955,7 @@ def test_checkout_create_check_lines_quantity_for_zone_insufficient_stocks(
def test_checkout_create_check_lines_quantity(
- user_api_client, stock, graphql_address_data
+ user_api_client, stock, graphql_address_data, channel_USD
):
variant = stock.product_variant
variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
@@ -618,6 +966,7 @@ def test_checkout_create_check_lines_quantity(
"lines": [{"quantity": 16, "variantId": variant_id}],
"email": test_email,
"shippingAddress": shipping_address,
+ "channel": channel_USD.slug,
}
}
assert not Checkout.objects.exists()
@@ -631,14 +980,13 @@ def test_checkout_create_check_lines_quantity(
def test_checkout_create_unavailable_for_purchase_product(
- user_api_client, stock, graphql_address_data
+ user_api_client, stock, graphql_address_data, channel_USD
):
# given
variant = stock.product_variant
product = variant.product
- product.available_for_purchase = None
- product.save(update_fields=["available_for_purchase"])
+ product.channel_listings.update(available_for_purchase=None)
variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
test_email = "[email protected]"
@@ -648,6 +996,45 @@ def test_checkout_create_unavailable_for_purchase_product(
"lines": [{"quantity": 10, "variantId": variant_id}],
"email": test_email,
"shippingAddress": shipping_address,
+ "channel": channel_USD.slug,
+ }
+ }
+ assert not Checkout.objects.exists()
+
+ # when
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutCreate"]
+
+ errors = data["checkoutErrors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "lines"
+ assert errors[0]["code"] == CheckoutErrorCode.PRODUCT_UNAVAILABLE_FOR_PURCHASE.name
+ assert errors[0]["variants"] == [variant_id]
+
+
+def test_checkout_create_available_for_purchase_from_tomorrow_product(
+ user_api_client, stock, graphql_address_data, channel_USD
+):
+ # given
+ variant = stock.product_variant
+ product = variant.product
+
+ product.channel_listings.update(
+ available_for_purchase=datetime.date.today() + datetime.timedelta(days=1)
+ )
+
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ test_email = "[email protected]"
+ shipping_address = graphql_address_data
+ variables = {
+ "checkoutInput": {
+ "lines": [{"quantity": 10, "variantId": variant_id}],
+ "email": test_email,
+ "shippingAddress": shipping_address,
+ "channel": channel_USD.slug,
}
}
assert not Checkout.objects.exists()
@@ -672,13 +1059,13 @@ def expected_dummy_gateway():
"id": "mirumee.payments.dummy",
"name": "Dummy",
"config": [{"field": "store_customer_card", "value": "false"}],
- "currencies": ["USD"],
+ "currencies": ["USD", "PLN"],
}
GET_CHECKOUT_PAYMENTS_QUERY = """
-query getCheckoutPayments($token: UUID!) {
- checkout(token: $token) {
+query getCheckoutPayments($token: UUID!, $channel: String!) {
+ checkout(token: $token, channel: $channel) {
availablePaymentGateways {
id
name
@@ -697,7 +1084,10 @@ def test_checkout_available_payment_gateways(
api_client, checkout_with_item, expected_dummy_gateway,
):
query = GET_CHECKOUT_PAYMENTS_QUERY
- variables = {"token": str(checkout_with_item.token)}
+ variables = {
+ "token": str(checkout_with_item.token),
+ "channel": checkout_with_item.channel.slug,
+ }
response = api_client.post_graphql(query, variables)
content = get_graphql_content(response)
@@ -715,7 +1105,10 @@ def test_checkout_available_payment_gateways_currency_specified_USD(
query = GET_CHECKOUT_PAYMENTS_QUERY
- variables = {"token": str(checkout_with_item.token)}
+ variables = {
+ "token": str(checkout_with_item.token),
+ "channel": checkout_with_item.channel.slug,
+ }
response = api_client.post_graphql(query, variables)
content = get_graphql_content(response)
@@ -726,15 +1119,18 @@ def test_checkout_available_payment_gateways_currency_specified_USD(
}
-def test_checkout_available_payment_gateways_currency_specified_PLN(
+def test_checkout_available_payment_gateways_currency_specified_EUR(
api_client, checkout_with_item, expected_dummy_gateway, sample_gateway
):
- checkout_with_item.currency = "PLN"
+ checkout_with_item.currency = "EUR"
checkout_with_item.save(update_fields=["currency"])
query = GET_CHECKOUT_PAYMENTS_QUERY
- variables = {"token": str(checkout_with_item.token)}
+ variables = {
+ "token": str(checkout_with_item.token),
+ "channel": checkout_with_item.channel.slug,
+ }
response = api_client.post_graphql(query, variables)
content = get_graphql_content(response)
@@ -744,28 +1140,37 @@ def test_checkout_available_payment_gateways_currency_specified_PLN(
)
+GET_CHECKOUT_AVAILABLE_SHIPPING_METHODS = """
+query getCheckout($token: UUID!, $channel: String!) {
+ checkout(token: $token, channel: $channel) {
+ availableShippingMethods {
+ name
+ price {
+ amount
+ }
+ }
+ }
+}
+"""
+
+
def test_checkout_available_shipping_methods(
api_client, checkout_with_item, address, shipping_zone
):
checkout_with_item.shipping_address = address
checkout_with_item.save()
- query = """
- query getCheckout($token: UUID!) {
- checkout(token: $token) {
- availableShippingMethods {
- name
- }
- }
+ query = GET_CHECKOUT_AVAILABLE_SHIPPING_METHODS
+ variables = {
+ "token": checkout_with_item.token,
+ "channel": checkout_with_item.channel.slug,
}
- """
- variables = {"token": checkout_with_item.token}
response = api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["checkout"]
shipping_method = shipping_zone.shipping_methods.first()
- assert data["availableShippingMethods"] == [{"name": shipping_method.name}]
+ assert data["availableShippingMethods"][0]["name"] == shipping_method.name
@pytest.mark.parametrize(
@@ -784,6 +1189,9 @@ def test_checkout_available_shipping_methods_with_price_displayed(
site_settings,
):
shipping_method = shipping_zone.shipping_methods.first()
+ shipping_price = shipping_method.channel_listings.get(
+ channel_id=checkout_with_item.channel_id
+ ).price
taxed_price = TaxedMoney(net=Money(10, "USD"), gross=Money(13, "USD"))
apply_taxes_to_shipping_mock = mock.Mock(return_value=taxed_price)
monkeypatch.setattr(
@@ -794,26 +1202,17 @@ def test_checkout_available_shipping_methods_with_price_displayed(
checkout_with_item.shipping_address = address
checkout_with_item.save()
- query = """
- query getCheckout($token: UUID!) {
- checkout(token: $token) {
- availableShippingMethods {
- name
- price {
- amount
- }
- }
- }
+ query = GET_CHECKOUT_AVAILABLE_SHIPPING_METHODS
+
+ variables = {
+ "token": checkout_with_item.token,
+ "channel": checkout_with_item.channel.slug,
}
- """
- variables = {"token": checkout_with_item.token}
response = api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["checkout"]
- apply_taxes_to_shipping_mock.assert_called_once_with(
- shipping_method.price, mock.ANY
- )
+ apply_taxes_to_shipping_mock.assert_called_once_with(shipping_price, mock.ANY)
assert data["availableShippingMethods"] == [
{"name": "DHL", "price": {"amount": expected_price}}
]
@@ -822,16 +1221,11 @@ def test_checkout_available_shipping_methods_with_price_displayed(
def test_checkout_no_available_shipping_methods_without_address(
api_client, checkout_with_item
):
- query = """
- query getCheckout($token: UUID!) {
- checkout(token: $token) {
- availableShippingMethods {
- name
- }
- }
+ query = GET_CHECKOUT_AVAILABLE_SHIPPING_METHODS
+ variables = {
+ "token": checkout_with_item.token,
+ "channel": checkout_with_item.channel.slug,
}
- """
- variables = {"token": checkout_with_item.token}
response = api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["checkout"]
@@ -840,16 +1234,9 @@ def test_checkout_no_available_shipping_methods_without_address(
def test_checkout_no_available_shipping_methods_without_lines(api_client, checkout):
- query = """
- query getCheckout($token: UUID!) {
- checkout(token: $token) {
- availableShippingMethods {
- name
- }
- }
- }
- """
- variables = {"token": checkout.token}
+ query = GET_CHECKOUT_AVAILABLE_SHIPPING_METHODS
+
+ variables = {"token": checkout.token, "channel": checkout.channel.slug}
response = api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["checkout"]
@@ -897,6 +1284,7 @@ def test_checkout_lines_add(
variables = {
"checkoutId": checkout_id,
"lines": [{"variantId": variant_id, "quantity": 1}],
+ "channelSlug": checkout.channel.slug,
}
response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
content = get_graphql_content(response)
@@ -913,11 +1301,13 @@ def test_checkout_lines_add(
def test_checkout_lines_add_with_unpublished_product(
- user_api_client, checkout_with_item, stock
+ user_api_client, checkout_with_item, stock, channel_USD
):
variant = stock.product_variant
- stock.product_variant.product.is_published = False
- stock.product_variant.product.save()
+ product = variant.product
+ ProductChannelListing.objects.filter(product=product, channel=channel_USD).update(
+ is_published=False
+ )
variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
checkout_id = graphene.Node.to_global_id("Checkout", checkout_with_item.pk)
@@ -925,6 +1315,7 @@ def test_checkout_lines_add_with_unpublished_product(
variables = {
"checkoutId": checkout_id,
"lines": [{"variantId": variant_id, "quantity": 1}],
+ "channelSlug": checkout_with_item.channel.slug,
}
response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
@@ -941,8 +1332,36 @@ def test_checkout_lines_add_with_unavailable_for_purchase_product(
# given
variant = stock.product_variant
product = stock.product_variant.product
- product.available_for_purchase = None
- product.save(update_fields=["available_for_purchase"])
+ product.channel_listings.update(available_for_purchase=None)
+
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout_with_item.pk)
+
+ variables = {
+ "checkoutId": checkout_id,
+ "lines": [{"variantId": variant_id, "quantity": 1}],
+ }
+
+ # when
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
+
+ # then
+ content = get_graphql_content(response)
+ error = content["data"]["checkoutLinesAdd"]["checkoutErrors"][0]
+ assert error["field"] == "lines"
+ assert error["code"] == CheckoutErrorCode.PRODUCT_UNAVAILABLE_FOR_PURCHASE.name
+ assert error["variants"] == [variant_id]
+
+
+def test_checkout_lines_add_with_available_for_purchase_from_tomorrow_product(
+ user_api_client, checkout_with_item, stock
+):
+ # given
+ variant = stock.product_variant
+ product = stock.product_variant.product
+ product.channel_listings.update(
+ available_for_purchase=datetime.date.today() + datetime.timedelta(days=1)
+ )
variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
checkout_id = graphene.Node.to_global_id("Checkout", checkout_with_item.pk)
@@ -971,6 +1390,7 @@ def test_checkout_lines_add_too_many(user_api_client, checkout_with_item, stock)
variables = {
"checkoutId": checkout_id,
"lines": [{"variantId": variant_id, "quantity": 51}],
+ "channelSlug": checkout_with_item.channel.slug,
}
response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
content = get_graphql_content(response)["data"]["checkoutLinesAdd"]
@@ -1125,11 +1545,13 @@ def test_checkout_lines_update(
def test_create_checkout_with_unpublished_product(
- user_api_client, checkout_with_item, stock
+ user_api_client, checkout_with_item, stock, channel_USD
):
variant = stock.product_variant
- variant.product.is_published = False
- variant.product.save()
+ product = variant.product
+ ProductChannelListing.objects.filter(product=product, channel=channel_USD).update(
+ is_published=False
+ )
variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
query = """
@@ -1147,6 +1569,7 @@ def test_create_checkout_with_unpublished_product(
"""
variables = {
"checkoutInput": {
+ "channel": channel_USD.slug,
"email": "[email protected]",
"lines": [{"variantId": variant_id, "quantity": 1}],
}
@@ -1159,13 +1582,15 @@ def test_create_checkout_with_unpublished_product(
def test_checkout_lines_update_with_unpublished_product(
- user_api_client, checkout_with_item
+ user_api_client, checkout_with_item, channel_USD
):
checkout = checkout_with_item
line = checkout.lines.first()
variant = line.variant
- variant.product.is_published = False
- variant.product.save()
+ product = variant.product
+ ProductChannelListing.objects.filter(product=product, channel=channel_USD).update(
+ is_published=False
+ )
variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
@@ -1476,11 +1901,12 @@ def test_checkout_shipping_address_update(
def test_checkout_shipping_address_update_changes_checkout_country(
mocked_update_shipping_method,
user_api_client,
+ channel_USD,
variant_with_many_stocks_different_shipping_zones,
graphql_address_data,
):
variant = variant_with_many_stocks_different_shipping_zones
- checkout = Checkout.objects.create()
+ checkout = Checkout.objects.create(channel=channel_USD)
checkout.set_country("PL", commit=True)
add_variant_to_checkout(checkout, variant, 1)
assert checkout.shipping_address is None
@@ -1524,12 +1950,13 @@ def test_checkout_shipping_address_update_changes_checkout_country(
@override_settings(DEFAULT_COUNTRY="DE")
def test_checkout_shipping_address_update_insufficient_stocks(
mocked_update_shipping_method,
+ channel_USD,
user_api_client,
variant_with_many_stocks_different_shipping_zones,
graphql_address_data,
):
variant = variant_with_many_stocks_different_shipping_zones
- checkout = Checkout.objects.create()
+ checkout = Checkout.objects.create(channel=channel_USD)
checkout.set_country("PL", commit=True)
add_variant_to_checkout(checkout, variant, 1)
Stock.objects.filter(
@@ -1753,8 +2180,8 @@ TRANSACTION_CONFIRM_GATEWAY_RESPONSE = GatewayResponse(
def test_fetch_checkout_by_token(user_api_client, checkout_with_item):
query = """
- query getCheckout($token: UUID!) {
- checkout(token: $token) {
+ query getCheckout($token: UUID!, $channel: String!) {
+ checkout(token: $token, channel: $channel) {
token,
lines {
variant {
@@ -1766,7 +2193,10 @@ def test_fetch_checkout_by_token(user_api_client, checkout_with_item):
}
}
"""
- variables = {"token": str(checkout_with_item.token)}
+ variables = {
+ "token": str(checkout_with_item.token),
+ "channel": checkout_with_item.channel.slug,
+ }
response = user_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["checkout"]
@@ -1774,17 +2204,20 @@ def test_fetch_checkout_by_token(user_api_client, checkout_with_item):
assert len(data["lines"]) == checkout_with_item.lines.count()
-def test_anonymous_client_cant_fetch_checkout_user(api_client, checkout):
- query = """
- query getCheckout($token: UUID!) {
- checkout(token: $token) {
+QUERY_CHECKOUT_USER_ID = """
+ query getCheckout($token: UUID!, $channel: String!) {
+ checkout(token: $token, channel: $channel) {
user {
id
}
}
}
"""
- variables = {"token": str(checkout.token)}
+
+
+def test_anonymous_client_cant_fetch_checkout_user(api_client, checkout):
+ query = QUERY_CHECKOUT_USER_ID
+ variables = {"token": str(checkout.token), "channel": checkout.channel.slug}
response = api_client.post_graphql(query, variables)
assert_no_permission(response)
@@ -1792,19 +2225,11 @@ def test_anonymous_client_cant_fetch_checkout_user(api_client, checkout):
def test_authorized_access_to_checkout_user_as_customer(
user_api_client, checkout, customer_user,
):
- query = """
- query getCheckout($token: UUID!) {
- checkout(token: $token) {
- user {
- id
- }
- }
- }
- """
+ query = QUERY_CHECKOUT_USER_ID
checkout.user = customer_user
checkout.save()
- variables = {"token": str(checkout.token)}
+ variables = {"token": str(checkout.token), "channel": checkout.channel.slug}
customer_user_id = graphene.Node.to_global_id("User", customer_user.id)
response = user_api_client.post_graphql(query, variables)
@@ -1819,19 +2244,11 @@ def test_authorized_access_to_checkout_user_as_staff(
permission_manage_users,
permission_manage_checkouts,
):
- query = """
- query getCheckout($token: UUID!) {
- checkout(token: $token) {
- user {
- id
- }
- }
- }
- """
+ query = QUERY_CHECKOUT_USER_ID
checkout.user = customer_user
checkout.save()
- variables = {"token": str(checkout.token)}
+ variables = {"token": str(checkout.token), "channel": checkout.channel.slug}
customer_user_id = graphene.Node.to_global_id("User", customer_user.id)
response = staff_api_client.post_graphql(
@@ -1847,19 +2264,12 @@ def test_authorized_access_to_checkout_user_as_staff(
def test_authorized_access_to_checkout_user_as_staff_no_permission(
staff_api_client, checkout, customer_user, permission_manage_checkouts,
):
- query = """
- query getCheckout($token: UUID!) {
- checkout(token: $token) {
- user {
- id
- }
- }
- }
- """
+ query = QUERY_CHECKOUT_USER_ID
+
checkout.user = customer_user
checkout.save()
- variables = {"token": str(checkout.token)}
+ variables = {"token": str(checkout.token), "channel": checkout.channel.slug}
response = staff_api_client.post_graphql(
query,
@@ -1871,23 +2281,65 @@ def test_authorized_access_to_checkout_user_as_staff_no_permission(
QUERY_CHECKOUT = """
-query getCheckout($token: UUID!) {
- checkout(token: $token) {
- token
+ query getCheckout($token: UUID!, $channel: String!) {
+ checkout(token: $token, channel: $channel) {
+ token
+ }
}
-}
"""
def test_query_anonymous_customer_checkout_as_anonymous_customer(api_client, checkout):
- variables = {"token": str(checkout.token)}
+ variables = {"token": str(checkout.token), "channel": checkout.channel.slug}
response = api_client.post_graphql(QUERY_CHECKOUT, variables)
content = get_graphql_content(response)
assert content["data"]["checkout"]["token"] == str(checkout.token)
+QUERY_CHECKOUT_CHANNEL_SLUG = """
+ query getCheckout($token: UUID!, $channel: String!) {
+ checkout(token: $token, channel: $channel) {
+ token
+ channel {
+ slug
+ }
+ }
+ }
+"""
+
+
+def test_query_anonymous_customer_channel_checkout_as_anonymous_customer(
+ api_client, checkout
+):
+ query = QUERY_CHECKOUT_CHANNEL_SLUG
+ checkout_token = str(checkout.token)
+ channel_slug = checkout.channel.slug
+ variables = {"token": checkout_token, "channel": channel_slug}
+
+ response = api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+
+ assert content["data"]["checkout"]["token"] == checkout_token
+ assert content["data"]["checkout"]["channel"]["slug"] == channel_slug
+
+
+def test_query_anonymous_customer_channel_checkout_as_customer(
+ user_api_client, checkout
+):
+ query = QUERY_CHECKOUT_CHANNEL_SLUG
+ checkout_token = str(checkout.token)
+ channel_slug = checkout.channel.slug
+ variables = {"token": checkout_token, "channel": channel_slug}
+
+ response = user_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+
+ assert content["data"]["checkout"]["token"] == checkout_token
+ assert content["data"]["checkout"]["channel"]["slug"] == channel_slug
+
+
def test_query_anonymous_customer_checkout_as_customer(user_api_client, checkout):
- variables = {"token": str(checkout.token)}
+ variables = {"token": str(checkout.token), "channel": checkout.channel.slug}
response = user_api_client.post_graphql(QUERY_CHECKOUT, variables)
content = get_graphql_content(response)
assert content["data"]["checkout"]["token"] == str(checkout.token)
@@ -1896,7 +2348,7 @@ def test_query_anonymous_customer_checkout_as_customer(user_api_client, checkout
def test_query_anonymous_customer_checkout_as_staff_user(
staff_api_client, checkout, permission_manage_checkouts
):
- variables = {"token": str(checkout.token)}
+ variables = {"token": str(checkout.token), "channel": checkout.channel.slug}
response = staff_api_client.post_graphql(
QUERY_CHECKOUT,
variables,
@@ -1910,7 +2362,7 @@ def test_query_anonymous_customer_checkout_as_staff_user(
def test_query_anonymous_customer_checkout_as_app(
app_api_client, checkout, permission_manage_checkouts
):
- variables = {"token": str(checkout.token)}
+ variables = {"token": str(checkout.token), "channel": checkout.channel.slug}
response = app_api_client.post_graphql(
QUERY_CHECKOUT,
variables,
@@ -1926,7 +2378,7 @@ def test_query_customer_checkout_as_anonymous_customer(
):
checkout.user = customer_user
checkout.save(update_fields=["user"])
- variables = {"token": str(checkout.token)}
+ variables = {"token": str(checkout.token), "channel": checkout.channel.slug}
response = api_client.post_graphql(QUERY_CHECKOUT, variables)
content = get_graphql_content(response)
assert not content["data"]["checkout"]
@@ -1935,7 +2387,7 @@ def test_query_customer_checkout_as_anonymous_customer(
def test_query_customer_checkout_as_customer(user_api_client, checkout, customer_user):
checkout.user = customer_user
checkout.save(update_fields=["user"])
- variables = {"token": str(checkout.token)}
+ variables = {"token": str(checkout.token), "channel": checkout.channel.slug}
response = user_api_client.post_graphql(QUERY_CHECKOUT, variables)
content = get_graphql_content(response)
assert content["data"]["checkout"]["token"] == str(checkout.token)
@@ -1946,7 +2398,7 @@ def test_query_other_customer_checkout_as_customer(
):
checkout.user = staff_user
checkout.save(update_fields=["user"])
- variables = {"token": str(checkout.token)}
+ variables = {"token": str(checkout.token), "channel": checkout.channel.slug}
response = user_api_client.post_graphql(QUERY_CHECKOUT, variables)
content = get_graphql_content(response)
assert not content["data"]["checkout"]
@@ -1957,7 +2409,7 @@ def test_query_customer_checkout_as_staff_user(
):
checkout.user = customer_user
checkout.save(update_fields=["user"])
- variables = {"token": str(checkout.token)}
+ variables = {"token": str(checkout.token), "channel": checkout.channel.slug}
response = app_api_client.post_graphql(
QUERY_CHECKOUT,
variables,
@@ -1973,7 +2425,7 @@ def test_query_customer_checkout_as_app(
):
checkout.user = customer_user
checkout.save(update_fields=["user"])
- variables = {"token": str(checkout.token)}
+ variables = {"token": str(checkout.token), "channel": checkout.channel.slug}
response = staff_api_client.post_graphql(
QUERY_CHECKOUT,
variables,
@@ -1984,8 +2436,8 @@ def test_query_customer_checkout_as_app(
assert content["data"]["checkout"]["token"] == str(checkout.token)
-def test_fetch_checkout_invalid_token(user_api_client):
- variables = {"token": str(uuid.uuid4())}
+def test_fetch_checkout_invalid_token(user_api_client, channel_USD):
+ variables = {"token": str(uuid.uuid4()), "channel": channel_USD.slug}
response = user_api_client.post_graphql(QUERY_CHECKOUT, variables)
content = get_graphql_content(response)
data = content["data"]["checkout"]
@@ -1994,8 +2446,8 @@ def test_fetch_checkout_invalid_token(user_api_client):
def test_checkout_prices(user_api_client, checkout_with_item):
query = """
- query getCheckout($token: UUID!) {
- checkout(token: $token) {
+ query getCheckout($token: UUID!, $channel: String!) {
+ checkout(token: $token, channel: $channel) {
token,
totalPrice {
currency
@@ -2020,7 +2472,10 @@ def test_checkout_prices(user_api_client, checkout_with_item):
}
}
"""
- variables = {"token": str(checkout_with_item.token)}
+ variables = {
+ "token": str(checkout_with_item.token),
+ "channel": checkout_with_item.channel.slug,
+ }
response = user_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["checkout"]
@@ -2135,6 +2590,49 @@ def test_query_checkouts(
assert str(checkout.token) == received_checkout["token"]
+def test_query_with_channel(
+ checkouts_list, staff_api_client, permission_manage_checkouts, channel_USD
+):
+ query = """
+ query CheckoutsQuery($channel: String) {
+ checkouts(first: 20, channel: $channel) {
+ edges {
+ node {
+ token
+ }
+ }
+ }
+ }
+ """
+ variables = {"channel": channel_USD.slug}
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_checkouts]
+ )
+ content = get_graphql_content(response)
+ assert len(content["data"]["checkouts"]["edges"]) == 3
+
+
+def test_query_without_channel(
+ checkouts_list, staff_api_client, permission_manage_checkouts
+):
+ query = """
+ {
+ checkouts(first: 20) {
+ edges {
+ node {
+ token
+ }
+ }
+ }
+ }
+ """
+ response = staff_api_client.post_graphql(
+ query, {}, permissions=[permission_manage_checkouts]
+ )
+ content = get_graphql_content(response)
+ assert len(content["data"]["checkouts"]["edges"]) == 5
+
+
def test_query_checkout_lines(
checkout_with_item, staff_api_client, permission_manage_checkouts
):
diff --git a/saleor/graphql/checkout/tests/test_checkout_complete.py b/saleor/graphql/checkout/tests/test_checkout_complete.py
index d0f2b663fa..3b4d15fcc7 100644
--- a/saleor/graphql/checkout/tests/test_checkout_complete.py
+++ b/saleor/graphql/checkout/tests/test_checkout_complete.py
@@ -80,6 +80,68 @@ def test_checkout_complete_order_already_exists(
assert order_with_lines.token == order_token
+def test_checkout_complete_with_inactive_channel_order_already_exists(
+ user_api_client, order_with_lines, checkout_with_gift_card,
+):
+ checkout = checkout_with_gift_card
+ order_with_lines.checkout_token = checkout.pk
+ channel = order_with_lines.channel
+ channel.is_active = False
+ channel.save()
+ order_with_lines.save()
+
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
+ variables = {"checkoutId": checkout_id, "redirectUrl": "https://www.example.com"}
+ checkout.delete()
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutComplete"]
+ assert data["checkoutErrors"][0]["code"] == CheckoutErrorCode.CHANNEL_INACTIVE.name
+ assert data["checkoutErrors"][0]["field"] == "channel"
+
+
+def test_checkout_complete_with_inactive_channel(
+ user_api_client,
+ checkout_with_gift_card,
+ gift_card,
+ payment_dummy,
+ address,
+ shipping_method,
+):
+ assert not gift_card.last_used_on
+
+ checkout = checkout_with_gift_card
+ channel = checkout.channel
+ channel.is_active = False
+ channel.save()
+ checkout.shipping_address = address
+ checkout.shipping_method = shipping_method
+ checkout.billing_address = address
+ checkout.store_value_in_metadata(items={"accepted": "true"})
+ checkout.store_value_in_private_metadata(items={"accepted": "false"})
+ checkout.save()
+
+ total = calculations.calculate_checkout_total_with_gift_cards(checkout=checkout)
+ payment = payment_dummy
+ payment.is_active = True
+ payment.order = None
+ payment.total = total.gross.amount
+ payment.currency = total.gross.currency
+ payment.checkout = checkout
+ payment.save()
+ assert not payment.transactions.exists()
+
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout.pk)
+ variables = {"checkoutId": checkout_id, "redirectUrl": "https://www.example.com"}
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutComplete"]
+ assert data["checkoutErrors"][0]["code"] == CheckoutErrorCode.CHANNEL_INACTIVE.name
+ assert data["checkoutErrors"][0]["field"] == "channel"
+
+
@pytest.mark.integration
def test_checkout_complete(
user_api_client,
@@ -142,7 +204,7 @@ def test_checkout_complete(
assert payment.transactions.count() == 1
gift_card.refresh_from_db()
- assert gift_card.current_balance == zero_money()
+ assert gift_card.current_balance == zero_money(gift_card.currency)
assert gift_card.last_used_on
assert not Checkout.objects.filter(
@@ -716,7 +778,7 @@ def test_checkout_complete_without_redirect_url(
assert payment.transactions.count() == 1
gift_card.refresh_from_db()
- assert gift_card.current_balance == zero_money()
+ assert gift_card.current_balance == zero_money(gift_card.currency)
assert gift_card.last_used_on
assert not Checkout.objects.filter(
diff --git a/saleor/graphql/checkout/tests/test_checkout_digital.py b/saleor/graphql/checkout/tests/test_checkout_digital.py
index b4d58c9aeb..da543688a0 100644
--- a/saleor/graphql/checkout/tests/test_checkout_digital.py
+++ b/saleor/graphql/checkout/tests/test_checkout_digital.py
@@ -19,7 +19,11 @@ from .test_checkout import (
@pytest.mark.parametrize("with_shipping_address", (True, False))
def test_create_checkout(
- api_client, digital_content, graphql_address_data, with_shipping_address
+ api_client,
+ digital_content,
+ graphql_address_data,
+ with_shipping_address,
+ channel_USD,
):
"""Test creating a checkout with a shipping address gets the address ignored."""
@@ -29,6 +33,7 @@ def test_create_checkout(
variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
checkout_input = {
+ "channel": channel_USD.slug,
"lines": [{"quantity": 1, "variantId": variant_id}],
"email": "[email protected]",
}
@@ -63,8 +68,8 @@ def test_checkout_has_no_available_shipping_methods(
"""Test no shipping method are available on digital orders."""
query = """
- query getCheckout($token: UUID!) {
- checkout(token: $token) {
+ query getCheckout($token: UUID!, $channel: String!) {
+ checkout(token: $token, channel: $channel) {
availableShippingMethods {
name
}
@@ -78,7 +83,8 @@ def test_checkout_has_no_available_shipping_methods(
checkout.shipping_address = address
checkout.save(update_fields=["shipping_address"])
- response = api_client.post_graphql(query, {"token": checkout.token})
+ variables = {"token": checkout.token, "channel": checkout.channel.slug}
+ response = api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["checkout"]
diff --git a/saleor/graphql/checkout/tests/test_checkout_promo_codes.py b/saleor/graphql/checkout/tests/test_checkout_promo_codes.py
index cd6c1665d3..33a3790789 100644
--- a/saleor/graphql/checkout/tests/test_checkout_promo_codes.py
+++ b/saleor/graphql/checkout/tests/test_checkout_promo_codes.py
@@ -15,13 +15,14 @@ from .test_checkout import (
def test_checkout_lines_delete_with_not_applicable_voucher(
- user_api_client, checkout_with_item, voucher
+ user_api_client, checkout_with_item, voucher, channel_USD
):
subtotal = calculations.checkout_subtotal(
checkout=checkout_with_item, lines=list(checkout_with_item)
)
- voucher.min_spent = subtotal.gross
- voucher.save(update_fields=["min_spent_amount", "currency"])
+ voucher.channel_listings.filter(channel=channel_USD).update(
+ min_spent_amount=subtotal.gross.amount
+ )
add_voucher_to_checkout(checkout_with_item, list(checkout_with_item), voucher)
assert checkout_with_item.voucher_code == voucher.code
@@ -80,15 +81,17 @@ def test_checkout_shipping_address_update_with_not_applicable_voucher(
assert checkout_with_item.voucher_code is None
-def test_checkout_totals_use_discounts(api_client, checkout_with_item, sale):
+def test_checkout_totals_use_discounts(
+ api_client, checkout_with_item, sale, channel_USD
+):
checkout = checkout_with_item
# make sure that we're testing a variant that is actually on sale
product = checkout.lines.first().variant.product
sale.products.add(product)
query = """
- query getCheckout($token: UUID) {
- checkout(token: $token) {
+ query getCheckout($token: UUID, $channel: String) {
+ checkout(token: $token, channel: $channel) {
lines {
totalPrice {
gross {
@@ -110,14 +113,15 @@ def test_checkout_totals_use_discounts(api_client, checkout_with_item, sale):
}
"""
- variables = {"token": str(checkout.token)}
+ variables = {"token": str(checkout.token), "channel": checkout.channel.slug}
response = api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["checkout"]
-
+ sale_channel_listing = sale.channel_listings.get(channel=channel_USD)
discounts = [
DiscountInfo(
sale=sale,
+ channel_listings={channel_USD.slug: sale_channel_listing},
product_ids={product.id},
category_ids=set(),
collection_ids=set(),
@@ -130,13 +134,15 @@ def test_checkout_totals_use_discounts(api_client, checkout_with_item, sale):
assert data["subtotalPrice"]["gross"]["amount"] == taxed_total.gross.amount
line = checkout.lines.first()
- line_total = calculations.checkout_line_total(line=line, discounts=discounts)
+ line_total = calculations.checkout_line_total(
+ line=line, discounts=discounts, channel=channel_USD
+ )
assert data["lines"][0]["totalPrice"]["gross"]["amount"] == line_total.gross.amount
QUERY_GET_CHECKOUT_GIFT_CARD_CODES = """
-query getCheckout($token: UUID!) {
- checkout(token: $token) {
+query getCheckout($token: UUID!, $channel: String!) {
+ checkout(token: $token, channel: $channel) {
token
giftCards {
displayCode
@@ -151,7 +157,10 @@ query getCheckout($token: UUID!) {
def test_checkout_get_gift_card_code(user_api_client, checkout_with_gift_card):
gift_card = checkout_with_gift_card.gift_cards.first()
- variables = {"token": str(checkout_with_gift_card.token)}
+ variables = {
+ "token": str(checkout_with_gift_card.token),
+ "channel": checkout_with_gift_card.channel.slug,
+ }
response = user_api_client.post_graphql(
QUERY_GET_CHECKOUT_GIFT_CARD_CODES, variables
)
@@ -168,7 +177,10 @@ def test_checkout_get_gift_card_codes(
checkout_with_gift_card.save()
gift_card_first = checkout_with_gift_card.gift_cards.first()
gift_card_last = checkout_with_gift_card.gift_cards.last()
- variables = {"token": str(checkout_with_gift_card.token)}
+ variables = {
+ "token": str(checkout_with_gift_card.token),
+ "channel": checkout_with_gift_card.channel.slug,
+ }
response = user_api_client.post_graphql(
QUERY_GET_CHECKOUT_GIFT_CARD_CODES, variables
)
@@ -181,7 +193,7 @@ def test_checkout_get_gift_card_codes(
def test_checkout_get_gift_card_code_without_gift_card(user_api_client, checkout):
- variables = {"token": str(checkout.token)}
+ variables = {"token": str(checkout.token), "channel": checkout.channel.slug}
response = user_api_client.post_graphql(
QUERY_GET_CHECKOUT_GIFT_CARD_CODES, variables
)
@@ -367,6 +379,20 @@ def test_checkout_add_voucher_code_not_applicable_voucher(
assert data["errors"][0]["field"] == "promoCode"
+def test_checkout_add_voucher_code_not_assigned_to_channel(
+ api_client, checkout_with_item, voucher_without_channel
+):
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout_with_item.pk)
+ variables = {
+ "checkoutId": checkout_id,
+ "promoCode": voucher_without_channel.code,
+ }
+ data = _mutate_checkout_add_promo_code(api_client, variables)
+
+ assert data["errors"]
+ assert data["errors"][0]["field"] == "promoCode"
+
+
def test_checkout_add_gift_card_code(api_client, checkout_with_item, gift_card):
checkout_id = graphene.Node.to_global_id("Checkout", checkout_with_item.pk)
gift_card_id = graphene.Node.to_global_id("GiftCard", gift_card.pk)
@@ -557,6 +583,27 @@ def test_checkout_remove_voucher_code(api_client, checkout_with_voucher):
assert checkout_with_voucher.voucher_code is None
+def test_checkout_remove_voucher_code_with_inactive_channel(
+ api_client, checkout_with_voucher
+):
+ channel = checkout_with_voucher.channel
+ channel.is_active = False
+ channel.save()
+
+ checkout_id = graphene.Node.to_global_id("Checkout", checkout_with_voucher.pk)
+ variables = {
+ "checkoutId": checkout_id,
+ "promoCode": checkout_with_voucher.voucher_code,
+ }
+
+ data = _mutate_checkout_remove_promo_code(api_client, variables)
+
+ checkout_with_voucher.refresh_from_db()
+ assert not data["errors"]
+ assert data["checkout"]["id"] == checkout_id
+ assert data["checkout"]["voucherCode"] == checkout_with_voucher.voucher_code
+
+
def test_checkout_remove_gift_card_code(api_client, checkout_with_gift_card):
assert checkout_with_gift_card.gift_cards.count() == 1
diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.py
index 8c59ce1f45..75cf85cd9b 100644
--- a/saleor/graphql/checkout/types.py
+++ b/saleor/graphql/checkout/types.py
@@ -8,12 +8,16 @@ from ...core.permissions import AccountPermissions
from ...core.taxes import display_gross_prices, zero_taxed_money
from ...plugins.manager import get_plugins_manager
from ..account.utils import requestor_has_access
+from ..channel import ChannelContext
+from ..channel.dataloaders import ChannelByCheckoutLineIDLoader, ChannelByIdLoader
from ..core.connection import CountableDjangoObjectType
from ..core.scalars import UUID
from ..core.types.money import TaxedMoney
from ..discount.dataloaders import DiscountsByDateTimeLoader
from ..giftcard.types import GiftCard
from ..meta.types import ObjectWithMetadata
+from ..product.resolvers import resolve_variant
+from ..shipping.dataloaders import ShippingMethodByIdLoader
from ..shipping.types import ShippingMethod
from ..utils import get_user_or_app_from_context
from .dataloaders import CheckoutLinesByCheckoutTokenLoader
@@ -65,16 +69,27 @@ class CheckoutLine(CountableDjangoObjectType):
filter_fields = ["id"]
@staticmethod
- def resolve_total_price(self, info):
- def calculate_total_price(discounts):
- return info.context.plugins.calculate_checkout_line_total(
- checkout_line=self, discounts=discounts
- )
+ def resolve_variant(root: models.CheckoutLine, info):
+ dataloader = ChannelByCheckoutLineIDLoader(info.context)
+ return resolve_variant(info, root, dataloader)
+
+ @staticmethod
+ def resolve_total_price(root, info):
+ context = info.context
+ channel = ChannelByCheckoutLineIDLoader(context).load(root.id)
+
+ def calculate_total_price_with_discounts(discounts):
+ def calculate_total_price_with_channel(channel):
+ return info.context.plugins.calculate_checkout_line_total(
+ checkout_line=root, discounts=discounts, channel=channel,
+ )
+
+ return channel.then(calculate_total_price_with_channel)
return (
- DiscountsByDateTimeLoader(info.context)
- .load(info.context.request_time)
- .then(calculate_total_price)
+ DiscountsByDateTimeLoader(context)
+ .load(context.request_time)
+ .then(calculate_total_price_with_discounts)
)
@staticmethod
@@ -111,11 +126,14 @@ class Checkout(CountableDjangoObjectType):
TaxedMoney,
description="The price of the shipping, with all the taxes included.",
)
+ shipping_method = graphene.Field(
+ ShippingMethod, description="The shipping method related with checkout.",
+ )
subtotal_price = graphene.Field(
TaxedMoney,
description="The price of the checkout before shipping, with taxes included.",
)
- token = graphene.Field(UUID, description=("The checkout's token."), required=True)
+ token = graphene.Field(UUID, description="The checkout's token.", required=True)
total_price = graphene.Field(
TaxedMoney,
description=(
@@ -132,10 +150,10 @@ class Checkout(CountableDjangoObjectType):
"gift_cards",
"is_shipping_required",
"last_change",
+ "channel",
"note",
"quantity",
"shipping_address",
- "shipping_method",
"translated_discount_name",
"user",
"voucher_code",
@@ -158,6 +176,25 @@ class Checkout(CountableDjangoObjectType):
return root.get_customer_email()
@staticmethod
+ def resolve_shipping_method(root: models.Checkout, info):
+ if not root.shipping_method_id:
+ return None
+
+ def wrap_shipping_method_with_channel_context(data):
+ shipping_method, channel = data
+ return ChannelContext(node=shipping_method, channel_slug=channel.slug)
+
+ shipping_method = ShippingMethodByIdLoader(info.context).load(
+ root.shipping_method_id
+ )
+ channel = ChannelByIdLoader(info.context).load(root.channel_id)
+
+ return Promise.all([shipping_method, channel]).then(
+ wrap_shipping_method_with_channel_context
+ )
+
+ @staticmethod
+ # TODO: We should optimize it in/after PR#5819
def resolve_total_price(root: models.Checkout, info):
def calculate_total_price(data):
lines, discounts = data
@@ -167,7 +204,7 @@ class Checkout(CountableDjangoObjectType):
)
- root.get_total_gift_cards_balance()
)
- return max(taxed_total, zero_taxed_money())
+ return max(taxed_total, zero_taxed_money(root.currency))
lines = CheckoutLinesByCheckoutTokenLoader(info.context).load(root.token)
discounts = DiscountsByDateTimeLoader(info.context).load(
@@ -177,6 +214,7 @@ class Checkout(CountableDjangoObjectType):
return Promise.all([lines, discounts]).then(calculate_total_price)
@staticmethod
+ # TODO: We should optimize it in/after PR#5819
def resolve_subtotal_price(root: models.Checkout, info):
def calculate_subtotal_price(data):
lines, discounts = data
@@ -192,6 +230,7 @@ class Checkout(CountableDjangoObjectType):
return Promise.all([lines, discounts]).then(calculate_subtotal_price)
@staticmethod
+ # TODO: We should optimize it in/after PR#5819
def resolve_shipping_price(root: models.Checkout, info):
def calculate_shipping_price(data):
lines, discounts = data
@@ -207,24 +246,28 @@ class Checkout(CountableDjangoObjectType):
return Promise.all([lines, discounts]).then(calculate_shipping_price)
@staticmethod
+ # TODO: We should optimize it in/after PR#5819
def resolve_lines(root: models.Checkout, *_args):
return root.lines.prefetch_related("variant")
@staticmethod
+ # TODO: We should optimize it in/after PR#5819
def resolve_available_shipping_methods(root: models.Checkout, info):
def calculate_available_shipping_methods(data):
lines, discounts = data
available = get_valid_shipping_methods_for_checkout(root, lines, discounts)
if available is None:
return []
-
manager = get_plugins_manager()
display_gross = display_gross_prices()
for shipping_method in available:
# ignore mypy checking because it is checked in
# get_valid_shipping_methods_for_checkout
- taxed_price = manager.apply_taxes_to_shipping(
- shipping_method.price, root.shipping_address # type: ignore
+ shipping_channel_listing = shipping_method.channel_listings.get(
+ channel=root.channel
+ )
+ taxed_price = manager.apply_taxes_to_shipping( # type: ignore
+ shipping_channel_listing.price, root.shipping_address
)
if display_gross:
shipping_method.price = taxed_price.gross
@@ -236,9 +279,15 @@ class Checkout(CountableDjangoObjectType):
discounts = DiscountsByDateTimeLoader(info.context).load(
info.context.request_time
)
-
- return Promise.all([lines, discounts]).then(
- calculate_available_shipping_methods
+ return (
+ Promise.all([lines, discounts])
+ .then(calculate_available_shipping_methods)
+ .then(
+ lambda available: [
+ ChannelContext(node=shipping, channel_slug=root.channel.slug)
+ for shipping in available
+ ]
+ )
)
@staticmethod
diff --git a/saleor/graphql/core/enums.py b/saleor/graphql/core/enums.py
index ac510ba5a6..358810ce79 100644
--- a/saleor/graphql/core/enums.py
+++ b/saleor/graphql/core/enums.py
@@ -2,6 +2,7 @@ import graphene
from ...account import error_codes as account_error_codes
from ...app import error_codes as app_error_codes
+from ...channel import error_codes as channel_error_codes
from ...checkout import error_codes as checkout_error_codes
from ...core import JobStatus, error_codes as core_error_codes
from ...core.permissions import get_permissions_enum_list
@@ -87,6 +88,7 @@ WeightUnitsEnum = graphene.Enum(
AccountErrorCode = graphene.Enum.from_enum(account_error_codes.AccountErrorCode)
AppErrorCode = graphene.Enum.from_enum(app_error_codes.AppErrorCode)
+ChannelErrorCode = graphene.Enum.from_enum(channel_error_codes.ChannelErrorCode)
CheckoutErrorCode = graphene.Enum.from_enum(checkout_error_codes.CheckoutErrorCode)
ExportErrorCode = graphene.Enum.from_enum(csv_error_codes.ExportErrorCode)
DiscountErrorCode = graphene.Enum.from_enum(discount_error_codes.DiscountErrorCode)
@@ -102,6 +104,7 @@ PermissionGroupErrorCode = graphene.Enum.from_enum(
account_error_codes.PermissionGroupErrorCode
)
ProductErrorCode = graphene.Enum.from_enum(product_error_codes.ProductErrorCode)
+CollectionErrorCode = graphene.Enum.from_enum(product_error_codes.CollectionErrorCode)
ShopErrorCode = graphene.Enum.from_enum(core_error_codes.ShopErrorCode)
ShippingErrorCode = graphene.Enum.from_enum(shipping_error_codes.ShippingErrorCode)
StockErrorCode = graphene.Enum.from_enum(warehouse_error_codes.StockErrorCode)
diff --git a/saleor/graphql/core/fields.py b/saleor/graphql/core/fields.py
index 043e07c202..1eca121f5b 100644
--- a/saleor/graphql/core/fields.py
+++ b/saleor/graphql/core/fields.py
@@ -8,6 +8,7 @@ from graphql.error import GraphQLError
from graphql_relay.connection.arrayconnection import connection_from_list_slice
from promise import Promise
+from ..channel import ChannelContext, ChannelQsContext
from ..utils.sorting import sort_queryset_for_connection
from .connection import connection_from_queryset_slice
@@ -106,7 +107,7 @@ class PrefetchingConnectionField(BaseDjangoConnectionField):
)
-class FilterInputConnectionField(PrefetchingConnectionField):
+class FilterInputConnectionField(BaseDjangoConnectionField):
def __init__(self, *args, **kwargs):
self.filter_field_name = kwargs.pop("filter_field_name", "filter")
self.filter_input = kwargs.get(self.filter_field_name)
@@ -173,6 +174,16 @@ class FilterInputConnectionField(PrefetchingConnectionField):
cls.resolve_connection, connection, args, max_limit=max_limit
)
+ iterable = cls.filter_iterable(
+ iterable, filterset_class, filters_name, info, **args
+ )
+
+ if Promise.is_thenable(iterable):
+ return Promise.resolve(iterable).then(on_resolve)
+ return on_resolve(iterable)
+
+ @classmethod
+ def filter_iterable(cls, iterable, filterset_class, filters_name, info, **args):
filter_input = args.get(filters_name)
if filter_input and filterset_class:
instance = filterset_class(
@@ -182,10 +193,7 @@ class FilterInputConnectionField(PrefetchingConnectionField):
if not instance.is_valid():
raise GraphQLError(json.dumps(instance.errors.get_json_data()))
iterable = instance.qs
-
- if Promise.is_thenable(iterable):
- return Promise.resolve(iterable).then(on_resolve)
- return on_resolve(iterable)
+ return iterable
def get_resolver(self, parent_resolver):
return partial(
@@ -193,3 +201,44 @@ class FilterInputConnectionField(PrefetchingConnectionField):
self.filterset_class,
self.filter_field_name,
)
+
+
+class ChannelContextFilterConnectionField(FilterInputConnectionField):
+ @classmethod
+ def filter_iterable(cls, iterable, filterset_class, filters_name, info, **args):
+ # Overriding filter_iterable to unpack the queryset from iterable, which is
+ # an instance of ChannelQsContext and pack it back after filtering is done.
+ channel_slug = iterable.channel_slug
+ iterable = super().filter_iterable(
+ iterable.qs, filterset_class, filters_name, info, **args
+ )
+ return ChannelQsContext(qs=iterable, channel_slug=channel_slug)
+
+ @classmethod
+ def resolve_connection(
+ cls, connection, args, iterable: ChannelQsContext, max_limit=None
+ ):
+ connection = super().resolve_connection(
+ connection, args, iterable.qs, max_limit
+ )
+ edges_with_context = []
+ for edge in connection.edges:
+ node = edge.node
+ edge.node = ChannelContext(node=node, channel_slug=iterable.channel_slug)
+ edges_with_context.append(edge)
+ connection.edges = edges_with_context
+ return connection
+
+
+class FieldWithChannel(graphene.Field):
+ def __init__(self, type, *args, **kwargs):
+ kwargs.setdefault(
+ "channel",
+ graphene.Argument(
+ graphene.String,
+ description=(
+ "Slug of the channel for which the data should be returned."
+ ),
+ ),
+ )
+ super().__init__(type, *args, **kwargs)
diff --git a/saleor/graphql/core/tests/test_base_mutation.py b/saleor/graphql/core/tests/test_base_mutation.py
index 1171e89cd3..f887aac1fc 100644
--- a/saleor/graphql/core/tests/test_base_mutation.py
+++ b/saleor/graphql/core/tests/test_base_mutation.py
@@ -15,12 +15,13 @@ class Mutation(BaseMutation):
class Arguments:
product_id = graphene.ID(required=True)
+ channel = graphene.String()
class Meta:
description = "Base mutation"
@classmethod
- def perform_mutation(cls, _root, info, product_id):
+ def perform_mutation(cls, _root, info, product_id, channel):
# Need to mock `app_middleware`
info.context.app = None
@@ -68,39 +69,34 @@ def test_mutation_without_description_raises_error():
product_id = graphene.ID(required=True)
-def test_resolve_id(product, schema_context):
- product_id = graphene.Node.to_global_id("Product", product.pk)
- query = """
- mutation testMutation($productId: ID!) {
- test(productId: $productId) {
- name
- errors {
- field
- message
- }
+TEST_MUTATION = """
+ mutation testMutation($productId: ID!, $channel: String) {
+ test(productId: $productId, channel: $channel) {
+ name
+ errors {
+ field
+ message
}
}
- """
- variables = {"productId": product_id}
- result = schema.execute(query, variables=variables, context_value=schema_context)
+ }
+"""
+
+
+def test_resolve_id(product, schema_context, channel_USD):
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ variables = {"productId": product_id, "channel": channel_USD.slug}
+ result = schema.execute(
+ TEST_MUTATION, variables=variables, context_value=schema_context
+ )
assert not result.errors
assert result.data["test"]["name"] == product.name
-def test_user_error_nonexistent_id(schema_context):
- query = """
- mutation testMutation($productId: ID!) {
- test(productId: $productId) {
- name
- errors {
- field
- message
- }
- }
- }
- """
- variables = {"productId": "not-really"}
- result = schema.execute(query, variables=variables, context_value=schema_context)
+def test_user_error_nonexistent_id(schema_context, channel_USD):
+ variables = {"productId": "not-really", "channel": channel_USD.slug}
+ result = schema.execute(
+ TEST_MUTATION, variables=variables, context_value=schema_context
+ )
assert not result.errors
user_errors = result.data["test"]["errors"]
assert user_errors
@@ -108,11 +104,11 @@ def test_user_error_nonexistent_id(schema_context):
assert user_errors[0]["message"] == "Couldn't resolve to a node: not-really"
-def test_mutation_custom_errors_default_value(product, schema_context):
+def test_mutation_custom_errors_default_value(product, schema_context, channel_USD):
product_id = graphene.Node.to_global_id("Product", product.pk)
query = """
- mutation testMutation($productId: ID!) {
- testWithCustomErrors(productId: $productId) {
+ mutation testMutation($productId: ID!, $channel: String) {
+ testWithCustomErrors(productId: $productId, channel: $channel) {
name
errors {
field
@@ -125,33 +121,23 @@ def test_mutation_custom_errors_default_value(product, schema_context):
}
}
"""
- variables = {"productId": product_id}
+ variables = {"productId": product_id, "channel": channel_USD.slug}
result = schema.execute(query, variables=variables, context_value=schema_context)
assert result.data["testWithCustomErrors"]["errors"] == []
assert result.data["testWithCustomErrors"]["customErrors"] == []
-def test_user_error_id_of_different_type(product, schema_context):
- query = """
- mutation testMutation($productId: ID!) {
- test(productId: $productId) {
- name
- errors {
- field
- message
- }
- }
- }
- """
-
+def test_user_error_id_of_different_type(product, schema_context, channel_USD):
# Test that get_node_or_error checks that the returned ID must be of
# proper type. Providing correct ID but of different type than expected
# should result in user error.
variant = product.variants.first()
variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
- variables = {"productId": variant_id}
- result = schema.execute(query, variables=variables, context_value=schema_context)
+ variables = {"productId": variant_id, "channel": channel_USD.slug}
+ result = schema.execute(
+ TEST_MUTATION, variables=variables, context_value=schema_context
+ )
assert not result.errors
user_errors = result.data["test"]["errors"]
assert user_errors
diff --git a/saleor/graphql/core/tests/test_core.py b/saleor/graphql/core/tests/test_core.py
index 38b9df71ee..cb9ac59cd4 100644
--- a/saleor/graphql/core/tests/test_core.py
+++ b/saleor/graphql/core/tests/test_core.py
@@ -8,7 +8,7 @@ from django.core.exceptions import ImproperlyConfigured, ValidationError
from django.utils import timezone
from graphene import InputField
-from ....product.models import Category, Product
+from ....product.models import Category, Product, ProductChannelListing
from ...product import types as product_types
from ...tests.utils import get_graphql_content, get_graphql_content_from_response
from ...utils import get_database_id, requestor_is_superuser
@@ -116,151 +116,19 @@ def test_require_pagination(api_client):
)
-def test_total_count_query(api_client, product):
+def test_total_count_query(api_client, product, channel_USD):
query = """
- query {
- products {
+ query ($channel: String){
+ products (channel: $channel){
totalCount
}
}
"""
- response = api_client.post_graphql(query)
+ response = api_client.post_graphql(query, {"channel": channel_USD.slug})
content = get_graphql_content(response)
assert content["data"]["products"]["totalCount"] == Product.objects.count()
-def test_mutation_positive_decimal_input(
- staff_api_client, variant, stock, permission_manage_products
-):
- query = """
- mutation PositiveDecimalInput(
- $id: ID!,
- $cost: PositiveDecimal,
- $price: PositiveDecimal,
- ) {
- productVariantUpdate(
- id: $id,
- input: {
- costPrice: $cost,
- price: $price,
- }
- ) {
- errors {
- field
- message
- }
- productVariant {
- costPrice {
- amount
- }
- }
- }
- }
- """
-
- variables = {
- "id": graphene.Node.to_global_id("ProductVariant", variant.id),
- "price": 15,
- "cost": 12.12,
- "quantity": 17,
- }
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_products]
- )
- content = get_graphql_content(response)
- data = content["data"]["productVariantUpdate"]
- assert data["errors"] == []
-
-
-def test_mutation_positive_decimal_input_without_arguments(
- staff_api_client, variant, permission_manage_products
-):
- query = """
- mutation ProductVariantUpdate(
- $id: ID!,
- $price: PositiveDecimal,
- $costPrice: PositiveDecimal,
- ) {
- productVariantUpdate(
- id: $id,
- input: {
- costPrice: $costPrice,
- price: $price,
- }
- ) {
- errors {
- field
- message
- }
- productVariant {
- costPrice{
- amount
- }
- }
- }
- }
- """
- variables = {
- "id": graphene.Node.to_global_id("ProductVariant", variant.id),
- "cost": 12.12,
- "price": 15,
- }
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_products]
- )
- content = get_graphql_content(response)
- data = content["data"]["productVariantUpdate"]
- assert data["errors"] == []
-
-
-def test_mutation_update_product_with_default_variant(
- product_with_default_variant, staff_api_client, permission_manage_products
-):
- # given
- query = """
- mutation ProductVariantUpdate(
- $id: ID!,
- $sku: String,
- ) {
- productVariantUpdate(
- id: $id,
- input: {
- sku: $sku,
- }
- ) {
- errors {
- field
- message
- }
- productVariant {
- sku
- }
- }
- }
- """
- variant = product_with_default_variant.variants.first()
- variant_id = variant.pk
-
- assert product_with_default_variant.product_type.has_variants is False
-
- variables = {
- "id": graphene.Node.to_global_id("ProductVariant", variant_id),
- "sku": "Updated product SKU",
- }
-
- # when
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_products]
- )
-
- # then
- content = get_graphql_content(response)
- data = content["data"]["productVariantUpdate"]
-
- assert data["errors"] == []
- assert data["productVariant"]["sku"] == "Updated product SKU"
-
-
def test_filter_input():
class CreatedEnum(graphene.Enum):
WEEK = "week"
@@ -374,8 +242,8 @@ def test_validate_slug_and_generate_if_needed_generate_slug(cleaned_input):
],
)
def test_filter_range_field(value, count, product_indexes, product_list):
- qs = Product.objects.all().order_by("pk")
- field = "minimal_variant_price_amount"
+ qs = ProductChannelListing.objects.all().order_by("pk")
+ field = "discounted_price_amount"
result = filter_range_field(qs, field, value)
diff --git a/saleor/graphql/core/tests/test_graphql.py b/saleor/graphql/core/tests/test_graphql.py
index 89fea0b98f..95c201e5ec 100644
--- a/saleor/graphql/core/tests/test_graphql.py
+++ b/saleor/graphql/core/tests/test_graphql.py
@@ -73,25 +73,25 @@ def test_jwt_middleware(client, admin_user):
assert repl_data["data"]["me"] == {"email": admin_user.email}
-def test_real_query(user_api_client, product):
+def test_real_query(user_api_client, product, channel_USD):
product_attr = product.product_type.product_attributes.first()
category = product.category
attr_value = product_attr.values.first()
query = """
query Root($categoryId: ID!, $sortBy: ProductOrder, $first: Int,
- $attributesFilter: [AttributeInput]) {
+ $attributesFilter: [AttributeInput], $channel: String) {
category(id: $categoryId) {
...CategoryPageFragmentQuery
__typename
}
products(first: $first, sortBy: $sortBy, filter: {categories: [$categoryId],
- attributes: $attributesFilter}) {
+ attributes: $attributesFilter}, channel: $channel) {
...ProductListFragmentQuery
__typename
}
- attributes(first: 20, filter: {inCategory: $categoryId}) {
+ attributes(first: 20, filter: {inCategory: $categoryId, channel: $channel}) {
edges {
node {
...ProductFiltersFragmentQuery
@@ -217,6 +217,7 @@ def test_real_query(user_api_client, product):
"attributesFilter": [
{"slug": f"{product_attr.slug}", "value": f"{attr_value.slug}"}
],
+ "channel": channel_USD.slug,
}
response = user_api_client.post_graphql(query, variables)
get_graphql_content(response)
diff --git a/saleor/graphql/core/tests/test_scalars.py b/saleor/graphql/core/tests/test_scalars.py
index 377cfc048f..cab931c5fb 100644
--- a/saleor/graphql/core/tests/test_scalars.py
+++ b/saleor/graphql/core/tests/test_scalars.py
@@ -1,8 +1,8 @@
from ...tests.utils import get_graphql_content
QUERY_CHECKOUT = """
-query getCheckout($token: UUID!) {
- checkout(token: $token) {
+query getCheckout($token: UUID!, $channel: String!) {
+ checkout(token: $token, channel: $channel) {
token
}
}
@@ -10,14 +10,14 @@ query getCheckout($token: UUID!) {
def test_uuid_scalar_value_passed_as_variable(api_client, checkout):
- variables = {"token": str(checkout.token)}
+ variables = {"token": str(checkout.token), "channel": checkout.channel.slug}
response = api_client.post_graphql(QUERY_CHECKOUT, variables)
content = get_graphql_content(response)
assert content["data"]["checkout"]["token"] == str(checkout.token)
def test_uuid_scalar_wrong_value_passed_as_variable(api_client, checkout):
- variables = {"token": "wrong-token"}
+ variables = {"token": "wrong-token", "channel": checkout.channel.slug}
response = api_client.post_graphql(QUERY_CHECKOUT, variables)
content = get_graphql_content(response, ignore_errors=True)
assert len(content["errors"]) == 1
@@ -25,9 +25,11 @@ def test_uuid_scalar_wrong_value_passed_as_variable(api_client, checkout):
def test_uuid_scalar_value_passed_in_input(api_client, checkout):
token = checkout.token
+ channel_slug = checkout.channel.slug
+
query = f"""
query{{
- checkout(token: "{token}") {{
+ checkout(token: "{token}", channel: "{channel_slug}") {{
token
}}
}}
@@ -39,9 +41,11 @@ def test_uuid_scalar_value_passed_in_input(api_client, checkout):
def test_uuid_scalar_wrong_value_passed_in_input(api_client, checkout):
token = "wrong-token"
+ channel_slug = checkout.channel.slug
+
query = f"""
query{{
- checkout(token: "{token}") {{
+ checkout(token: "{token}", channel: "{channel_slug}") {{
token
}}
}}
diff --git a/saleor/graphql/core/tests/test_view.py b/saleor/graphql/core/tests/test_view.py
index 52ffd30f2d..fffd66d783 100644
--- a/saleor/graphql/core/tests/test_view.py
+++ b/saleor/graphql/core/tests/test_view.py
@@ -5,7 +5,6 @@ import pytest
from django.test import override_settings
from ....demo.views import EXAMPLE_QUERY
-from ...product.types import Product
from ...tests.fixtures import (
ACCESS_CONTROL_ALLOW_CREDENTIALS,
ACCESS_CONTROL_ALLOW_HEADERS,
@@ -16,10 +15,10 @@ from ...tests.fixtures import (
from ...tests.utils import get_graphql_content, get_graphql_content_from_response
-def test_batch_queries(category, product, api_client):
+def test_batch_queries(category, product, api_client, channel_USD):
query_product = """
- query GetProduct($id: ID!) {
- product(id: $id) {
+ query GetProduct($id: ID!, $channel: String) {
+ product(id: $id, channel: $channel) {
name
}
}
@@ -34,11 +33,17 @@ def test_batch_queries(category, product, api_client):
data = [
{
"query": query_category,
- "variables": {"id": graphene.Node.to_global_id("Category", category.pk)},
+ "variables": {
+ "id": graphene.Node.to_global_id("Category", category.pk),
+ "channel": channel_USD.slug,
+ },
},
{
"query": query_product,
- "variables": {"id": graphene.Node.to_global_id("Product", product.pk)},
+ "variables": {
+ "id": graphene.Node.to_global_id("Product", product.pk),
+ "channel": channel_USD.slug,
+ },
},
]
response = api_client.post(data)
@@ -265,18 +270,33 @@ def test_validation_errors_query_do_not_get_logged(
assert graphql_log_handler.messages == []
[email protected](Product, "get_node")
[email protected]("saleor.graphql.product.schema.resolve_collection_by_id")
def test_unexpected_exceptions_are_logged_in_their_own_logger(
- mocked_get_node, staff_api_client, graphql_log_handler, permission_manage_products
+ mocked_resolve_collection_by_id,
+ staff_api_client,
+ graphql_log_handler,
+ permission_manage_products,
+ published_collection,
+ channel_USD,
):
- def bad_get_node(info, pk):
- raise NotImplementedError(info, pk)
+ def bad_mocked_resolve_collection_by_id(info, id, channel, requestor):
+ raise NotImplementedError(info, id, channel, requestor)
- mocked_get_node.side_effect = bad_get_node
+ mocked_resolve_collection_by_id.side_effect = bad_mocked_resolve_collection_by_id
staff_api_client.user.user_permissions.add(permission_manage_products)
+ variables = {
+ "id": graphene.Node.to_global_id("Collection", published_collection.pk),
+ "channel": channel_USD.slug,
+ }
response = staff_api_client.post_graphql(
- '{ product(id: "UHJvZHVjdDoxMg==") { name } }'
+ """
+ query($id: ID!,$channel:String) {
+ collection(id: $id,channel:$channel) {
+ name
+ }
+ }""",
+ variables=variables,
)
assert response.status_code == 200
diff --git a/saleor/graphql/core/types/__init__.py b/saleor/graphql/core/types/__init__.py
index 6fae71dda0..26a9fe8bf4 100644
--- a/saleor/graphql/core/types/__init__.py
+++ b/saleor/graphql/core/types/__init__.py
@@ -10,7 +10,7 @@ from .common import (
UploadedFile,
Weight,
)
-from .filter_input import FilterInputObjectType
+from .filter_input import ChannelFilterInputObjectType, FilterInputObjectType
from .money import VAT, Money, MoneyRange, ReducedRate, TaxedMoney, TaxedMoneyRange
-from .sort_input import SortInputObjectType
+from .sort_input import ChannelSortInputObjectType, SortInputObjectType
from .upload import Upload
diff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.py
index ca1a3ea04e..e19bf39d06 100644
--- a/saleor/graphql/core/types/common.py
+++ b/saleor/graphql/core/types/common.py
@@ -5,7 +5,9 @@ from ...translations.enums import LanguageCodeEnum
from ..enums import (
AccountErrorCode,
AppErrorCode,
+ ChannelErrorCode,
CheckoutErrorCode,
+ CollectionErrorCode,
DiscountErrorCode,
ExportErrorCode,
GiftCardErrorCode,
@@ -101,6 +103,10 @@ class StaffError(AccountError):
)
+class ChannelError(Error):
+ code = ChannelErrorCode(description="The error code.", required=True)
+
+
class CheckoutError(Error):
code = CheckoutErrorCode(description="The error code.", required=True)
variants = graphene.List(
@@ -110,8 +116,20 @@ class CheckoutError(Error):
)
-class DiscountError(Error):
+class ProductWithoutVariantError(Error):
+ products = graphene.List(
+ graphene.NonNull(graphene.ID),
+ description="List of products IDs which causes the error.",
+ )
+
+
+class DiscountError(ProductWithoutVariantError):
code = DiscountErrorCode(description="The error code.", required=True)
+ channels = graphene.List(
+ graphene.NonNull(graphene.ID),
+ description="List of channels IDs which causes the error.",
+ required=False,
+ )
class ExportError(Error):
@@ -134,6 +152,11 @@ class OrderError(Error):
order_line = graphene.ID(
description="Order line ID which causes the error.", required=False,
)
+ variants = graphene.List(
+ graphene.NonNull(graphene.ID),
+ description="List of product variants that are associated with the error",
+ required=False,
+ )
class InvoiceError(Error):
@@ -163,6 +186,26 @@ class ProductError(Error):
)
+class CollectionError(ProductWithoutVariantError):
+ code = CollectionErrorCode(description="The error code.", required=True)
+
+
+class ProductChannelListingError(ProductError):
+ channels = graphene.List(
+ graphene.NonNull(graphene.ID),
+ description="List of channels IDs which causes the error.",
+ required=False,
+ )
+
+
+class CollectionChannelListingError(ProductError):
+ channels = graphene.List(
+ graphene.NonNull(graphene.ID),
+ description="List of channels IDs which causes the error.",
+ required=False,
+ )
+
+
class BulkProductError(ProductError):
index = graphene.Int(
description="Index of an input list item that caused the error."
@@ -172,6 +215,11 @@ class BulkProductError(ProductError):
description="List of warehouse IDs which causes the error.",
required=False,
)
+ channels = graphene.List(
+ graphene.NonNull(graphene.ID),
+ description="List of channel IDs which causes the error.",
+ required=False,
+ )
class ShopError(Error):
@@ -185,6 +233,11 @@ class ShippingError(Error):
description="List of warehouse IDs which causes the error.",
required=False,
)
+ channels = graphene.List(
+ graphene.NonNull(graphene.ID),
+ description="List of channels IDs which causes the error.",
+ required=False,
+ )
class PageError(Error):
@@ -225,7 +278,7 @@ class WebhookError(Error):
code = WebhookErrorCode(description="The error code.", required=True)
-class WishlistError(Error):
+class WishlistError(ProductWithoutVariantError):
code = WishlistErrorCode(description="The error code.", required=True)
diff --git a/saleor/graphql/core/types/filter_input.py b/saleor/graphql/core/types/filter_input.py
index 1690ee0577..e3d678a2c8 100644
--- a/saleor/graphql/core/types/filter_input.py
+++ b/saleor/graphql/core/types/filter_input.py
@@ -1,4 +1,4 @@
-from graphene import InputField, InputObjectType
+from graphene import Argument, InputField, InputObjectType, String
from graphene.types.inputobjecttype import InputObjectTypeOptions
from graphene.types.utils import yank_fields_from_attrs
from graphene_django.filter.utils import get_filterset_class
@@ -62,3 +62,12 @@ class FilterInputObjectType(InputObjectType):
field_type.kwargs = kwargs
args[name] = field_type
return args
+
+
+class ChannelFilterInputObjectType(FilterInputObjectType):
+ channel = Argument(
+ String, description="Specifies the channel by which the data should be sorted.",
+ )
+
+ class Meta:
+ abstract = True
diff --git a/saleor/graphql/core/types/sort_input.py b/saleor/graphql/core/types/sort_input.py
index 31a8a35ef1..fe9199582a 100644
--- a/saleor/graphql/core/types/sort_input.py
+++ b/saleor/graphql/core/types/sort_input.py
@@ -35,3 +35,12 @@ class SortInputObjectType(graphene.InputObjectType):
description=f"Sort {type_name} by the selected field.",
)
cls._meta.fields.update({"field": field})
+
+
+class ChannelSortInputObjectType(SortInputObjectType):
+ channel = graphene.Argument(
+ graphene.String, description="Specifies the channel in which to sort the data.",
+ )
+
+ class Meta:
+ abstract = True
diff --git a/saleor/graphql/core/utils/error_codes.py b/saleor/graphql/core/utils/error_codes.py
index e838cc55b5..1e4405e816 100644
--- a/saleor/graphql/core/utils/error_codes.py
+++ b/saleor/graphql/core/utils/error_codes.py
@@ -2,6 +2,7 @@ from enum import Enum
from ....account.error_codes import AccountErrorCode, PermissionGroupErrorCode
from ....app.error_codes import AppErrorCode
+from ....channel.error_codes import ChannelErrorCode
from ....checkout.error_codes import CheckoutErrorCode
from ....core.error_codes import (
MetadataErrorCode,
@@ -51,6 +52,7 @@ DJANGO_FORM_FIELDS_ERROR_CODES = [
SALEOR_ERROR_CODE_ENUMS = [
AccountErrorCode,
AppErrorCode,
+ ChannelErrorCode,
CheckoutErrorCode,
ExportErrorCode,
DiscountErrorCode,
diff --git a/saleor/graphql/core/validators.py b/saleor/graphql/core/validators.py
index e6d88270f2..5f5c63703d 100644
--- a/saleor/graphql/core/validators.py
+++ b/saleor/graphql/core/validators.py
@@ -1,6 +1,5 @@
from typing import TYPE_CHECKING, Optional
-from django.conf import settings
from django.core.exceptions import ValidationError
from django_prices.utils.formatting import get_currency_fraction
from graphql.error import GraphQLError
@@ -27,7 +26,7 @@ def validate_one_of_args_is_in_query(*args):
raise GraphQLError(f"At least one of arguments is required: {required_args}.")
-def validate_price_precision(value: Optional["Decimal"], currency: str = None):
+def validate_price_precision(value: Optional["Decimal"], currency: str):
"""Validate if price amount does not have too many decimal places.
Price amount can't have more decimal places than currency allow to.
@@ -38,7 +37,7 @@ def validate_price_precision(value: Optional["Decimal"], currency: str = None):
if not value:
return
- currency_fraction = get_currency_fraction(currency or settings.DEFAULT_CURRENCY)
+ currency_fraction = get_currency_fraction(currency)
value = value.normalize()
if abs(value.as_tuple().exponent) > currency_fraction:
raise ValidationError(
diff --git a/saleor/graphql/csv/enums.py b/saleor/graphql/csv/enums.py
index 02c9c7ead3..c93a066f69 100644
--- a/saleor/graphql/csv/enums.py
+++ b/saleor/graphql/csv/enums.py
@@ -31,14 +31,10 @@ class ProductFieldEnum(graphene.Enum):
PRODUCT_TYPE = "product type"
CATEGORY = "category"
VISIBLE = "visible"
- AVAILABLE_FOR_PURCHASE = "available for purchase"
- SEARCHABLE = "searchable"
PRODUCT_WEIGHT = "product weight"
COLLECTIONS = "collections"
CHARGE_TAXES = "charge taxes"
PRODUCT_IMAGES = "product images"
VARIANT_SKU = "variant sku"
- VARIANT_PRICE = "variant price"
- COST_PRICE = "cost price"
VARIANT_WEIGHT = "variant weight"
VARIANT_IMAGES = "variant images"
diff --git a/saleor/graphql/csv/mutations.py b/saleor/graphql/csv/mutations.py
index f2d235c460..abd60c978a 100644
--- a/saleor/graphql/csv/mutations.py
+++ b/saleor/graphql/csv/mutations.py
@@ -7,6 +7,7 @@ from ...core.permissions import ProductPermissions
from ...csv import models as csv_models
from ...csv.events import export_started_event
from ...csv.tasks import export_products_task
+from ..channel.types import Channel
from ..core.enums import ExportErrorCode
from ..core.mutations import BaseMutation
from ..core.types.common import ExportError
@@ -27,6 +28,10 @@ class ExportInfoInput(graphene.InputObjectType):
graphene.NonNull(graphene.ID),
description="List of warehouse ids witch should be exported.",
)
+ channels = graphene.List(
+ graphene.NonNull(graphene.ID),
+ description="List of channels ids which should be exported.",
+ )
fields = graphene.List(
graphene.NonNull(ProductFieldEnum),
description="List of product fields witch should be exported.",
@@ -126,22 +131,28 @@ class ExportProducts(BaseMutation):
)
return {"filter": filter}
- @staticmethod
- def get_export_info(export_info_input):
+ @classmethod
+ def get_export_info(cls, export_info_input):
export_info = {}
fields = export_info_input.get("fields")
- attribute_ids = export_info_input.get("attributes")
- warehouse_ids = export_info_input.get("warehouses")
if fields:
export_info["fields"] = fields
- if attribute_ids:
- _, attribute_pks = resolve_global_ids_to_primary_keys(
- attribute_ids, graphene_type=Attribute
- )
- export_info["attributes"] = attribute_pks
- if warehouse_ids:
- _, warehouse_pks = resolve_global_ids_to_primary_keys(
- warehouse_ids, graphene_type=Warehouse
- )
- export_info["warehouses"] = warehouse_pks
+
+ for field, graphene_type in [
+ ("attributes", Attribute),
+ ("warehouses", Warehouse),
+ ("channels", Channel),
+ ]:
+ pks = cls.get_items_pks(field, export_info_input, graphene_type)
+ if pks:
+ export_info[field] = pks
+
return export_info
+
+ @staticmethod
+ def get_items_pks(field, export_info_input, graphene_type):
+ ids = export_info_input.get(field)
+ if not ids:
+ return
+ _, pks = resolve_global_ids_to_primary_keys(ids, graphene_type=graphene_type)
+ return pks
diff --git a/saleor/graphql/csv/tests/mutations/test_export_products.py b/saleor/graphql/csv/tests/mutations/test_export_products.py
index daf1e0bdd2..322c5c696a 100644
--- a/saleor/graphql/csv/tests/mutations/test_export_products.py
+++ b/saleor/graphql/csv/tests/mutations/test_export_products.py
@@ -3,6 +3,7 @@ from unittest.mock import ANY, patch
import graphene
import pytest
+from .....channel.models import Channel
from .....csv import ExportEvents
from .....csv.models import ExportEvent
from .....product.models import Attribute
@@ -165,7 +166,7 @@ def test_export_products_mutation_ids_scope(
"scope": ExportScope.IDS.name,
"ids": ids,
"exportInfo": {
- "fields": [ProductFieldEnum.VARIANT_PRICE.name],
+ "fields": [ProductFieldEnum.NAME.name],
"warehouses": [],
"attributes": [],
},
@@ -186,7 +187,7 @@ def test_export_products_mutation_ids_scope(
(call_args, call_kwargs,) = export_products_mock.call_args
assert set(call_args[1]["ids"]) == pks
- assert call_args[2] == {"fields": [ProductFieldEnum.VARIANT_PRICE.value]}
+ assert call_args[2] == {"fields": [ProductFieldEnum.NAME.value]}
assert call_args[3] == FileTypeEnum.XLSX.value
assert not data["exportErrors"]
@@ -204,6 +205,8 @@ def test_export_products_mutation_with_warehouse_and_attribute_ids(
export_products_mock,
staff_api_client,
product_list,
+ channel_USD,
+ channel_PLN,
permission_manage_products,
permission_manage_apps,
):
@@ -220,6 +223,7 @@ def test_export_products_mutation_with_warehouse_and_attribute_ids(
attribute_pks = [str(attr.pk) for attr in Attribute.objects.all()]
warehouse_pks = [str(warehouse.pk) for warehouse in Warehouse.objects.all()]
+ channel_pks = [str(channel.pk) for channel in Channel.objects.all()]
attribute_ids = [
graphene.Node.to_global_id("Attribute", pk) for pk in attribute_pks
@@ -227,15 +231,17 @@ def test_export_products_mutation_with_warehouse_and_attribute_ids(
warehouse_ids = [
graphene.Node.to_global_id("Warehouse", pk) for pk in warehouse_pks
]
+ channel_ids = [graphene.Node.to_global_id("Channel", pk) for pk in channel_pks]
variables = {
"input": {
"scope": ExportScope.IDS.name,
"ids": ids,
"exportInfo": {
- "fields": [ProductFieldEnum.VARIANT_PRICE.name],
+ "fields": [ProductFieldEnum.NAME.name],
"warehouses": warehouse_ids,
"attributes": attribute_ids,
+ "channels": channel_ids,
},
"fileType": FileTypeEnum.CSV.name,
}
@@ -255,9 +261,10 @@ def test_export_products_mutation_with_warehouse_and_attribute_ids(
assert set(call_args[1]["ids"]) == pks
assert call_args[2] == {
- "fields": [ProductFieldEnum.VARIANT_PRICE.value],
+ "fields": [ProductFieldEnum.NAME.value],
"warehouses": warehouse_pks,
"attributes": attribute_pks,
+ "channels": channel_pks,
}
assert call_args[3] == FileTypeEnum.CSV.value
diff --git a/saleor/graphql/discount/dataloaders.py b/saleor/graphql/discount/dataloaders.py
index 9d03baf0ab..e86ccee156 100644
--- a/saleor/graphql/discount/dataloaders.py
+++ b/saleor/graphql/discount/dataloaders.py
@@ -1,68 +1,37 @@
from collections import defaultdict
+from django.db.models import F
+
from ...discount import DiscountInfo
-from ...discount.models import Sale
-from ...product.models import Category
+from ...discount.models import Sale, SaleChannelListing, Voucher, VoucherChannelListing
+from ...discount.utils import (
+ fetch_categories,
+ fetch_collections,
+ fetch_products,
+ fetch_sale_channel_listings,
+)
from ..core.dataloaders import DataLoader
class DiscountsByDateTimeLoader(DataLoader):
context_key = "discounts"
- def fetch_categories(self, sale_pks):
- categories = (
- Sale.categories.through.objects.filter(sale_id__in=sale_pks)
- .order_by("id")
- .values_list("sale_id", "category_id")
- )
- category_map = defaultdict(set)
- for sale_pk, category_pk in categories:
- category_map[sale_pk].add(category_pk)
- subcategory_map = defaultdict(set)
- for sale_pk, category_pks in category_map.items():
- subcategory_map[sale_pk] = set(
- Category.tree.filter(pk__in=category_pks)
- .get_descendants(include_self=True)
- .values_list("id", flat=True)
- )
- return subcategory_map
-
- def fetch_collections(self, sale_pks):
- collections = (
- Sale.collections.through.objects.filter(sale_id__in=sale_pks)
- .order_by("id")
- .values_list("sale_id", "collection_id")
- )
- collection_map = defaultdict(set)
- for sale_pk, collection_pk in collections:
- collection_map[sale_pk].add(collection_pk)
- return collection_map
-
- def fetch_products(self, sale_pks):
- products = (
- Sale.products.through.objects.filter(sale_id__in=sale_pks)
- .order_by("id")
- .values_list("sale_id", "product_id")
- )
- product_map = defaultdict(set)
- for sale_pk, product_pk in products:
- product_map[sale_pk].add(product_pk)
- return product_map
-
def batch_load(self, keys):
sales_map = {
datetime: list(Sale.objects.active(datetime).order_by("id"))
for datetime in keys
}
pks = {s.pk for d, ss in sales_map.items() for s in ss}
- collections = self.fetch_collections(pks)
- products = self.fetch_products(pks)
- categories = self.fetch_categories(pks)
+ collections = fetch_collections(pks)
+ channel_listings = fetch_sale_channel_listings(pks)
+ products = fetch_products(pks)
+ categories = fetch_categories(pks)
return [
[
DiscountInfo(
sale=sale,
+ channel_listings=channel_listings[sale.pk],
category_ids=categories[sale.pk],
collection_ids=collections[sale.pk],
product_ids=products[sale.pk],
@@ -71,3 +40,80 @@ class DiscountsByDateTimeLoader(DataLoader):
]
for datetime in keys
]
+
+
+class SaleChannelListingBySaleIdAndChanneSlugLoader(DataLoader):
+ context_key = "salechannelisting_by_sale_and_channel"
+
+ def batch_load(self, keys):
+ sale_ids = [key[0] for key in keys]
+ channel_slugs = [key[1] for key in keys]
+ sale_channel_listings = SaleChannelListing.objects.filter(
+ sale_id__in=sale_ids, channel__slug__in=channel_slugs
+ ).annotate(channel_slug=F("channel__slug"))
+ sale_channel_listings_by_sale_and_channel_map = {}
+ for sale_channel_listing in sale_channel_listings:
+ key = (sale_channel_listing.sale_id, sale_channel_listing.channel_slug)
+ sale_channel_listings_by_sale_and_channel_map[key] = sale_channel_listing
+ return [sale_channel_listings_by_sale_and_channel_map.get(key) for key in keys]
+
+
+class SaleChannelListingBySaleIdLoader(DataLoader):
+ context_key = "salechannelisting_by_sale"
+
+ def batch_load(self, keys):
+ sale_channel_listings = SaleChannelListing.objects.filter(sale_id__in=keys)
+ sale_channel_listings_by_sale_map = defaultdict(list)
+ for sale_channel_listing in sale_channel_listings:
+ sale_channel_listings_by_sale_map[sale_channel_listing.sale_id].append(
+ sale_channel_listing
+ )
+ return [sale_channel_listings_by_sale_map[sale_id] for sale_id in keys]
+
+
+class VoucherByIdLoader(DataLoader):
+ context_key = "voucher_by_id"
+
+ def batch_load(self, keys):
+ vouchers = Voucher.objects.in_bulk(keys)
+ return [vouchers.get(voucher_id) for voucher_id in keys]
+
+
+class VoucherChannelListingByVoucherIdAndChanneSlugLoader(DataLoader):
+ context_key = "voucherchannelisting_by_voucher_and_channel"
+
+ def batch_load(self, keys):
+ voucher_ids = [key[0] for key in keys]
+ channel_slugs = [key[1] for key in keys]
+ voucher_channel_listings = VoucherChannelListing.objects.filter(
+ voucher_id__in=voucher_ids, channel__slug__in=channel_slugs
+ ).annotate(channel_slug=F("channel__slug"))
+ voucher_channel_listings_by_voucher_and_channel_map = {}
+ for voucher_channel_listing in voucher_channel_listings:
+ key = (
+ voucher_channel_listing.voucher_id,
+ voucher_channel_listing.channel_slug,
+ )
+ voucher_channel_listings_by_voucher_and_channel_map[
+ key
+ ] = voucher_channel_listing
+ return [
+ voucher_channel_listings_by_voucher_and_channel_map.get(key) for key in keys
+ ]
+
+
+class VoucherChannelListingByVoucherIdLoader(DataLoader):
+ context_key = "voucherchannellisting_by_voucher"
+
+ def batch_load(self, keys):
+ voucher_channel_listings = VoucherChannelListing.objects.filter(
+ voucher_id__in=keys
+ )
+ voucher_channel_listings_by_voucher_map = defaultdict(list)
+ for voucher_channel_listing in voucher_channel_listings:
+ voucher_channel_listings_by_voucher_map[
+ voucher_channel_listing.voucher_id
+ ].append(voucher_channel_listing)
+ return [
+ voucher_channel_listings_by_voucher_map[voucher_id] for voucher_id in keys
+ ]
diff --git a/saleor/graphql/discount/filters.py b/saleor/graphql/discount/filters.py
index 1630d7f596..f74aee7f87 100644
--- a/saleor/graphql/discount/filters.py
+++ b/saleor/graphql/discount/filters.py
@@ -62,7 +62,7 @@ def filter_sale_type(qs, _, value):
def filter_sale_search(qs, _, value):
- search_fields = ("name", "value", "type")
+ search_fields = ("name", "channel_listings__discount_value", "type")
if value:
qs = filter_by_query_param(qs, value, search_fields)
return qs
diff --git a/saleor/graphql/discount/mutations.py b/saleor/graphql/discount/mutations.py
index c6c79f7f1b..d8dce59543 100644
--- a/saleor/graphql/discount/mutations.py
+++ b/saleor/graphql/discount/mutations.py
@@ -1,14 +1,22 @@
+from collections import defaultdict
+from typing import TYPE_CHECKING, DefaultDict, Dict, List
+
import graphene
from django.core.exceptions import ValidationError
+from django.db import transaction
from ...core.permissions import DiscountPermissions
from ...core.utils.promo_code import generate_promo_code, is_available_promo_code
-from ...discount import models
+from ...discount import DiscountValueType, models
from ...discount.error_codes import DiscountErrorCode
+from ...discount.models import SaleChannelListing
from ...product.tasks import (
- update_products_minimal_variant_prices_of_catalogues_task,
- update_products_minimal_variant_prices_of_discount_task,
+ update_products_discounted_prices_of_catalogues_task,
+ update_products_discounted_prices_of_discount_task,
)
+from ...product.utils import get_products_ids_without_variants
+from ..channel import ChannelContext
+from ..channel.mutations import BaseChannelListingMutation
from ..core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation
from ..core.scalars import PositiveDecimal
from ..core.types.common import DiscountError
@@ -17,6 +25,11 @@ from ..product.types import Category, Collection, Product
from .enums import DiscountValueTypeEnum, VoucherTypeEnum
from .types import Sale, Voucher
+if TYPE_CHECKING:
+ from ...discount.models import Sale as SaleModel
+
+ErrorType = DefaultDict[str, List[ValidationError]]
+
class CatalogueInput(graphene.InputObjectType):
products = graphene.List(
@@ -39,8 +52,8 @@ class BaseDiscountCatalogueMutation(BaseMutation):
abstract = True
@classmethod
- def recalculate_minimal_prices(cls, products, categories, collections):
- update_products_minimal_variant_prices_of_catalogues_task.delay(
+ def recalculate_discounted_prices(cls, products, categories, collections):
+ update_products_discounted_prices_of_catalogues_task.delay(
product_ids=[p.pk for p in products],
category_ids=[c.pk for c in categories],
collection_ids=[c.pk for c in collections],
@@ -51,6 +64,7 @@ class BaseDiscountCatalogueMutation(BaseMutation):
products = input.get("products", [])
if products:
products = cls.get_nodes_or_error(products, "products", Product)
+ cls.clean_product(products)
node.products.add(*products)
categories = input.get("categories", [])
if categories:
@@ -61,7 +75,21 @@ class BaseDiscountCatalogueMutation(BaseMutation):
collections = cls.get_nodes_or_error(collections, "collections", Collection)
node.collections.add(*collections)
# Updated the db entries, recalculating discounts of affected products
- cls.recalculate_minimal_prices(products, categories, collections)
+ cls.recalculate_discounted_prices(products, categories, collections)
+
+ @classmethod
+ def clean_product(cls, products):
+ products_ids_without_variants = get_products_ids_without_variants(products)
+ if products_ids_without_variants:
+ raise ValidationError(
+ {
+ "products": ValidationError(
+ "Cannot manage products without variants.",
+ code=DiscountErrorCode.CANNOT_MANAGE_PRODUCT_WITHOUT_VARIANT,
+ params={"products": products_ids_without_variants},
+ )
+ }
+ )
@classmethod
def remove_catalogues_from_node(cls, node, input):
@@ -78,7 +106,7 @@ class BaseDiscountCatalogueMutation(BaseMutation):
collections = cls.get_nodes_or_error(collections, "collections", Collection)
node.collections.remove(*collections)
# Updated the db entries, recalculating discounts of affected products
- cls.recalculate_minimal_prices(products, categories, collections)
+ cls.recalculate_discounted_prices(products, categories, collections)
class VoucherInput(graphene.InputObjectType):
@@ -96,7 +124,6 @@ class VoucherInput(graphene.InputObjectType):
discount_value_type = DiscountValueTypeEnum(
description="Choices: fixed or percentage."
)
- discount_value = PositiveDecimal(description="Value of the voucher.")
products = graphene.List(
graphene.ID, description="Products discounted by the voucher.", name="products"
)
@@ -110,9 +137,6 @@ class VoucherInput(graphene.InputObjectType):
description="Categories discounted by the voucher.",
name="categories",
)
- min_amount_spent = PositiveDecimal(
- description="Min purchase amount required to apply the voucher."
- )
min_checkout_items_quantity = graphene.Int(
description="Minimal quantity of checkout items required to apply the voucher."
)
@@ -160,16 +184,13 @@ class VoucherCreate(ModelMutation):
)
cleaned_input = super().clean_input(info, instance, data)
- min_spent_amount = cleaned_input.pop("min_amount_spent", None)
- if min_spent_amount is not None:
- try:
- validate_price_precision(min_spent_amount, instance.currency)
- except ValidationError as error:
- error.code = DiscountErrorCode.INVALID.value
- raise ValidationError({"min_spent_amount": error})
- cleaned_input["min_spent_amount"] = min_spent_amount
return cleaned_input
+ @classmethod
+ def success_response(cls, instance):
+ instance = ChannelContext(node=instance, channel_slug=None)
+ return super().success_response(instance)
+
class VoucherUpdate(VoucherCreate):
class Arguments:
@@ -197,6 +218,12 @@ class VoucherDelete(ModelDeleteMutation):
error_type_class = DiscountError
error_type_field = "discount_errors"
+ @classmethod
+ def success_response(cls, instance):
+ instance = ChannelContext(node=instance, channel_slug=None)
+ response = super().success_response(instance)
+ return response
+
class VoucherBaseCatalogueMutation(BaseDiscountCatalogueMutation):
voucher = graphene.Field(
@@ -213,6 +240,13 @@ class VoucherBaseCatalogueMutation(BaseDiscountCatalogueMutation):
class Meta:
abstract = True
+ @classmethod
+ def mutate(cls, root, info, **data):
+ response = super().mutate(root, info, **data)
+ if response.voucher:
+ response.voucher = ChannelContext(node=response.voucher, channel_slug=None)
+ return response
+
class VoucherAddCatalogues(VoucherBaseCatalogueMutation):
class Meta:
@@ -246,6 +280,154 @@ class VoucherRemoveCatalogues(VoucherBaseCatalogueMutation):
return VoucherRemoveCatalogues(voucher=voucher)
+class VoucherChannelListingAddInput(graphene.InputObjectType):
+ channel_id = graphene.ID(required=True, description="ID of a channel.")
+ discount_value = PositiveDecimal(description="Value of the voucher.")
+ min_amount_spent = PositiveDecimal(
+ description="Min purchase amount required to apply the voucher."
+ )
+
+
+class VoucherChannelListingInput(graphene.InputObjectType):
+ add_channels = graphene.List(
+ graphene.NonNull(VoucherChannelListingAddInput),
+ description="List of channels to which the voucher should be assigned.",
+ required=False,
+ )
+ remove_channels = graphene.List(
+ graphene.NonNull(graphene.ID),
+ description=("List of channels from which the voucher should be unassigned."),
+ required=False,
+ )
+
+
+class VoucherChannelListingUpdate(BaseChannelListingMutation):
+ voucher = graphene.Field(Voucher, description="An updated voucher instance.")
+
+ class Arguments:
+ id = graphene.ID(required=True, description="ID of a voucher to update.")
+ input = VoucherChannelListingInput(
+ required=True,
+ description="Fields required to update voucher channel listings.",
+ )
+
+ class Meta:
+ description = "Manage voucher's availability in channels."
+ permissions = (DiscountPermissions.MANAGE_DISCOUNTS,)
+ error_type_class = DiscountError
+ error_type_field = "discount_errors"
+
+ @classmethod
+ def clean_prices(cls, cleaned_input, voucher, errors):
+ channel_slugs_assigned_to_voucher = voucher.channel_listings.values_list(
+ "channel__slug", flat=True
+ )
+ is_fixed_value_type = voucher.discount_value_type == DiscountValueType.FIXED
+ channels_without_value = []
+ channels_with_invalid_value_precision = []
+ channels_with_invalid_min_amount_spent_precision = []
+ for cleaned_channel in cleaned_input.get("add_channels", []):
+ channel = cleaned_channel.get("channel", None)
+ if not channel:
+ continue
+ discount_value = cleaned_channel.get("discount_value", "")
+ # New channel listing requires discout value. It raises validation error for
+ # `discout_value` == `None`.
+ # Updating channel listing doesn't require to pass `discout_value`.
+ should_create = channel.slug not in channel_slugs_assigned_to_voucher
+ missing_required_value = not discount_value and should_create
+ if missing_required_value or discount_value is None:
+ channels_without_value.append(cleaned_channel["channel_id"])
+ # Validate value precision if it is fixed amount voucher
+ if discount_value and is_fixed_value_type:
+ try:
+ validate_price_precision(discount_value, channel.currency_code)
+ except ValidationError:
+ channels_with_invalid_value_precision.append(
+ cleaned_channel["channel_id"]
+ )
+ if discount_value:
+ cleaned_channel["discount_value"] = discount_value
+
+ min_amount_spent = cleaned_channel.get("min_amount_spent", None)
+ if min_amount_spent:
+ try:
+ validate_price_precision(min_amount_spent, channel.currency_code)
+ except ValidationError:
+ channels_with_invalid_min_amount_spent_precision.append(
+ cleaned_channel["channel_id"]
+ )
+
+ if channels_without_value:
+ errors["discount_value"].append(
+ ValidationError(
+ "Value is required for voucher.",
+ code=DiscountErrorCode.REQUIRED.value,
+ params={"channels": channels_without_value},
+ )
+ )
+
+ if channels_with_invalid_value_precision:
+ errors["discount_value"].append(
+ ValidationError(
+ "Invalid amount precision.",
+ code=DiscountErrorCode.INVALID.value,
+ params={"channels": channels_with_invalid_value_precision},
+ )
+ )
+ if channels_with_invalid_min_amount_spent_precision:
+ errors["min_amount_spent"].append(
+ ValidationError(
+ "Invalid amount precision.",
+ code=DiscountErrorCode.INVALID.value,
+ params={
+ "channels": channels_with_invalid_min_amount_spent_precision
+ },
+ )
+ )
+ return cleaned_input
+
+ @classmethod
+ def add_channels(cls, voucher, add_channels):
+ for add_channel in add_channels:
+ channel = add_channel["channel"]
+ defaults = {"currency": channel.currency_code}
+ if "discount_value" in add_channel.keys():
+ defaults["discount_value"] = add_channel.get("discount_value")
+ if "min_amount_spent" in add_channel.keys():
+ defaults["min_spent_amount"] = add_channel.get("min_amount_spent", None)
+ models.VoucherChannelListing.objects.update_or_create(
+ voucher=voucher, channel=channel, defaults=defaults,
+ )
+
+ @classmethod
+ def remove_channels(cls, voucher, remove_channels):
+ voucher.channel_listings.filter(channel_id__in=remove_channels).delete()
+
+ @classmethod
+ @transaction.atomic()
+ def save(cls, voucher, cleaned_input):
+ cls.add_channels(voucher, cleaned_input.get("add_channels", []))
+ cls.remove_channels(voucher, cleaned_input.get("remove_channels", []))
+
+ @classmethod
+ def perform_mutation(cls, _root, info, id, input):
+ voucher = cls.get_node_or_error(info, id, only_type=Voucher, field="id")
+ errors = defaultdict(list)
+ cleaned_input = cls.clean_channels(
+ info, input, errors, DiscountErrorCode.DUPLICATED_INPUT_ITEM.value
+ )
+ cleaned_input = cls.clean_prices(cleaned_input, voucher, errors)
+
+ if errors:
+ raise ValidationError(errors)
+
+ cls.save(voucher, cleaned_input)
+ return VoucherChannelListingUpdate(
+ voucher=ChannelContext(node=voucher, channel_slug=None)
+ )
+
+
class SaleInput(graphene.InputObjectType):
name = graphene.String(description="Voucher name.")
type = DiscountValueTypeEnum(description="Fixed or percentage.")
@@ -271,16 +453,18 @@ class SaleInput(graphene.InputObjectType):
)
-class SaleUpdateMinimalVariantPriceMixin:
+class SaleUpdateDiscountedPriceMixin:
@classmethod
def success_response(cls, instance):
- # Update the "minimal_variant_prices" of the associated, discounted
+ # Update the "discounted_prices" of the associated, discounted
# products (including collections and categories).
- update_products_minimal_variant_prices_of_discount_task.delay(instance.pk)
- return super().success_response(instance)
+ update_products_discounted_prices_of_discount_task.delay(instance.pk)
+ return super().success_response(
+ ChannelContext(node=instance, channel_slug=None)
+ )
-class SaleCreate(SaleUpdateMinimalVariantPriceMixin, ModelMutation):
+class SaleCreate(SaleUpdateDiscountedPriceMixin, ModelMutation):
class Arguments:
input = SaleInput(
required=True, description="Fields required to create a sale."
@@ -294,7 +478,7 @@ class SaleCreate(SaleUpdateMinimalVariantPriceMixin, ModelMutation):
error_type_field = "discount_errors"
-class SaleUpdate(SaleUpdateMinimalVariantPriceMixin, ModelMutation):
+class SaleUpdate(SaleUpdateDiscountedPriceMixin, ModelMutation):
class Arguments:
id = graphene.ID(required=True, description="ID of a sale to update.")
input = SaleInput(
@@ -309,7 +493,7 @@ class SaleUpdate(SaleUpdateMinimalVariantPriceMixin, ModelMutation):
error_type_field = "discount_errors"
-class SaleDelete(SaleUpdateMinimalVariantPriceMixin, ModelDeleteMutation):
+class SaleDelete(SaleUpdateDiscountedPriceMixin, ModelDeleteMutation):
class Arguments:
id = graphene.ID(required=True, description="ID of a sale to delete.")
@@ -350,7 +534,7 @@ class SaleAddCatalogues(SaleBaseCatalogueMutation):
info, data.get("id"), only_type=Sale, field="sale_id"
)
cls.add_catalogues_to_node(sale, data.get("input"))
- return SaleAddCatalogues(sale=sale)
+ return SaleAddCatalogues(sale=ChannelContext(node=sale, channel_slug=None))
class SaleRemoveCatalogues(SaleBaseCatalogueMutation):
@@ -366,4 +550,110 @@ class SaleRemoveCatalogues(SaleBaseCatalogueMutation):
info, data.get("id"), only_type=Sale, field="sale_id"
)
cls.remove_catalogues_from_node(sale, data.get("input"))
- return SaleRemoveCatalogues(sale=sale)
+ return SaleRemoveCatalogues(sale=ChannelContext(node=sale, channel_slug=None))
+
+
+class SaleChannelListingAddInput(graphene.InputObjectType):
+ channel_id = graphene.ID(required=True, description="ID of a channel.")
+ discount_value = PositiveDecimal(
+ required=True, description="The value of the discount."
+ )
+
+
+class SaleChannelListingInput(graphene.InputObjectType):
+ add_channels = graphene.List(
+ graphene.NonNull(SaleChannelListingAddInput),
+ description="List of channels to which the sale should be assigned.",
+ required=False,
+ )
+ remove_channels = graphene.List(
+ graphene.NonNull(graphene.ID),
+ description=("List of channels from which the sale should be unassigned."),
+ required=False,
+ )
+
+
+class SaleChannelListingUpdate(BaseChannelListingMutation):
+ sale = graphene.Field(Sale, description="An updated sale instance.")
+
+ class Arguments:
+ id = graphene.ID(required=True, description="ID of a sale to update.")
+ input = SaleChannelListingInput(
+ required=True,
+ description="Fields required to update sale channel listings.",
+ )
+
+ class Meta:
+ description = "Manage sale's availability in channels."
+ permissions = (DiscountPermissions.MANAGE_DISCOUNTS,)
+ error_type_class = DiscountError
+ error_type_field = "discount_errors"
+
+ @classmethod
+ def add_channels(cls, sale: "SaleModel", add_channels: List[Dict]):
+ for add_channel in add_channels:
+ channel = add_channel["channel"]
+ defaults = {"currency": channel.currency_code}
+ channel = add_channel["channel"]
+ if "discount_value" in add_channel.keys():
+ defaults["discount_value"] = add_channel.get("discount_value")
+ SaleChannelListing.objects.update_or_create(
+ sale=sale, channel=channel, defaults=defaults,
+ )
+
+ @classmethod
+ def clean_prices(cls, cleaned_channels, sale_type, errors, error_code):
+ if sale_type != DiscountValueType.FIXED:
+ return cleaned_channels
+
+ invalid_channels_ids = []
+ error_message = None
+ for cleaned_channel in cleaned_channels.get("add_channels", []):
+ channel = cleaned_channel["channel"]
+ currency_code = channel.currency_code
+ discount_value = cleaned_channel.get("discount_value")
+ if discount_value:
+ try:
+ validate_price_precision(discount_value, currency_code)
+ except ValidationError as error:
+ error_message = error.message
+ invalid_channels_ids.append(cleaned_channel["channel_id"])
+ if invalid_channels_ids and error_message:
+ errors["input"].append(
+ ValidationError(
+ error_message,
+ code=error_code,
+ params={"channels": invalid_channels_ids},
+ )
+ )
+ return cleaned_channels
+
+ @classmethod
+ def remove_channels(cls, sale: "SaleModel", remove_channels: List[int]):
+ sale.channel_listings.filter(channel_id__in=remove_channels).delete()
+
+ @classmethod
+ @transaction.atomic()
+ def save(cls, info, sale: "SaleModel", cleaned_input: Dict):
+ cls.add_channels(sale, cleaned_input.get("add_channels", []))
+ cls.remove_channels(sale, cleaned_input.get("remove_channels", []))
+ update_products_discounted_prices_of_discount_task.delay(sale.pk)
+
+ @classmethod
+ def perform_mutation(cls, _root, info, id, input):
+ sale = cls.get_node_or_error(info, id, only_type=Sale, field="id")
+ errors = defaultdict(list)
+ cleaned_channels = cls.clean_channels(
+ info, input, errors, DiscountErrorCode.DUPLICATED_INPUT_ITEM.value
+ )
+ cleaned_input = cls.clean_prices(
+ cleaned_channels, sale.type, errors, DiscountErrorCode.INVALID.value
+ )
+
+ if errors:
+ raise ValidationError(errors)
+
+ cls.save(info, sale, cleaned_input)
+ return SaleChannelListingUpdate(
+ sale=ChannelContext(node=sale, channel_slug=None)
+ )
diff --git a/saleor/graphql/discount/resolvers.py b/saleor/graphql/discount/resolvers.py
index 55d438be26..d4d38a95ef 100644
--- a/saleor/graphql/discount/resolvers.py
+++ b/saleor/graphql/discount/resolvers.py
@@ -1,15 +1,22 @@
from ...discount import models
+from ..channel import ChannelQsContext
from ..utils.filters import filter_by_query_param
VOUCHER_SEARCH_FIELDS = ("name", "code")
SALE_SEARCH_FIELDS = ("name", "value", "type")
-def resolve_vouchers(info, query, **_kwargs):
+def resolve_vouchers(info, query, channel_slug, **_kwargs) -> ChannelQsContext:
qs = models.Voucher.objects.all()
- return filter_by_query_param(qs, query, VOUCHER_SEARCH_FIELDS)
+ qs = filter_by_query_param(qs, query, VOUCHER_SEARCH_FIELDS)
+ if channel_slug:
+ qs = qs.filter(channel_listings__channel__slug=channel_slug)
+ return ChannelQsContext(qs=qs, channel_slug=channel_slug)
-def resolve_sales(info, query, **_kwargs):
+def resolve_sales(info, query, channel_slug, **_kwargs) -> ChannelQsContext:
qs = models.Sale.objects.all()
- return filter_by_query_param(qs, query, SALE_SEARCH_FIELDS)
+ qs = filter_by_query_param(qs, query, SALE_SEARCH_FIELDS)
+ if channel_slug:
+ qs = qs.filter(channel_listings__channel__slug=channel_slug)
+ return ChannelQsContext(qs=qs, channel_slug=channel_slug)
diff --git a/saleor/graphql/discount/schema.py b/saleor/graphql/discount/schema.py
index 232c253e4f..8590a6ba6c 100644
--- a/saleor/graphql/discount/schema.py
+++ b/saleor/graphql/discount/schema.py
@@ -1,7 +1,8 @@
import graphene
from ...core.permissions import DiscountPermissions
-from ..core.fields import FilterInputConnectionField
+from ..channel import ChannelContext
+from ..core.fields import ChannelContextFilterConnectionField
from ..core.types import FilterInputObjectType
from ..decorators import permission_required
from ..translations.mutations import SaleTranslate, VoucherTranslate
@@ -9,11 +10,13 @@ from .bulk_mutations import SaleBulkDelete, VoucherBulkDelete
from .filters import SaleFilter, VoucherFilter
from .mutations import (
SaleAddCatalogues,
+ SaleChannelListingUpdate,
SaleCreate,
SaleDelete,
SaleRemoveCatalogues,
SaleUpdate,
VoucherAddCatalogues,
+ VoucherChannelListingUpdate,
VoucherCreate,
VoucherDelete,
VoucherRemoveCatalogues,
@@ -38,13 +41,19 @@ class DiscountQueries(graphene.ObjectType):
sale = graphene.Field(
Sale,
id=graphene.Argument(graphene.ID, description="ID of the sale.", required=True),
+ channel=graphene.String(
+ description="Slug of a channel for which the data should be returned."
+ ),
description="Look up a sale by ID.",
)
- sales = FilterInputConnectionField(
+ sales = ChannelContextFilterConnectionField(
Sale,
filter=SaleFilterInput(description="Filtering options for sales."),
sort_by=SaleSortingInput(description="Sort sales."),
query=graphene.String(description="Search sales by name, value or type."),
+ channel=graphene.String(
+ description="Slug of a channel for which the data should be returned."
+ ),
description="List of the shop's sales.",
)
voucher = graphene.Field(
@@ -52,31 +61,39 @@ class DiscountQueries(graphene.ObjectType):
id=graphene.Argument(
graphene.ID, description="ID of the voucher.", required=True
),
+ channel=graphene.String(
+ description="Slug of a channel for which the data should be returned."
+ ),
description="Look up a voucher by ID.",
)
- vouchers = FilterInputConnectionField(
+ vouchers = ChannelContextFilterConnectionField(
Voucher,
filter=VoucherFilterInput(description="Filtering options for vouchers."),
sort_by=VoucherSortingInput(description="Sort voucher."),
query=graphene.String(description="Search vouchers by name or code."),
+ channel=graphene.String(
+ description="Slug of a channel for which the data should be returned."
+ ),
description="List of the shop's vouchers.",
)
@permission_required(DiscountPermissions.MANAGE_DISCOUNTS)
- def resolve_sale(self, info, id):
- return graphene.Node.get_node_from_global_id(info, id, Sale)
+ def resolve_sale(self, info, id, channel=None):
+ sale = graphene.Node.get_node_from_global_id(info, id, Sale)
+ return ChannelContext(node=sale, channel_slug=channel) if sale else None
@permission_required(DiscountPermissions.MANAGE_DISCOUNTS)
- def resolve_sales(self, info, query=None, **kwargs):
- return resolve_sales(info, query, **kwargs)
+ def resolve_sales(self, info, query=None, channel=None, **kwargs):
+ return resolve_sales(info, query, channel_slug=channel, **kwargs)
@permission_required(DiscountPermissions.MANAGE_DISCOUNTS)
- def resolve_voucher(self, info, id):
- return graphene.Node.get_node_from_global_id(info, id, Voucher)
+ def resolve_voucher(self, info, id, channel=None):
+ voucher = graphene.Node.get_node_from_global_id(info, id, Voucher)
+ return ChannelContext(node=voucher, channel_slug=channel) if voucher else None
@permission_required(DiscountPermissions.MANAGE_DISCOUNTS)
- def resolve_vouchers(self, info, query=None, **kwargs):
- return resolve_vouchers(info, query, **kwargs)
+ def resolve_vouchers(self, info, query=None, channel=None, **kwargs):
+ return resolve_vouchers(info, query, channel_slug=channel, **kwargs)
class DiscountMutations(graphene.ObjectType):
@@ -87,6 +104,7 @@ class DiscountMutations(graphene.ObjectType):
sale_catalogues_add = SaleAddCatalogues.Field()
sale_catalogues_remove = SaleRemoveCatalogues.Field()
sale_translate = SaleTranslate.Field()
+ sale_channel_listing_update = SaleChannelListingUpdate.Field()
voucher_create = VoucherCreate.Field()
voucher_delete = VoucherDelete.Field()
@@ -95,3 +113,4 @@ class DiscountMutations(graphene.ObjectType):
voucher_catalogues_add = VoucherAddCatalogues.Field()
voucher_catalogues_remove = VoucherRemoveCatalogues.Field()
voucher_translate = VoucherTranslate.Field()
+ voucher_channel_listing_update = VoucherChannelListingUpdate.Field()
diff --git a/saleor/graphql/discount/sorters.py b/saleor/graphql/discount/sorters.py
index 479792510e..99cb7021f1 100644
--- a/saleor/graphql/discount/sorters.py
+++ b/saleor/graphql/discount/sorters.py
@@ -1,6 +1,8 @@
import graphene
+from django.db.models import Min, Q, QuerySet
-from ..core.types import SortInputObjectType
+from ..channel.sorters import validate_channel_slug
+from ..core.types import ChannelSortInputObjectType
class SaleSortField(graphene.Enum):
@@ -17,8 +19,18 @@ class SaleSortField(graphene.Enum):
return f"Sort sales by {sort_name}."
raise ValueError("Unsupported enum value: %s" % self.value)
+ @staticmethod
+ def qs_with_value(queryset: QuerySet, channel_slug: str) -> QuerySet:
+ validate_channel_slug(channel_slug)
+ return queryset.annotate(
+ value=Min(
+ "channel_listings__discount_value",
+ filter=Q(channel_listings__channel__slug=channel_slug),
+ )
+ )
-class SaleSortingInput(SortInputObjectType):
+
+class SaleSortingInput(ChannelSortInputObjectType):
class Meta:
sort_enum = SaleSortField
type_name = "sales"
@@ -40,8 +52,28 @@ class VoucherSortField(graphene.Enum):
return f"Sort vouchers by {sort_name}."
raise ValueError("Unsupported enum value: %s" % self.value)
+ @staticmethod
+ def qs_with_minimum_spent_amount(queryset: QuerySet, channel_slug: str) -> QuerySet:
+ validate_channel_slug(channel_slug)
+ return queryset.annotate(
+ min_spent_amount=Min(
+ "channel_listings__min_spent_amount",
+ filter=Q(channel_listings__channel__slug=channel_slug),
+ )
+ )
+
+ @staticmethod
+ def qs_with_value(queryset: QuerySet, channel_slug: str) -> QuerySet:
+ validate_channel_slug(channel_slug)
+ return queryset.annotate(
+ discount_value=Min(
+ "channel_listings__discount_value",
+ filter=Q(channel_listings__channel__slug=channel_slug),
+ )
+ )
+
-class VoucherSortingInput(SortInputObjectType):
+class VoucherSortingInput(ChannelSortInputObjectType):
class Meta:
sort_enum = VoucherSortField
type_name = "vouchers"
diff --git a/saleor/graphql/discount/tests/benchmark/__init__.py b/saleor/graphql/discount/tests/benchmark/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/graphql/discount/tests/benchmark/test_sales.py b/saleor/graphql/discount/tests/benchmark/test_sales.py
new file mode 100644
index 0000000000..40d93309b2
--- /dev/null
+++ b/saleor/graphql/discount/tests/benchmark/test_sales.py
@@ -0,0 +1,119 @@
+import pytest
+
+from .....discount.models import Sale, SaleChannelListing
+from ....tests.utils import get_graphql_content
+
+
+def sales_list(channel_USD, channel_PLN):
+ sales = Sale.objects.bulk_create(
+ [Sale(name="Sale1"), Sale(name="Sale2"), Sale(name="Sale2")]
+ )
+ values = [15, 5, 25]
+ sale_channel_listings = []
+ for sale, value in zip(sales, values):
+ sale_channel_listings.append(
+ SaleChannelListing(
+ sale=sale,
+ channel=channel_USD,
+ discount_value=value,
+ currency=channel_USD.currency_code,
+ )
+ )
+ sale_channel_listings.append(
+ SaleChannelListing(
+ sale=sale,
+ channel=channel_PLN,
+ discount_value=value * 2,
+ currency=channel_PLN.currency_code,
+ )
+ )
+ SaleChannelListing.objects.bulk_create(sale_channel_listings)
+ return sales
+
+
+SALES_QUERY = """
+query GetSales($channel: String){
+ sales(last: 10, channel: $channel) {
+ edges {
+ node {
+ id
+ name
+ type
+ startDate
+ endDate
+ categories(first: 10) {
+ edges {
+ node {
+ id
+ }
+ }
+ }
+ collections(first: 10) {
+ edges {
+ node {
+ id
+ }
+ }
+ }
+ products(first: 10) {
+ edges {
+ node {
+ id
+ }
+ }
+ }
+ channelListings {
+ id
+ discountValue
+ currency
+ channel {
+ id
+ name
+ isActive
+ slug
+ currencyCode
+ }
+ }
+ discountValue
+ currency
+ }
+ }
+ }
+}
+"""
+
+
[email protected]_queries(autouse=False)
+def test_sales_query_with_channel_slug(
+ staff_api_client,
+ sales_list,
+ channel_USD,
+ permission_manage_discounts,
+ count_queries,
+):
+ variables = {"channel": channel_USD.slug}
+ get_graphql_content(
+ staff_api_client.post_graphql(
+ SALES_QUERY,
+ variables,
+ permissions=[permission_manage_discounts],
+ check_no_permissions=False,
+ )
+ )
+
+
[email protected]_queries(autouse=False)
+def test_sales_query_withot_channel_slug(
+ staff_api_client, sales_list, permission_manage_discounts, count_queries,
+):
+ get_graphql_content(
+ staff_api_client.post_graphql(
+ SALES_QUERY,
+ {},
+ permissions=[permission_manage_discounts],
+ check_no_permissions=False,
+ )
+ )
diff --git a/saleor/graphql/discount/tests/benchmark/test_vouchers.py b/saleor/graphql/discount/tests/benchmark/test_vouchers.py
new file mode 100644
index 0000000000..608c5faeec
--- /dev/null
+++ b/saleor/graphql/discount/tests/benchmark/test_vouchers.py
@@ -0,0 +1,141 @@
+import pytest
+
+from .....discount.models import Voucher, VoucherChannelListing
+from ....tests.utils import get_graphql_content
+
+
+def vouchers_list(channel_USD, channel_PLN):
+ vouchers = Voucher.objects.bulk_create(
+ [
+ Voucher(name="Voucher1", code="Voucher1"),
+ Voucher(name="Voucher2", code="Voucher2"),
+ Voucher(name="Voucher3", code="Voucher3"),
+ ]
+ )
+ values = [15, 5, 25]
+ voucher_channel_listings = []
+ for voucher, value in zip(vouchers, values):
+ voucher_channel_listings.append(
+ VoucherChannelListing(
+ voucher=voucher,
+ channel=channel_USD,
+ discount_value=value,
+ currency=channel_USD.currency_code,
+ )
+ )
+ voucher_channel_listings.append(
+ VoucherChannelListing(
+ voucher=voucher,
+ channel=channel_PLN,
+ discount_value=value * 2,
+ currency=channel_PLN.currency_code,
+ )
+ )
+ VoucherChannelListing.objects.bulk_create(voucher_channel_listings)
+ return vouchers
+
+
+VOUCHERS_QUERY = """
+query GetVouchers($channel: String){
+ vouchers(last: 10, channel: $channel) {
+ edges {
+ node {
+ id
+ name
+ type
+ startDate
+ endDate
+ usageLimit
+ code
+ applyOncePerOrder
+ applyOncePerCustomer
+ discountValueType
+ minCheckoutItemsQuantity
+ countries{
+ code
+ country
+ vat{
+ countryCode
+ standardRate
+ }
+ }
+ categories(first: 10) {
+ edges {
+ node {
+ id
+ }
+ }
+ }
+ collections(first: 10) {
+ edges {
+ node {
+ id
+ }
+ }
+ }
+ products(first: 10) {
+ edges {
+ node {
+ id
+ }
+ }
+ }
+ channelListings {
+ id
+ discountValue
+ currency
+ minSpent{
+ currency
+ amount
+ }
+ channel {
+ id
+ name
+ isActive
+ slug
+ currencyCode
+ }
+ }
+ discountValue
+ currency
+ }
+ }
+ }
+}
+"""
+
+
[email protected]_queries(autouse=False)
+def test_vouchers_query_with_channel_slug(
+ staff_api_client,
+ vouchers_list,
+ channel_USD,
+ permission_manage_discounts,
+ count_queries,
+):
+ variables = {"channel": channel_USD.slug}
+ get_graphql_content(
+ staff_api_client.post_graphql(
+ VOUCHERS_QUERY,
+ variables,
+ permissions=[permission_manage_discounts],
+ check_no_permissions=False,
+ )
+ )
+
+
[email protected]_queries(autouse=False)
+def test_vouchers_query_withot_channel_slug(
+ staff_api_client, vouchers_list, permission_manage_discounts, count_queries,
+):
+ get_graphql_content(
+ staff_api_client.post_graphql(
+ VOUCHERS_QUERY,
+ {},
+ permissions=[permission_manage_discounts],
+ check_no_permissions=False,
+ )
+ )
diff --git a/saleor/graphql/discount/tests/test_bulk_delete.py b/saleor/graphql/discount/tests/test_bulk_delete.py
index 030460f5fc..4aa3fad542 100644
--- a/saleor/graphql/discount/tests/test_bulk_delete.py
+++ b/saleor/graphql/discount/tests/test_bulk_delete.py
@@ -1,23 +1,55 @@
import graphene
import pytest
-from ....discount.models import Sale, Voucher
+from ....discount.models import Sale, SaleChannelListing, Voucher, VoucherChannelListing
from ...tests.utils import get_graphql_content
@pytest.fixture
-def sale_list():
- sale_1 = Sale.objects.create(name="Sale 1", value=5)
- sale_2 = Sale.objects.create(name="Sale 2", value=5)
- sale_3 = Sale.objects.create(name="Sale 3", value=5)
- return sale_1, sale_2, sale_3
+def sale_list(channel_USD):
+ sales = Sale.objects.bulk_create(
+ [Sale(name="Sale 1"), Sale(name="Sale 2"), Sale(name="Sale 3")]
+ )
+ SaleChannelListing.objects.bulk_create(
+ [
+ SaleChannelListing(sale=sale, discount_value=5, channel=channel_USD)
+ for sale in sales
+ ]
+ )
+ return list(sales)
@pytest.fixture
-def voucher_list():
- voucher_1 = Voucher.objects.create(code="voucher-1", discount_value=1)
- voucher_2 = Voucher.objects.create(code="voucher-2", discount_value=2)
- voucher_3 = Voucher.objects.create(code="voucher-3", discount_value=3)
+def voucher_list(channel_USD):
+ [voucher_1, voucher_2, voucher_3] = Voucher.objects.bulk_create(
+ [
+ Voucher(code="voucher-1"),
+ Voucher(code="voucher-2"),
+ Voucher(code="voucher-3"),
+ ]
+ )
+ VoucherChannelListing.objects.bulk_create(
+ [
+ VoucherChannelListing(
+ voucher=voucher_1,
+ channel=channel_USD,
+ discount_value=1,
+ currency=channel_USD.currency_code,
+ ),
+ VoucherChannelListing(
+ voucher=voucher_2,
+ channel=channel_USD,
+ discount_value=2,
+ currency=channel_USD.currency_code,
+ ),
+ VoucherChannelListing(
+ voucher=voucher_3,
+ channel=channel_USD,
+ discount_value=3,
+ currency=channel_USD.currency_code,
+ ),
+ ]
+ )
return voucher_1, voucher_2, voucher_3
diff --git a/saleor/graphql/discount/tests/test_discount.py b/saleor/graphql/discount/tests/test_discount.py
index 68bd383825..f90c453163 100644
--- a/saleor/graphql/discount/tests/test_discount.py
+++ b/saleor/graphql/discount/tests/test_discount.py
@@ -1,5 +1,5 @@
from datetime import timedelta
-from decimal import Decimal
+from unittest.mock import ANY
import graphene
import pytest
@@ -8,16 +8,16 @@ from django_countries import countries
from ....discount import DiscountValueType, VoucherType
from ....discount.error_codes import DiscountErrorCode
-from ....discount.models import Sale, Voucher
+from ....discount.models import Sale, SaleChannelListing, Voucher
from ...tests.utils import get_graphql_content
from ..enums import DiscountValueTypeEnum, VoucherTypeEnum
@pytest.fixture
-def voucher_countries(voucher):
- voucher.countries = countries
- voucher.save(update_fields=["countries"])
- return voucher
+def voucher_with_many_channels_and_countries(voucher_with_many_channels):
+ voucher_with_many_channels.countries = countries
+ voucher_with_many_channels.save(update_fields=["countries"])
+ return voucher_with_many_channels
@pytest.fixture
@@ -56,22 +56,94 @@ def query_sales_with_filter():
return query
-def sale():
- return Sale.objects.create(name="Sale", value=123)
+def test_voucher_query(
+ staff_api_client,
+ voucher,
+ product,
+ permission_manage_discounts,
+ permission_manage_products,
+):
+ query = """
+ query vouchers {
+ vouchers(first: 1) {
+ edges {
+ node {
+ type
+ name
+ code
+ usageLimit
+ used
+ startDate
+ discountValueType
+ applyOncePerCustomer
+ products(first: 1) {
+ edges {
+ node {
+ name
+ }
+ }
+ }
+ countries {
+ code
+ country
+ }
+ channelListings {
+ id
+ channel {
+ slug
+ }
+ discountValue
+ currency
+ }
+ }
+ }
+ }
+ }
+ """
+ voucher.products.add(product)
+ response = staff_api_client.post_graphql(
+ query, permissions=[permission_manage_discounts, permission_manage_products]
+ )
-def voucher():
- return Voucher.objects.create(name="Voucher", discount_value=123)
+ content = get_graphql_content(response)
+ data = content["data"]["vouchers"]["edges"][0]["node"]
+ assert data["type"] == voucher.type.upper()
+ assert data["name"] == voucher.name
+ assert data["code"] == voucher.code
+ assert data["usageLimit"] == voucher.usage_limit
+ assert data["products"]["edges"][0]["node"]["name"] == product.name
-def test_voucher_query(
- staff_api_client, voucher_countries, permission_manage_discounts
+ assert data["applyOncePerCustomer"] == voucher.apply_once_per_customer
+ assert data["used"] == voucher.used
+ assert data["startDate"] == voucher.start_date.isoformat()
+ assert data["discountValueType"] == voucher.discount_value_type.upper()
+ assert data["countries"] == [
+ {"country": country.name, "code": country.code} for country in voucher.countries
+ ]
+ channel_listing = voucher.channel_listings.first()
+ assert {
+ "id": ANY,
+ "channel": {"slug": channel_listing.channel.slug},
+ "discountValue": channel_listing.discount_value,
+ "currency": channel_listing.channel.currency_code,
+ } in data["channelListings"]
+
+
+def test_voucher_query_with_channel_slug(
+ staff_api_client,
+ voucher_with_many_channels_and_countries,
+ permission_manage_discounts,
+ channel_USD,
+ product,
):
+ voucher = voucher_with_many_channels_and_countries
+ voucher.products.add(product)
+
query = """
- query vouchers {
- vouchers(first: 1) {
+ query vouchers($channel: String) {
+ vouchers(first: 1, channel: $channel) {
edges {
node {
type
@@ -81,47 +153,149 @@ def test_voucher_query(
used
startDate
discountValueType
- discountValue
applyOncePerCustomer
+ products(first: 1) {
+ edges {
+ node {
+ name
+ }
+ }
+ }
countries {
code
country
}
+ channelListings {
+ id
+ channel {
+ slug
+ }
+ discountValue
+ currency
+ }
}
}
}
}
"""
+ variables = {"channel": channel_USD.slug}
+
response = staff_api_client.post_graphql(
- query, permissions=[permission_manage_discounts]
+ query, variables, permissions=[permission_manage_discounts]
)
content = get_graphql_content(response)
data = content["data"]["vouchers"]["edges"][0]["node"]
- assert data["type"] == voucher_countries.type.upper()
- assert data["name"] == voucher_countries.name
- assert data["code"] == voucher_countries.code
- assert data["usageLimit"] == voucher_countries.usage_limit
- assert data["applyOncePerCustomer"] == voucher_countries.apply_once_per_customer
- assert data["used"] == voucher_countries.used
- assert data["startDate"] == voucher_countries.start_date.isoformat()
- assert data["discountValueType"] == voucher_countries.discount_value_type.upper()
- assert data["discountValue"] == voucher_countries.discount_value
+ assert data["type"] == voucher.type.upper()
+ assert data["name"] == voucher.name
+ assert data["code"] == voucher.code
+ assert data["products"]["edges"][0]["node"]["name"] == product.name
+ assert data["usageLimit"] == voucher.usage_limit
+ assert data["applyOncePerCustomer"] == voucher.apply_once_per_customer
+ assert data["used"] == voucher.used
+ assert data["startDate"] == voucher.start_date.isoformat()
+ assert data["discountValueType"] == voucher.discount_value_type.upper()
assert data["countries"] == [
- {"country": country.name, "code": country.code}
- for country in voucher_countries.countries
+ {"country": country.name, "code": country.code} for country in voucher.countries
]
+ assert len(data["channelListings"]) == 2
+ for channel_listing in voucher.channel_listings.all():
+ assert {
+ "id": ANY,
+ "channel": {"slug": channel_listing.channel.slug},
+ "discountValue": channel_listing.discount_value,
+ "currency": channel_listing.channel.currency_code,
+ } in data["channelListings"]
+
+
+def test_vouchers_query_with_channel_slug(
+ staff_api_client,
+ voucher_percentage,
+ voucher_with_many_channels,
+ permission_manage_discounts,
+ channel_PLN,
+ product,
+):
+
+ query = """
+ query vouchers($channel: String) {
+ vouchers(first: 2, channel: $channel) {
+ edges {
+ node {
+ name
+ }
+ }
+ }
+ }
+ """
+ variables = {"channel": channel_PLN.slug}
+
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_discounts]
+ )
+ content = get_graphql_content(response)
+ assert len(content["data"]["vouchers"]["edges"]) == 1
+
+
+def test_vouchers_query(
+ staff_api_client,
+ voucher_percentage,
+ voucher_with_many_channels,
+ permission_manage_discounts,
+ channel_PLN,
+ product,
+):
+
+ query = """
+ query vouchers {
+ vouchers(first: 2) {
+ edges {
+ node {
+ name
+ }
+ }
+ }
+ }
+ """
+
+ response = staff_api_client.post_graphql(
+ query, permissions=[permission_manage_discounts]
+ )
+ content = get_graphql_content(response)
+ assert len(content["data"]["vouchers"]["edges"]) == 2
-def test_sale_query(staff_api_client, sale, permission_manage_discounts):
+def test_sale_query(
+ staff_api_client,
+ sale,
+ permission_manage_discounts,
+ channel_USD,
+ permission_manage_products,
+):
query = """
query sales {
sales(first: 1) {
edges {
node {
type
+ products(first: 1) {
+ edges {
+ node {
+ name
+ }
+ }
+ }
+ collections(first: 1) {
+ edges {
+ node {
+ slug
+ }
+ }
+ }
name
- value
+ channelListings {
+ discountValue
+ }
startDate
}
}
@@ -129,28 +303,132 @@ def test_sale_query(staff_api_client, sale, permission_manage_discounts):
}
"""
response = staff_api_client.post_graphql(
- query, permissions=[permission_manage_discounts]
+ query, permissions=[permission_manage_discounts, permission_manage_products]
)
+ channel_listing_usd = sale.channel_listings.get(channel=channel_USD)
content = get_graphql_content(response)
data = content["data"]["sales"]["edges"][0]["node"]
+ assert data["products"]["edges"][0]["node"]["name"] == sale.products.first().name
+
assert data["type"] == sale.type.upper()
assert data["name"] == sale.name
- assert data["value"] == sale.value
+ assert (
+ data["channelListings"][0]["discountValue"]
+ == channel_listing_usd.discount_value
+ )
assert data["startDate"] == sale.start_date.isoformat()
+def test_sale_query_with_channel_slug(
+ staff_api_client, sale, permission_manage_discounts, channel_USD
+):
+ query = """
+ query sales($channel: String) {
+ sales(first: 1, channel: $channel) {
+ edges {
+ node {
+ type
+ products(first: 1) {
+ edges {
+ node {
+ name
+ }
+ }
+ }
+ discountValue
+ name
+ channelListings {
+ discountValue
+ }
+ startDate
+ }
+ }
+ }
+ }
+ """
+ variables = {"channel": channel_USD.slug}
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_discounts]
+ )
+ channel_listing = sale.channel_listings.get()
+ content = get_graphql_content(response)
+
+ data = content["data"]["sales"]["edges"][0]["node"]
+
+ assert data["type"] == sale.type.upper()
+ assert data["name"] == sale.name
+ assert data["products"]["edges"][0]["node"]["name"] == sale.products.first().name
+ assert data["discountValue"] == channel_listing.discount_value
+ assert data["channelListings"][0]["discountValue"] == channel_listing.discount_value
+ assert data["startDate"] == sale.start_date.isoformat()
+
+
+def test_sales_query(
+ staff_api_client,
+ sale_with_many_channels,
+ sale,
+ permission_manage_discounts,
+ channel_USD,
+ permission_manage_products,
+):
+ query = """
+ query sales {
+ sales(first: 2) {
+ edges {
+ node {
+ name
+ }
+ }
+ }
+ }
+ """
+ response = staff_api_client.post_graphql(
+ query, permissions=[permission_manage_discounts, permission_manage_products]
+ )
+ content = get_graphql_content(response)
+
+ assert len(content["data"]["sales"]["edges"]) == 2
+
+
+def test_sales_query_with_channel_slug(
+ staff_api_client,
+ sale_with_many_channels,
+ sale,
+ permission_manage_discounts,
+ channel_PLN,
+ permission_manage_products,
+):
+ query = """
+ query sales($channel: String) {
+ sales(first: 2, channel: $channel) {
+ edges {
+ node {
+ name
+ }
+ }
+ }
+ }
+ """
+ variables = {"channel": channel_PLN.slug}
+ response = staff_api_client.post_graphql(
+ query,
+ variables,
+ permissions=[permission_manage_discounts, permission_manage_products],
+ )
+ content = get_graphql_content(response)
+
+ assert len(content["data"]["sales"]["edges"]) == 1
+
+
CREATE_VOUCHER_MUTATION = """
mutation voucherCreate(
$type: VoucherTypeEnum, $name: String, $code: String,
$discountValueType: DiscountValueTypeEnum, $usageLimit: Int,
- $discountValue: PositiveDecimal,
- $minAmountSpent: PositiveDecimal, $minCheckoutItemsQuantity: Int,
- $startDate: DateTime, $endDate: DateTime, $applyOncePerOrder: Boolean,
- $applyOncePerCustomer: Boolean) {
+ $minCheckoutItemsQuantity: Int, $startDate: DateTime, $endDate: DateTime,
+ $applyOncePerOrder: Boolean, $applyOncePerCustomer: Boolean) {
voucherCreate(input: {
name: $name, type: $type, code: $code,
discountValueType: $discountValueType,
- discountValue: $discountValue, minAmountSpent: $minAmountSpent,
minCheckoutItemsQuantity: $minCheckoutItemsQuantity,
startDate: $startDate, endDate: $endDate, usageLimit: $usageLimit
applyOncePerOrder: $applyOncePerOrder,
@@ -162,9 +440,6 @@ mutation voucherCreate(
}
voucher {
type
- minSpent {
- amount
- }
minCheckoutItemsQuantity
name
code
@@ -187,8 +462,6 @@ def test_create_voucher(staff_api_client, permission_manage_discounts):
"type": VoucherTypeEnum.ENTIRE_ORDER.name,
"code": "testcode123",
"discountValueType": DiscountValueTypeEnum.FIXED.name,
- "discountValue": 10.12,
- "minAmountSpent": 1.12,
"minCheckoutItemsQuantity": 10,
"startDate": start_date.isoformat(),
"endDate": end_date.isoformat(),
@@ -203,7 +476,6 @@ def test_create_voucher(staff_api_client, permission_manage_discounts):
get_graphql_content(response)
voucher = Voucher.objects.get()
assert voucher.type == VoucherType.ENTIRE_ORDER
- assert voucher.min_spent_amount == Decimal("1.12")
assert voucher.name == "test voucher"
assert voucher.code == "testcode123"
assert voucher.discount_value_type == DiscountValueType.FIXED
@@ -266,33 +538,6 @@ def test_create_voucher_with_existing_gift_card_code(
assert errors[0]["code"] == DiscountErrorCode.ALREADY_EXISTS.name
-def test_create_voucher_with_too_many_decimal_values_in_min_spent(
- staff_api_client, permission_manage_discounts
-):
- start_date = timezone.now() - timedelta(days=365)
- end_date = timezone.now() + timedelta(days=365)
- variables = {
- "name": "test voucher",
- "type": VoucherTypeEnum.ENTIRE_ORDER.name,
- "code": "test123",
- "discountValueType": DiscountValueTypeEnum.FIXED.name,
- "discountValue": 10.12,
- "minAmountSpent": 1.1201,
- "startDate": start_date.isoformat(),
- "endDate": end_date.isoformat(),
- "usageLimit": None,
- }
-
- response = staff_api_client.post_graphql(
- CREATE_VOUCHER_MUTATION, variables, permissions=[permission_manage_discounts]
- )
- content = get_graphql_content(response)
- errors = content["data"]["voucherCreate"]["discountErrors"]
- assert len(errors) == 1
- assert errors[0]["field"] == "minSpentAmount"
- assert errors[0]["code"] == DiscountErrorCode.INVALID.name
-
-
def test_create_voucher_with_existing_voucher_code(
staff_api_client, voucher_shipping_type, permission_manage_discounts
):
@@ -409,6 +654,9 @@ def test_voucher_add_catalogues(
query = """
mutation voucherCataloguesAdd($id: ID!, $input: CatalogueInput!) {
voucherCataloguesAdd(id: $id, input: $input) {
+ voucher {
+ name
+ }
discountErrors {
field
code
@@ -441,6 +689,51 @@ def test_voucher_add_catalogues(
assert collection in voucher.collections.all()
+def test_voucher_add_catalogues_with_product_without_variant(
+ staff_api_client,
+ voucher,
+ category,
+ product,
+ collection,
+ permission_manage_discounts,
+):
+ query = """
+ mutation voucherCataloguesAdd($id: ID!, $input: CatalogueInput!) {
+ voucherCataloguesAdd(id: $id, input: $input) {
+ voucher {
+ name
+ }
+ discountErrors {
+ field
+ code
+ message
+ }
+ }
+ }
+ """
+ product.variants.all().delete()
+ product_id = graphene.Node.to_global_id("Product", product.id)
+ collection_id = graphene.Node.to_global_id("Collection", collection.id)
+ category_id = graphene.Node.to_global_id("Category", category.id)
+ variables = {
+ "id": graphene.Node.to_global_id("Voucher", voucher.id),
+ "input": {
+ "products": [product_id],
+ "collections": [collection_id],
+ "categories": [category_id],
+ },
+ }
+
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_discounts]
+ )
+ content = get_graphql_content(response)
+ error = content["data"]["voucherCataloguesAdd"]["discountErrors"][0]
+
+ assert error["code"] == DiscountErrorCode.CANNOT_MANAGE_PRODUCT_WITHOUT_VARIANT.name
+ assert error["message"] == "Cannot manage products without variants."
+
+
def test_voucher_remove_catalogues(
staff_api_client,
voucher,
@@ -456,6 +749,9 @@ def test_voucher_remove_catalogues(
query = """
mutation voucherCataloguesRemove($id: ID!, $input: CatalogueInput!) {
voucherCataloguesRemove(id: $id, input: $input) {
+ voucher {
+ name
+ }
discountErrors {
field
code
@@ -494,6 +790,9 @@ def test_voucher_add_no_catalogues(
query = """
mutation voucherCataloguesAdd($id: ID!, $input: CatalogueInput!) {
voucherCataloguesAdd(id: $id, input: $input) {
+ voucher {
+ name
+ }
discountErrors {
field
code
@@ -531,16 +830,19 @@ def test_voucher_remove_no_catalogues(
voucher.categories.add(category)
query = """
- mutation voucherCataloguesAdd($id: ID!, $input: CatalogueInput!) {
- voucherCataloguesAdd(id: $id, input: $input) {
- discountErrors {
- field
- code
- message
- }
+ mutation voucherCataloguesAdd($id: ID!, $input: CatalogueInput!) {
+ voucherCataloguesAdd(id: $id, input: $input) {
+ voucher {
+ name
+ }
+ discountErrors {
+ field
+ code
+ message
}
}
- """
+ }
+ """
variables = {
"id": graphene.Node.to_global_id("Voucher", voucher.id),
"input": {"products": [], "collections": [], "categories": []},
@@ -568,7 +870,6 @@ def test_create_sale(staff_api_client, permission_manage_discounts):
sale {
type
name
- value
startDate
endDate
}
@@ -585,7 +886,6 @@ def test_create_sale(staff_api_client, permission_manage_discounts):
variables = {
"name": "test sale",
"type": DiscountValueTypeEnum.FIXED.name,
- "value": "10.12",
"startDate": start_date.isoformat(),
"endDate": end_date.isoformat(),
}
@@ -598,7 +898,6 @@ def test_create_sale(staff_api_client, permission_manage_discounts):
assert data["type"] == DiscountValueType.FIXED.upper()
assert data["name"] == "test sale"
- assert data["value"] == 10.12
assert data["startDate"] == start_date.isoformat()
assert data["endDate"] == end_date.isoformat()
@@ -668,6 +967,9 @@ def test_sale_add_catalogues(
query = """
mutation saleCataloguesAdd($id: ID!, $input: CatalogueInput!) {
saleCataloguesAdd(id: $id, input: $input) {
+ sale {
+ name
+ }
discountErrors {
field
code
@@ -700,6 +1002,46 @@ def test_sale_add_catalogues(
assert collection in sale.collections.all()
+def test_sale_add_catalogues_with_product_without_variants(
+ staff_api_client, sale, category, product, collection, permission_manage_discounts
+):
+ query = """
+ mutation saleCataloguesAdd($id: ID!, $input: CatalogueInput!) {
+ saleCataloguesAdd(id: $id, input: $input) {
+ sale {
+ name
+ }
+ discountErrors {
+ field
+ code
+ message
+ }
+ }
+ }
+ """
+ product.variants.all().delete()
+ product_id = graphene.Node.to_global_id("Product", product.id)
+ collection_id = graphene.Node.to_global_id("Collection", collection.id)
+ category_id = graphene.Node.to_global_id("Category", category.id)
+ variables = {
+ "id": graphene.Node.to_global_id("Sale", sale.id),
+ "input": {
+ "products": [product_id],
+ "collections": [collection_id],
+ "categories": [category_id],
+ },
+ }
+
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_discounts]
+ )
+ content = get_graphql_content(response)
+ error = content["data"]["saleCataloguesAdd"]["discountErrors"][0]
+
+ assert error["code"] == DiscountErrorCode.CANNOT_MANAGE_PRODUCT_WITHOUT_VARIANT.name
+ assert error["message"] == "Cannot manage products without variants."
+
+
def test_sale_remove_catalogues(
staff_api_client, sale, category, product, collection, permission_manage_discounts
):
@@ -710,6 +1052,9 @@ def test_sale_remove_catalogues(
query = """
mutation saleCataloguesRemove($id: ID!, $input: CatalogueInput!) {
saleCataloguesRemove(id: $id, input: $input) {
+ sale {
+ name
+ }
discountErrors {
field
code
@@ -742,10 +1087,15 @@ def test_sale_remove_catalogues(
assert collection not in sale.collections.all()
-def test_sale_add_no_catalogues(staff_api_client, sale, permission_manage_discounts):
+def test_sale_add_no_catalogues(
+ staff_api_client, new_sale, permission_manage_discounts
+):
query = """
mutation saleCataloguesAdd($id: ID!, $input: CatalogueInput!) {
saleCataloguesAdd(id: $id, input: $input) {
+ sale {
+ name
+ }
discountErrors {
field
code
@@ -755,7 +1105,7 @@ def test_sale_add_no_catalogues(staff_api_client, sale, permission_manage_discou
}
"""
variables = {
- "id": graphene.Node.to_global_id("Sale", sale.id),
+ "id": graphene.Node.to_global_id("Sale", new_sale.id),
"input": {"products": [], "collections": [], "categories": []},
}
response = staff_api_client.post_graphql(
@@ -765,9 +1115,9 @@ def test_sale_add_no_catalogues(staff_api_client, sale, permission_manage_discou
data = content["data"]["saleCataloguesAdd"]
assert not data["discountErrors"]
- assert not sale.products.exists()
- assert not sale.categories.exists()
- assert not sale.collections.exists()
+ assert not new_sale.products.exists()
+ assert not new_sale.categories.exists()
+ assert not new_sale.collections.exists()
def test_sale_remove_no_catalogues(
@@ -780,6 +1130,9 @@ def test_sale_remove_no_catalogues(
query = """
mutation saleCataloguesAdd($id: ID!, $input: CatalogueInput!) {
saleCataloguesAdd(id: $id, input: $input) {
+ sale {
+ name
+ }
discountErrors {
field
code
@@ -838,18 +1191,9 @@ def test_query_vouchers_with_filter_status(
):
Voucher.objects.bulk_create(
[
+ Voucher(name="Voucher1", code="abc", start_date=timezone.now(),),
Voucher(
- name="Voucher1",
- discount_value=123,
- code="abc",
- start_date=timezone.now(),
- ),
- Voucher(
- name="Voucher2",
- discount_value=123,
- code="123",
- start_date=start_date,
- end_date=end_date,
+ name="Voucher2", code="123", start_date=start_date, end_date=end_date,
),
]
)
@@ -879,8 +1223,8 @@ def test_query_vouchers_with_filter_times_used(
):
Voucher.objects.bulk_create(
[
- Voucher(name="Voucher1", discount_value=123, code="abc"),
- Voucher(name="Voucher2", discount_value=123, code="123", used=2),
+ Voucher(name="Voucher1", code="abc"),
+ Voucher(name="Voucher2", code="123", used=2),
]
)
variables = {"filter": voucher_filter}
@@ -918,10 +1262,9 @@ def test_query_vouchers_with_filter_started(
):
Voucher.objects.bulk_create(
[
- Voucher(name="Voucher1", discount_value=123, code="abc"),
+ Voucher(name="Voucher1", code="abc"),
Voucher(
name="Voucher2",
- discount_value=123,
code="123",
start_date=timezone.now().replace(year=2012, month=1, day=5),
),
@@ -955,15 +1298,11 @@ def test_query_vouchers_with_filter_discount_type(
[
Voucher(
name="Voucher1",
- discount_value=123,
code="abc",
discount_value_type=DiscountValueType.FIXED,
),
Voucher(
- name="Voucher2",
- discount_value=123,
- code="123",
- discount_value_type=discount_value_type,
+ name="Voucher2", code="123", discount_value_type=discount_value_type,
),
]
)
@@ -988,8 +1327,8 @@ def test_query_vouchers_with_filter_search(
):
Voucher.objects.bulk_create(
[
- Voucher(name="The Biggest Voucher", discount_value=123, code="GIFT"),
- Voucher(name="Voucher2", discount_value=123, code="GIFT-COUPON"),
+ Voucher(name="The Biggest Voucher", code="GIFT"),
+ Voucher(name="Voucher2", code="GIFT-COUPON"),
]
)
variables = {"filter": voucher_filter}
@@ -1025,14 +1364,6 @@ QUERY_VOUCHER_WITH_SORT = """
{"field": "CODE", "direction": "DESC"},
["FreeShipping", "Voucher1", "Voucher2"],
),
- (
- {"field": "VALUE", "direction": "ASC"},
- ["Voucher2", "FreeShipping", "Voucher1"],
- ),
- (
- {"field": "VALUE", "direction": "DESC"},
- ["Voucher1", "FreeShipping", "Voucher2"],
- ),
(
{"field": "TYPE", "direction": "ASC"},
["Voucher1", "Voucher2", "FreeShipping"],
@@ -1065,14 +1396,6 @@ QUERY_VOUCHER_WITH_SORT = """
{"field": "USAGE_LIMIT", "direction": "DESC"},
["Voucher2", "FreeShipping", "Voucher1"],
),
- (
- {"field": "MINIMUM_SPENT_AMOUNT", "direction": "ASC"},
- ["Voucher2", "FreeShipping", "Voucher1"],
- ),
- (
- {"field": "MINIMUM_SPENT_AMOUNT", "direction": "DESC"},
- ["Voucher1", "FreeShipping", "Voucher2"],
- ),
],
)
def test_query_vouchers_with_sort(
@@ -1082,7 +1405,6 @@ def test_query_vouchers_with_sort(
[
Voucher(
name="Voucher1",
- discount_value=123,
code="abc",
discount_value_type=DiscountValueType.FIXED,
type=VoucherType.ENTIRE_ORDER,
@@ -1090,24 +1412,20 @@ def test_query_vouchers_with_sort(
),
Voucher(
name="Voucher2",
- discount_value=23,
code="123",
discount_value_type=DiscountValueType.FIXED,
type=VoucherType.ENTIRE_ORDER,
start_date=timezone.now().replace(year=2012, month=1, day=5),
end_date=timezone.now().replace(year=2013, month=1, day=5),
- min_spent_amount=50,
),
Voucher(
name="FreeShipping",
- discount_value=100,
code="xyz",
discount_value_type=DiscountValueType.PERCENTAGE,
type=VoucherType.SHIPPING,
start_date=timezone.now().replace(year=2011, month=1, day=5),
end_date=timezone.now().replace(year=2015, month=12, day=31),
usage_limit=1000,
- min_spent_amount=500,
),
]
)
@@ -1152,13 +1470,26 @@ def test_query_sales_with_filter_status(
staff_api_client,
query_sales_with_filter,
permission_manage_discounts,
+ channel_USD,
):
- Sale.objects.bulk_create(
+ sales = Sale.objects.bulk_create(
[
- Sale(name="Sale1", value=123, start_date=timezone.now()),
- Sale(name="Sale2", value=123, start_date=start_date, end_date=end_date),
+ Sale(name="Sale1", start_date=timezone.now()),
+ Sale(name="Sale2", start_date=start_date, end_date=end_date),
]
)
+ SaleChannelListing.objects.bulk_create(
+ [
+ SaleChannelListing(
+ sale=sale,
+ discount_value=123,
+ channel=channel_USD,
+ currency=channel_USD.currency_code,
+ )
+ for sale in sales
+ ]
+ )
+
variables = {"filter": sale_filter}
response = staff_api_client.post_graphql(
query_sales_with_filter, variables, permissions=[permission_manage_discounts]
@@ -1185,8 +1516,8 @@ def test_query_sales_with_filter_discount_type(
):
Sale.objects.bulk_create(
[
- Sale(name="Sale1", value=123, type=DiscountValueType.FIXED),
- Sale(name="Sale2", value=123, type=sale_type),
+ Sale(name="Sale1", type=DiscountValueType.FIXED),
+ Sale(name="Sale2", type=sale_type),
]
)
variables = {"filter": sale_filter}
@@ -1221,17 +1552,29 @@ def test_query_sales_with_filter_started(
staff_api_client,
query_sales_with_filter,
permission_manage_discounts,
+ channel_USD,
):
- Sale.objects.bulk_create(
+ sales = Sale.objects.bulk_create(
[
- Sale(name="Sale1", value=123),
+ Sale(name="Sale1"),
Sale(
name="Sale2",
- value=123,
start_date=timezone.now().replace(year=2012, month=1, day=5),
),
]
)
+ SaleChannelListing.objects.bulk_create(
+ [
+ SaleChannelListing(
+ sale=sale,
+ discount_value=123,
+ channel=channel_USD,
+ currency=channel_USD.currency_code,
+ )
+ for sale in sales
+ ]
+ )
+
variables = {"filter": sale_filter}
response = staff_api_client.post_graphql(
query_sales_with_filter, variables, permissions=[permission_manage_discounts]
@@ -1251,24 +1594,30 @@ def test_query_sales_with_filter_search(
staff_api_client,
query_sales_with_filter,
permission_manage_discounts,
+ channel_USD,
):
- Sale.objects.bulk_create(
+ sales = Sale.objects.bulk_create(
[
- Sale(name="BigSale", value=123, type="PERCENTAGE"),
+ Sale(name="BigSale", type="PERCENTAGE"),
Sale(
name="Sale2",
- value=123,
type="FIXED",
start_date=timezone.now().replace(year=2012, month=1, day=5),
),
Sale(
name="Sale3",
- value=69,
type="FIXED",
start_date=timezone.now().replace(year=2012, month=1, day=5),
),
]
)
+ values = [123, 123, 69]
+ SaleChannelListing.objects.bulk_create(
+ [
+ SaleChannelListing(channel=channel_USD, discount_value=values[i], sale=sale)
+ for i, sale in enumerate(sales)
+ ]
+ )
variables = {"filter": sale_filter}
response = staff_api_client.post_graphql(
query_sales_with_filter, variables, permissions=[permission_manage_discounts]
@@ -1296,8 +1645,6 @@ QUERY_SALE_WITH_SORT = """
[
({"field": "NAME", "direction": "ASC"}, ["BigSale", "Sale2", "Sale3"]),
({"field": "NAME", "direction": "DESC"}, ["Sale3", "Sale2", "BigSale"]),
- ({"field": "VALUE", "direction": "ASC"}, ["Sale3", "Sale2", "BigSale"]),
- ({"field": "VALUE", "direction": "DESC"}, ["BigSale", "Sale2", "Sale3"]),
({"field": "TYPE", "direction": "ASC"}, ["Sale2", "Sale3", "BigSale"]),
({"field": "TYPE", "direction": "DESC"}, ["BigSale", "Sale3", "Sale2"]),
({"field": "START_DATE", "direction": "ASC"}, ["Sale3", "Sale2", "BigSale"]),
@@ -1307,21 +1654,19 @@ QUERY_SALE_WITH_SORT = """
],
)
def test_query_sales_with_sort(
- sale_sort, result_order, staff_api_client, permission_manage_discounts
+ sale_sort, result_order, staff_api_client, permission_manage_discounts, channel_USD
):
- Sale.objects.bulk_create(
+ sales = Sale.objects.bulk_create(
[
- Sale(name="BigSale", value=1234, type="PERCENTAGE"),
+ Sale(name="BigSale", type="PERCENTAGE"),
Sale(
name="Sale2",
- value=123,
type="FIXED",
start_date=timezone.now().replace(year=2012, month=1, day=5),
end_date=timezone.now().replace(year=2013, month=1, day=5),
),
Sale(
name="Sale3",
- value=69,
type="FIXED",
start_date=timezone.now().replace(year=2011, month=1, day=5),
end_date=timezone.now().replace(year=2015, month=12, day=31),
diff --git a/saleor/graphql/discount/tests/test_pagination.py b/saleor/graphql/discount/tests/test_pagination.py
index 02c9f2d8eb..455553fd4a 100644
--- a/saleor/graphql/discount/tests/test_pagination.py
+++ b/saleor/graphql/discount/tests/test_pagination.py
@@ -5,47 +5,49 @@ from django.utils import timezone
from freezegun import freeze_time
from ....discount import DiscountValueType, VoucherType
-from ....discount.models import Sale, Voucher
+from ....discount.models import Sale, SaleChannelListing, Voucher, VoucherChannelListing
from ...tests.utils import get_graphql_content
@pytest.fixture
@freeze_time("2020-03-18 12:00:00")
-def sales_for_pagination(db):
+def sales_for_pagination(channel_USD):
now = timezone.now()
- return Sale.objects.bulk_create(
+ sales = Sale.objects.bulk_create(
[
Sale(
name="Sale1",
start_date=now + timezone.timedelta(hours=4),
end_date=now + timezone.timedelta(hours=14),
type=DiscountValueType.PERCENTAGE,
- value=Decimal("1"),
- ),
- Sale(
- name="Sale2",
- end_date=now + timezone.timedelta(hours=1),
- value=Decimal("7"),
),
+ Sale(name="Sale2", end_date=now + timezone.timedelta(hours=1),),
Sale(
name="Sale3",
end_date=now + timezone.timedelta(hours=2),
type=DiscountValueType.PERCENTAGE,
- value=Decimal("5"),
- ),
- Sale(
- name="Sale4",
- end_date=now + timezone.timedelta(hours=1),
- value=Decimal("5"),
),
+ Sale(name="Sale4", end_date=now + timezone.timedelta(hours=1),),
Sale(
name="Sale15",
start_date=now + timezone.timedelta(hours=1),
end_date=now + timezone.timedelta(hours=2),
- value=Decimal("25"),
),
]
)
+ values = [Decimal("1"), Decimal("7"), Decimal("5"), Decimal("5"), Decimal("25")]
+ SaleChannelListing.objects.bulk_create(
+ [
+ SaleChannelListing(
+ discount_value=values[i],
+ sale=sale,
+ channel=channel_USD,
+ currency=channel_USD.currency_code,
+ )
+ for i, sale in enumerate(sales)
+ ]
+ )
+ return sales
QUERY_SALES_PAGINATION = """
@@ -80,7 +82,6 @@ QUERY_SALES_PAGINATION = """
({"field": "NAME", "direction": "DESC"}, ["Sale4", "Sale3", "Sale2"]),
({"field": "START_DATE", "direction": "ASC"}, ["Sale2", "Sale3", "Sale4"]),
({"field": "END_DATE", "direction": "ASC"}, ["Sale2", "Sale4", "Sale15"]),
- ({"field": "VALUE", "direction": "ASC"}, ["Sale1", "Sale3", "Sale4"]),
({"field": "TYPE", "direction": "ASC"}, ["Sale15", "Sale2", "Sale4"]),
],
)
@@ -108,6 +109,28 @@ def test_sales_pagination_with_sorting(
assert len(sales_nodes) == page_size
+def test_sales_pagination_with_sorting_and_channel(
+ staff_api_client, permission_manage_discounts, sales_for_pagination, channel_USD,
+):
+ page_size = 3
+ sales_order = ["Sale1", "Sale3", "Sale4"]
+ sort_by = {"field": "VALUE", "direction": "ASC", "channel": channel_USD.slug}
+
+ variables = {"first": page_size, "after": None, "sortBy": sort_by}
+ response = staff_api_client.post_graphql(
+ QUERY_SALES_PAGINATION,
+ variables,
+ permissions=[permission_manage_discounts],
+ check_no_permissions=False,
+ )
+ content = get_graphql_content(response)
+ sales_nodes = content["data"]["sales"]["edges"]
+ assert sales_order[0] == sales_nodes[0]["node"]["name"]
+ assert sales_order[1] == sales_nodes[1]["node"]["name"]
+ assert sales_order[2] == sales_nodes[2]["node"]["name"]
+ assert len(sales_nodes) == page_size
+
+
@pytest.mark.parametrize(
"filter_by, sales_order",
[
@@ -145,9 +168,9 @@ def test_sales_pagination_with_filtering(
@pytest.fixture
@freeze_time("2020-03-18 12:00:00")
-def vouchers_for_pagination(db):
+def vouchers_for_pagination(db, channel_USD):
now = timezone.now()
- return Voucher.objects.bulk_create(
+ vouchers = Voucher.objects.bulk_create(
[
Voucher(
code="Code1",
@@ -155,8 +178,6 @@ def vouchers_for_pagination(db):
start_date=now + timezone.timedelta(hours=4),
end_date=now + timezone.timedelta(hours=14),
discount_value_type=DiscountValueType.PERCENTAGE,
- discount_value=Decimal("1"),
- min_spent_amount=Decimal("10"),
usage_limit=10,
type=VoucherType.SPECIFIC_PRODUCT,
),
@@ -164,8 +185,6 @@ def vouchers_for_pagination(db):
code="Code2",
name="Voucher2",
end_date=now + timezone.timedelta(hours=1),
- discount_value=Decimal("7"),
- min_spent_amount=Decimal("10"),
usage_limit=1000,
used=10,
type=VoucherType.ENTIRE_ORDER,
@@ -175,8 +194,6 @@ def vouchers_for_pagination(db):
name="Voucher3",
end_date=now + timezone.timedelta(hours=2),
discount_value_type=DiscountValueType.PERCENTAGE,
- discount_value=Decimal("5"),
- min_spent_amount=Decimal("120"),
usage_limit=100,
used=35,
type=VoucherType.ENTIRE_ORDER,
@@ -185,8 +202,6 @@ def vouchers_for_pagination(db):
code="Code4",
name="Voucher4",
end_date=now + timezone.timedelta(hours=1),
- discount_value=Decimal("5"),
- min_spent_amount=Decimal("50"),
usage_limit=100,
type=VoucherType.SPECIFIC_PRODUCT,
),
@@ -196,12 +211,50 @@ def vouchers_for_pagination(db):
start_date=now + timezone.timedelta(hours=1),
end_date=now + timezone.timedelta(hours=5),
discount_value_type=DiscountValueType.PERCENTAGE,
- discount_value=Decimal("2"),
- min_spent_amount=Decimal("100"),
usage_limit=10,
),
]
)
+ VoucherChannelListing.objects.bulk_create(
+ [
+ VoucherChannelListing(
+ voucher=vouchers[0],
+ channel=channel_USD,
+ discount_value=1,
+ min_spent_amount=10,
+ currency=channel_USD.currency_code,
+ ),
+ VoucherChannelListing(
+ voucher=vouchers[1],
+ channel=channel_USD,
+ discount_value=7,
+ min_spent_amount=10,
+ currency=channel_USD.currency_code,
+ ),
+ VoucherChannelListing(
+ voucher=vouchers[2],
+ channel=channel_USD,
+ discount_value=5,
+ min_spent_amount=12,
+ currency=channel_USD.currency_code,
+ ),
+ VoucherChannelListing(
+ voucher=vouchers[3],
+ channel=channel_USD,
+ discount_value=5,
+ min_spent_amount=50,
+ currency=channel_USD.currency_code,
+ ),
+ VoucherChannelListing(
+ voucher=vouchers[4],
+ channel=channel_USD,
+ discount_value=2,
+ min_spent_amount=100,
+ currency=channel_USD.currency_code,
+ ),
+ ]
+ )
+ return vouchers
QUERY_VOUCHERS_PAGINATION = """
@@ -242,27 +295,58 @@ QUERY_VOUCHERS_PAGINATION = """
{"field": "END_DATE", "direction": "ASC"},
["Voucher2", "Voucher4", "Voucher3"],
),
- ({"field": "VALUE", "direction": "ASC"}, ["Voucher1", "Voucher15", "Voucher3"]),
({"field": "TYPE", "direction": "ASC"}, ["Voucher15", "Voucher2", "Voucher3"]),
(
{"field": "USAGE_LIMIT", "direction": "ASC"},
["Voucher1", "Voucher15", "Voucher3"],
),
+ ],
+)
+def test_vouchers_pagination_with_sorting(
+ sort_by,
+ vouchers_order,
+ staff_api_client,
+ permission_manage_discounts,
+ vouchers_for_pagination,
+):
+ page_size = 3
+
+ variables = {"first": page_size, "after": None, "sortBy": sort_by}
+ response = staff_api_client.post_graphql(
+ QUERY_VOUCHERS_PAGINATION,
+ variables,
+ permissions=[permission_manage_discounts],
+ check_no_permissions=False,
+ )
+ content = get_graphql_content(response)
+ vouchers_nodes = content["data"]["vouchers"]["edges"]
+ assert vouchers_order[0] == vouchers_nodes[0]["node"]["name"]
+ assert vouchers_order[1] == vouchers_nodes[1]["node"]["name"]
+ assert vouchers_order[2] == vouchers_nodes[2]["node"]["name"]
+ assert len(vouchers_nodes) == page_size
+
+
+ "sort_by, vouchers_order",
+ [
+ ({"field": "VALUE", "direction": "ASC"}, ["Voucher1", "Voucher15", "Voucher3"]),
(
{"field": "MINIMUM_SPENT_AMOUNT", "direction": "ASC"},
- ["Voucher1", "Voucher2", "Voucher4"],
+ ["Voucher1", "Voucher2", "Voucher3"],
),
],
)
-def test_vouchers_pagination_with_sorting(
+def test_vouchers_pagination_with_sorting_and_channel(
sort_by,
vouchers_order,
staff_api_client,
permission_manage_discounts,
vouchers_for_pagination,
+ channel_USD,
):
page_size = 3
+ sort_by["channel"] = channel_USD.slug
variables = {"first": page_size, "after": None, "sortBy": sort_by}
response = staff_api_client.post_graphql(
QUERY_VOUCHERS_PAGINATION,
diff --git a/saleor/graphql/discount/tests/test_sale_channel_listing.py b/saleor/graphql/discount/tests/test_sale_channel_listing.py
new file mode 100644
index 0000000000..28f4dbf2ea
--- /dev/null
+++ b/saleor/graphql/discount/tests/test_sale_channel_listing.py
@@ -0,0 +1,278 @@
+from unittest.mock import patch
+
+import graphene
+
+from ....discount.error_codes import DiscountErrorCode
+from ....discount.models import SaleChannelListing
+from ...tests.utils import assert_negative_positive_decimal_value, get_graphql_content
+
+SALE_CHANNEL_LISTING_UPDATE_MUTATION = """
+mutation UpdateSaleChannelListing(
+ $id: ID!
+ $input: SaleChannelListingInput!
+) {
+ saleChannelListingUpdate(id: $id, input: $input) {
+ discountErrors {
+ field
+ message
+ code
+ channels
+ }
+ sale {
+ name
+ channelListings {
+ discountValue
+ channel {
+ slug
+ }
+ }
+ }
+ }
+}
+"""
+
+
+@patch(
+ "saleor.graphql.discount.mutations"
+ ".update_products_discounted_prices_of_discount_task"
+)
+def test_sale_channel_listing_create_as_staff_user(
+ mock_update_discounted_prices_of_discount_task,
+ staff_api_client,
+ sale,
+ permission_manage_discounts,
+ channel_PLN,
+):
+ # given
+ sale_id = graphene.Node.to_global_id("Sale", sale.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ discounted = 1.12
+
+ variables = {
+ "id": sale_id,
+ "input": {
+ "addChannels": [{"channelId": channel_id, "discountValue": discounted}]
+ },
+ }
+
+ # when
+
+ response = staff_api_client.post_graphql(
+ SALE_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_discounts,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["saleChannelListingUpdate"]
+ shipping_method_data = data["sale"]
+ assert not data["discountErrors"]
+ assert shipping_method_data["name"] == sale.name
+
+ assert shipping_method_data["channelListings"][1]["discountValue"] == discounted
+ assert (
+ shipping_method_data["channelListings"][1]["channel"]["slug"]
+ == channel_PLN.slug
+ )
+ mock_update_discounted_prices_of_discount_task.delay.assert_called_once_with(
+ sale.pk,
+ )
+
+
+@patch(
+ "saleor.graphql.discount.mutations"
+ ".update_products_discounted_prices_of_discount_task"
+)
+def test_sale_channel_listing_update_as_staff_user(
+ mock_update_discounted_prices_of_discount_task,
+ staff_api_client,
+ sale,
+ permission_manage_discounts,
+ channel_USD,
+):
+ # given
+ sale_id = graphene.Node.to_global_id("Sale", sale.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ discounted = 10.11
+
+ variables = {
+ "id": sale_id,
+ "input": {
+ "addChannels": [{"channelId": channel_id, "discountValue": discounted}]
+ },
+ }
+ channel_listing = SaleChannelListing.objects.get(
+ sale_id=sale.pk, channel_id=channel_USD.id
+ )
+ assert channel_listing.discount_value == 5
+
+ # when
+
+ response = staff_api_client.post_graphql(
+ SALE_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_discounts,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["saleChannelListingUpdate"]
+ shipping_method_data = data["sale"]
+ assert not data["discountErrors"]
+
+ assert shipping_method_data["channelListings"][0]["discountValue"] == discounted
+ mock_update_discounted_prices_of_discount_task.delay.assert_called_once_with(
+ sale.pk,
+ )
+
+
+def test_sale_channel_listing_update_with_negative_discounted_value(
+ staff_api_client, sale, permission_manage_discounts, channel_USD,
+):
+ # given
+ sale_id = graphene.Node.to_global_id("Sale", sale.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ discounted_value = -10
+
+ variables = {
+ "id": sale_id,
+ "input": {
+ "addChannels": [
+ {"channelId": channel_id, "discountValue": discounted_value}
+ ]
+ },
+ }
+ channel_listing = SaleChannelListing.objects.get(
+ sale_id=sale.pk, channel_id=channel_USD.id
+ )
+ assert channel_listing.discount_value == 5
+
+ # when
+ staff_api_client.user.user_permissions.add(permission_manage_discounts)
+
+ response = staff_api_client.post_graphql(
+ SALE_CHANNEL_LISTING_UPDATE_MUTATION, variables=variables,
+ )
+ assert_negative_positive_decimal_value(response)
+
+
+def test_sale_channel_listing_update_duplicated_ids_in_add_and_remove(
+ staff_api_client, sale, permission_manage_discounts, channel_USD
+):
+ # given
+ sale_id = graphene.Node.to_global_id("Sale", sale.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ discounted = 10.11
+ variables = {
+ "id": sale_id,
+ "input": {
+ "addChannels": [{"channelId": channel_id, "discountValue": discounted}],
+ "removeChannels": [channel_id],
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ SALE_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_discounts,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ errors = content["data"]["saleChannelListingUpdate"]["discountErrors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "input"
+ assert errors[0]["code"] == DiscountErrorCode.DUPLICATED_INPUT_ITEM.name
+ assert errors[0]["channels"] == [channel_id]
+
+
+def test_sale_channel_listing_update_duplicated_channel_in_add(
+ staff_api_client, sale, permission_manage_discounts, channel_USD
+):
+ # given
+ sale_id = graphene.Node.to_global_id("Sale", sale.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ discounted = 10.11
+ variables = {
+ "id": sale_id,
+ "input": {
+ "addChannels": [
+ {"channelId": channel_id, "discountValue": discounted},
+ {"channelId": channel_id, "discountValue": discounted},
+ ],
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ SALE_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_discounts,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ errors = content["data"]["saleChannelListingUpdate"]["discountErrors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "addChannels"
+ assert errors[0]["code"] == DiscountErrorCode.DUPLICATED_INPUT_ITEM.name
+ assert errors[0]["channels"] == [channel_id]
+
+
+def test_sale_channel_listing_update_duplicated_channel_in_remove(
+ staff_api_client, sale, permission_manage_discounts, channel_USD
+):
+ # given
+ sale_id = graphene.Node.to_global_id("Sale", sale.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": sale_id,
+ "input": {"removeChannels": [channel_id, channel_id]},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ SALE_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_discounts,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ errors = content["data"]["saleChannelListingUpdate"]["discountErrors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "removeChannels"
+ assert errors[0]["code"] == DiscountErrorCode.DUPLICATED_INPUT_ITEM.name
+ assert errors[0]["channels"] == [channel_id]
+
+
+def test_sale_channel_listing_update_with_invalid_decimal_places(
+ staff_api_client, sale, permission_manage_discounts, channel_USD
+):
+ # given
+ sale_id = graphene.Node.to_global_id("Sale", sale.pk)
+ discounted = 1.123
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": sale_id,
+ "input": {
+ "addChannels": [{"channelId": channel_id, "discountValue": discounted}],
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ SALE_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_discounts,),
+ )
+ content = get_graphql_content(response)
+ # then
+ errors = content["data"]["saleChannelListingUpdate"]["discountErrors"]
+
+ assert len(errors) == 1
+ assert errors[0]["code"] == DiscountErrorCode.INVALID.name
+ assert errors[0]["field"] == "input"
+ assert errors[0]["channels"] == [channel_id]
diff --git a/saleor/graphql/discount/tests/test_sale_sorting_with_channels.py b/saleor/graphql/discount/tests/test_sale_sorting_with_channels.py
new file mode 100644
index 0000000000..87fdaea515
--- /dev/null
+++ b/saleor/graphql/discount/tests/test_sale_sorting_with_channels.py
@@ -0,0 +1,221 @@
+import pytest
+
+from ....discount import DiscountValueType
+from ....discount.models import Sale, SaleChannelListing
+from ...channel.sorters import LACK_OF_CHANNEL_IN_SORTING_MSG
+from ...tests.utils import assert_graphql_error_with_message, get_graphql_content
+
+
+def sales_for_sorting_with_channels(db, channel_USD, channel_PLN):
+ sales = Sale.objects.bulk_create(
+ [
+ Sale(name="Sale1", type=DiscountValueType.PERCENTAGE,),
+ Sale(name="Sale2"),
+ Sale(name="Sale3", type=DiscountValueType.PERCENTAGE,),
+ Sale(name="Sale4"),
+ Sale(name="Sale15"),
+ ]
+ )
+ SaleChannelListing.objects.bulk_create(
+ [
+ SaleChannelListing(
+ discount_value=1,
+ sale=sales[0],
+ channel=channel_USD,
+ currency=channel_USD.currency_code,
+ ),
+ SaleChannelListing(
+ discount_value=7,
+ sale=sales[1],
+ channel=channel_USD,
+ currency=channel_USD.currency_code,
+ ),
+ SaleChannelListing(
+ discount_value=5,
+ sale=sales[2],
+ channel=channel_USD,
+ currency=channel_USD.currency_code,
+ ),
+ SaleChannelListing(
+ discount_value=2,
+ sale=sales[4],
+ channel=channel_USD,
+ currency=channel_USD.currency_code,
+ ),
+ # Second channel
+ SaleChannelListing(
+ discount_value=7,
+ sale=sales[0],
+ channel=channel_PLN,
+ currency=channel_PLN.currency_code,
+ ),
+ SaleChannelListing(
+ discount_value=1,
+ sale=sales[1],
+ channel=channel_PLN,
+ currency=channel_PLN.currency_code,
+ ),
+ SaleChannelListing(
+ discount_value=2,
+ sale=sales[3],
+ channel=channel_PLN,
+ currency=channel_PLN.currency_code,
+ ),
+ SaleChannelListing(
+ discount_value=5,
+ sale=sales[4],
+ channel=channel_PLN,
+ currency=channel_PLN.currency_code,
+ ),
+ ]
+ )
+ return sales
+
+
+QUERY_SALES_WITH_SORTING_AND_FILTERING = """
+ query (
+ $sortBy: SaleSortingInput, $filter: SaleFilterInput
+ ){
+ sales (
+ first: 10, sortBy: $sortBy, filter: $filter
+ ) {
+ edges {
+ node {
+ name
+ }
+ }
+ }
+ }
+"""
+
+
+def test_sales_with_sorting_and_without_channel(
+ staff_api_client, permission_manage_discounts,
+):
+ # given
+ variables = {"sortBy": {"field": "VALUE", "direction": "ASC"}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_SALES_WITH_SORTING_AND_FILTERING,
+ variables,
+ permissions=[permission_manage_discounts],
+ check_no_permissions=False,
+ )
+
+ # then
+ assert_graphql_error_with_message(response, LACK_OF_CHANNEL_IN_SORTING_MSG)
+
+
+ "sort_by, sales_order",
+ [
+ (
+ {"field": "VALUE", "direction": "ASC"},
+ ["Sale1", "Sale15", "Sale3", "Sale2", "Sale4"],
+ ),
+ (
+ {"field": "VALUE", "direction": "DESC"},
+ ["Sale4", "Sale2", "Sale3", "Sale15", "Sale1"],
+ ),
+ ],
+)
+def test_sales_with_sorting_and_channel_USD(
+ sort_by,
+ sales_order,
+ staff_api_client,
+ permission_manage_discounts,
+ sales_for_sorting_with_channels,
+ channel_USD,
+):
+ # given
+ sort_by["channel"] = channel_USD.slug
+ variables = {"sortBy": sort_by}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_SALES_WITH_SORTING_AND_FILTERING,
+ variables,
+ permissions=[permission_manage_discounts],
+ check_no_permissions=False,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ sales_nodes = content["data"]["sales"]["edges"]
+ for index, sale_name in enumerate(sales_order):
+ assert sale_name == sales_nodes[index]["node"]["name"]
+
+
+ "sort_by, sales_order",
+ [
+ (
+ {"field": "VALUE", "direction": "ASC"},
+ ["Sale2", "Sale4", "Sale15", "Sale1", "Sale3"],
+ ),
+ (
+ {"field": "VALUE", "direction": "DESC"},
+ ["Sale3", "Sale1", "Sale15", "Sale4", "Sale2"],
+ ),
+ ],
+)
+def test_sales_with_sorting_and_channel_PLN(
+ sort_by,
+ sales_order,
+ staff_api_client,
+ permission_manage_discounts,
+ sales_for_sorting_with_channels,
+ channel_PLN,
+):
+ # given
+ sort_by["channel"] = channel_PLN.slug
+ variables = {"sortBy": sort_by}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_SALES_WITH_SORTING_AND_FILTERING,
+ variables,
+ permissions=[permission_manage_discounts],
+ check_no_permissions=False,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ sales_nodes = content["data"]["sales"]["edges"]
+ for index, sale_name in enumerate(sales_order):
+ assert sale_name == sales_nodes[index]["node"]["name"]
+
+
+def test_vouchers_with_sorting_and_not_existing_channel_asc(
+ staff_api_client,
+ permission_manage_discounts,
+ sales_for_sorting_with_channels,
+ channel_USD,
+):
+ # given
+ sales_order = [
+ "Sale1",
+ "Sale15",
+ "Sale2",
+ "Sale3",
+ "Sale4",
+ ]
+ variables = {
+ "sortBy": {"field": "VALUE", "direction": "ASC", "channel": "Not-existing"}
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_SALES_WITH_SORTING_AND_FILTERING,
+ variables,
+ permissions=[permission_manage_discounts],
+ check_no_permissions=False,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ sales_nodes = content["data"]["sales"]["edges"]
+ for index, sale_name in enumerate(sales_order):
+ assert sale_name == sales_nodes[index]["node"]["name"]
diff --git a/saleor/graphql/discount/tests/test_voucher_channel_listing.py b/saleor/graphql/discount/tests/test_voucher_channel_listing.py
new file mode 100644
index 0000000000..3b3935532b
--- /dev/null
+++ b/saleor/graphql/discount/tests/test_voucher_channel_listing.py
@@ -0,0 +1,595 @@
+import graphene
+
+from ....discount.error_codes import DiscountErrorCode
+from ...tests.utils import assert_no_permission, get_graphql_content
+
+VOUCHER_CHANNEL_LISTING_UPDATE_MUTATION = """
+mutation UpdateVoucherChannelListing($id: ID!, $input: VoucherChannelListingInput!) {
+ voucherChannelListingUpdate(id: $id, input: $input) {
+ discountErrors {
+ field
+ message
+ code
+ channels
+ }
+ voucher {
+ code
+ channelListings {
+ channel{
+ slug
+ }
+ discountValue
+ currency
+ minSpent {
+ currency
+ amount
+ }
+ }
+ }
+ }
+}
+"""
+
+
+def test_voucher_channel_listing_create_as_staff(
+ staff_api_client, voucher_without_channel, permission_manage_discounts, channel_USD
+):
+ # given
+ voucher = voucher_without_channel
+ voucher_id = graphene.Node.to_global_id("Voucher", voucher.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ discount_value = 5.5
+ variables = {
+ "id": voucher_id,
+ "input": {
+ "addChannels": [{"channelId": channel_id, "discountValue": discount_value}]
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ VOUCHER_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_discounts,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["voucherChannelListingUpdate"]["voucher"]
+ assert not content["data"]["voucherChannelListingUpdate"]["discountErrors"]
+ channel_listing = data["channelListings"]
+ assert channel_listing[0]["channel"]["slug"] == channel_USD.slug
+ assert channel_listing[0]["discountValue"] == discount_value
+ assert channel_listing[0]["currency"] == channel_USD.currency_code
+
+
+def test_voucher_channel_listing_update_as_app(
+ app_api_client, voucher_without_channel, permission_manage_discounts, channel_USD
+):
+ # given
+ voucher = voucher_without_channel
+ voucher_id = graphene.Node.to_global_id("Voucher", voucher.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ discount_value = 5.5
+ variables = {
+ "id": voucher_id,
+ "input": {
+ "addChannels": [{"channelId": channel_id, "discountValue": discount_value}]
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ VOUCHER_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_discounts,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["voucherChannelListingUpdate"]["voucher"]
+ assert not content["data"]["voucherChannelListingUpdate"]["discountErrors"]
+ channel_listing = data["channelListings"]
+ assert channel_listing[0]["channel"]["slug"] == channel_USD.slug
+ assert channel_listing[0]["discountValue"] == discount_value
+ assert channel_listing[0]["currency"] == channel_USD.currency_code
+
+
+def test_voucher_channel_listing_update_as_customer(
+ user_api_client, voucher_without_channel, channel_USD
+):
+ # given
+ voucher = voucher_without_channel
+ voucher_id = graphene.Node.to_global_id("Voucher", voucher.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": voucher_id,
+ "input": {"addChannels": [{"channelId": channel_id, "discountValue": 5.5}]},
+ }
+
+ # when
+ response = user_api_client.post_graphql(
+ VOUCHER_CHANNEL_LISTING_UPDATE_MUTATION, variables=variables,
+ )
+
+ # then
+ assert_no_permission(response)
+
+
+def test_voucher_channel_listing_update_as_anonymous(
+ api_client, voucher_without_channel, channel_USD
+):
+ # given
+ voucher = voucher_without_channel
+ voucher_id = graphene.Node.to_global_id("Voucher", voucher.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": voucher_id,
+ "input": {"addChannels": [{"channelId": channel_id, "discountValue": 5.5}]},
+ }
+
+ # when
+ response = api_client.post_graphql(
+ VOUCHER_CHANNEL_LISTING_UPDATE_MUTATION, variables=variables,
+ )
+
+ # then
+ assert_no_permission(response)
+
+
+def test_voucher_channel_listing_create_many_channel(
+ staff_api_client,
+ voucher_without_channel,
+ permission_manage_discounts,
+ channel_USD,
+ channel_PLN,
+):
+ # given
+ voucher = voucher_without_channel
+ voucher_id = graphene.Node.to_global_id("Voucher", voucher.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ channel_pln_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ discount_value = 5.5
+ discount_value_pln = 50.5
+ min_amount_spent = 10.1
+ min_amount_spent_pln = 100.2
+ variables = {
+ "id": voucher_id,
+ "input": {
+ "addChannels": [
+ {
+ "channelId": channel_id,
+ "discountValue": discount_value,
+ "minAmountSpent": min_amount_spent,
+ },
+ {
+ "channelId": channel_pln_id,
+ "discountValue": discount_value_pln,
+ "minAmountSpent": min_amount_spent_pln,
+ },
+ ]
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ VOUCHER_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_discounts,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["voucherChannelListingUpdate"]["voucher"]
+ assert not content["data"]["voucherChannelListingUpdate"]["discountErrors"]
+ channel_listing = data["channelListings"]
+ assert channel_listing[0]["channel"]["slug"] == channel_USD.slug
+ assert channel_listing[0]["discountValue"] == discount_value
+ assert channel_listing[0]["minSpent"]["amount"] == min_amount_spent
+ assert channel_listing[0]["currency"] == channel_USD.currency_code
+ assert channel_listing[1]["channel"]["slug"] == channel_PLN.slug
+ assert channel_listing[1]["discountValue"] == discount_value_pln
+ assert channel_listing[1]["minSpent"]["amount"] == min_amount_spent_pln
+ assert channel_listing[1]["currency"] == channel_PLN.currency_code
+
+
+def test_voucher_channel_listing_create_and_remove(
+ staff_api_client, voucher, permission_manage_discounts, channel_USD, channel_PLN,
+):
+ # given
+ voucher_id = graphene.Node.to_global_id("Voucher", voucher.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ channel_pln_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ discount_value_pln = 50.5
+ min_amount_spent_pln = 100.2
+ variables = {
+ "id": voucher_id,
+ "input": {
+ "addChannels": [
+ {
+ "channelId": channel_pln_id,
+ "discountValue": discount_value_pln,
+ "minAmountSpent": min_amount_spent_pln,
+ }
+ ],
+ "removeChannels": [channel_id],
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ VOUCHER_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_discounts,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["voucherChannelListingUpdate"]["voucher"]
+ assert not content["data"]["voucherChannelListingUpdate"]["discountErrors"]
+ channel_listing = data["channelListings"]
+ assert len(channel_listing) == 1
+ assert channel_listing[0]["channel"]["slug"] == channel_PLN.slug
+ assert channel_listing[0]["discountValue"] == discount_value_pln
+ assert channel_listing[0]["minSpent"]["amount"] == min_amount_spent_pln
+ assert channel_listing[0]["currency"] == channel_PLN.currency_code
+
+
+def test_voucher_channel_listing_update(
+ staff_api_client, voucher, permission_manage_discounts, channel_USD,
+):
+ # given
+ voucher_id = graphene.Node.to_global_id("Voucher", voucher.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ discount_value = 5.5
+ min_amount_spent = 100.2
+ assert not voucher.channel_listings.get().discount_value == discount_value
+ variables = {
+ "id": voucher_id,
+ "input": {
+ "addChannels": [
+ {
+ "channelId": channel_id,
+ "discountValue": discount_value,
+ "minAmountSpent": min_amount_spent,
+ }
+ ]
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ VOUCHER_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_discounts,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["voucherChannelListingUpdate"]["voucher"]
+ assert not content["data"]["voucherChannelListingUpdate"]["discountErrors"]
+ channel_listing = data["channelListings"]
+ assert len(channel_listing) == 1
+ assert channel_listing[0]["channel"]["slug"] == channel_USD.slug
+ assert channel_listing[0]["discountValue"] == discount_value
+ assert channel_listing[0]["minSpent"]["amount"] == min_amount_spent
+ assert channel_listing[0]["currency"] == channel_USD.currency_code
+
+
+def test_voucher_channel_listing_update_without_discount_value(
+ staff_api_client, voucher, permission_manage_discounts, channel_USD,
+):
+ # given
+ voucher_id = graphene.Node.to_global_id("Voucher", voucher.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ min_amount_spent = 100.2
+ variables = {
+ "id": voucher_id,
+ "input": {
+ "addChannels": [
+ {"channelId": channel_id, "minAmountSpent": min_amount_spent}
+ ]
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ VOUCHER_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_discounts,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["voucherChannelListingUpdate"]["voucher"]
+ assert not content["data"]["voucherChannelListingUpdate"]["discountErrors"]
+ channel_listing = data["channelListings"]
+ assert len(channel_listing) == 1
+ assert channel_listing[0]["channel"]["slug"] == channel_USD.slug
+ assert channel_listing[0]["discountValue"] == 20
+ assert channel_listing[0]["minSpent"]["amount"] == min_amount_spent
+ assert channel_listing[0]["currency"] == channel_USD.currency_code
+
+
+def test_voucher_channel_listing_remove_channel(
+ staff_api_client, voucher, permission_manage_discounts, channel_USD,
+):
+ # given
+ voucher_id = graphene.Node.to_global_id("Voucher", voucher.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": voucher_id,
+ "input": {"removeChannels": [channel_id]},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ VOUCHER_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_discounts,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["voucherChannelListingUpdate"]["voucher"]
+ assert not content["data"]["voucherChannelListingUpdate"]["discountErrors"]
+ channel_listing = data["channelListings"]
+ assert len(channel_listing) == 0
+
+
+def test_voucher_channel_listing_update_with_null_as_discount_value(
+ staff_api_client, voucher, permission_manage_discounts, channel_USD,
+):
+ # given
+ voucher_id = graphene.Node.to_global_id("Voucher", voucher.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": voucher_id,
+ "input": {
+ "addChannels": [
+ {
+ "channelId": channel_id,
+ "discountValue": None,
+ "minAmountSpent": 100.2,
+ }
+ ]
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ VOUCHER_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_discounts,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ errors = content["data"]["voucherChannelListingUpdate"]["discountErrors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "discountValue"
+ assert errors[0]["code"] == DiscountErrorCode.REQUIRED.name
+ assert errors[0]["channels"] == [channel_id]
+
+
+def test_voucher_channel_listing_create_with_null_as_discount_value(
+ staff_api_client, voucher_without_channel, permission_manage_discounts, channel_USD,
+):
+ # given
+ voucher = voucher_without_channel
+ voucher_id = graphene.Node.to_global_id("Voucher", voucher.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": voucher_id,
+ "input": {
+ "addChannels": [
+ {
+ "channelId": channel_id,
+ "discountValue": None,
+ "minAmountSpent": 100.2,
+ }
+ ]
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ VOUCHER_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_discounts,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ errors = content["data"]["voucherChannelListingUpdate"]["discountErrors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "discountValue"
+ assert errors[0]["code"] == DiscountErrorCode.REQUIRED.name
+ assert errors[0]["channels"] == [channel_id]
+
+
+def test_voucher_channel_listing_create_without_discount_value(
+ staff_api_client, voucher_without_channel, permission_manage_discounts, channel_USD,
+):
+ # given
+ voucher = voucher_without_channel
+ voucher_id = graphene.Node.to_global_id("Voucher", voucher.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": voucher_id,
+ "input": {"addChannels": [{"channelId": channel_id, "minAmountSpent": 100.2}]},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ VOUCHER_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_discounts,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ errors = content["data"]["voucherChannelListingUpdate"]["discountErrors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "discountValue"
+ assert errors[0]["code"] == DiscountErrorCode.REQUIRED.name
+ assert errors[0]["channels"] == [channel_id]
+
+
+def test_voucher_channel_listing_update_duplicates_in_add(
+ staff_api_client, voucher, permission_manage_discounts, channel_USD,
+):
+ # given
+ voucher_id = graphene.Node.to_global_id("Voucher", voucher.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": voucher_id,
+ "input": {
+ "addChannels": [
+ {"channelId": channel_id, "discountValue": 50.5},
+ {"channelId": channel_id, "discountValue": 50.5},
+ ]
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ VOUCHER_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_discounts,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ errors = content["data"]["voucherChannelListingUpdate"]["discountErrors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "addChannels"
+ assert errors[0]["code"] == DiscountErrorCode.DUPLICATED_INPUT_ITEM.name
+ assert errors[0]["channels"] == [channel_id]
+
+
+def test_voucher_channel_listing_update_duplicates_in_remove(
+ staff_api_client, voucher, permission_manage_discounts, channel_USD,
+):
+ # given
+ voucher_id = graphene.Node.to_global_id("Voucher", voucher.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": voucher_id,
+ "input": {"removeChannels": [channel_id, channel_id]},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ VOUCHER_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_discounts,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ errors = content["data"]["voucherChannelListingUpdate"]["discountErrors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "removeChannels"
+ assert errors[0]["code"] == DiscountErrorCode.DUPLICATED_INPUT_ITEM.name
+ assert errors[0]["channels"] == [channel_id]
+
+
+def test_voucher_channel_listing_update_duplicates_in_add_and_remove(
+ staff_api_client, voucher, permission_manage_discounts, channel_USD,
+):
+ # given
+ voucher_id = graphene.Node.to_global_id("Voucher", voucher.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": voucher_id,
+ "input": {
+ "addChannels": [{"channelId": channel_id, "discountValue": 50.5}],
+ "removeChannels": [channel_id],
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ VOUCHER_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_discounts,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ errors = content["data"]["voucherChannelListingUpdate"]["discountErrors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "input"
+ assert errors[0]["code"] == DiscountErrorCode.DUPLICATED_INPUT_ITEM.name
+ assert errors[0]["channels"] == [channel_id]
+
+
+def test_voucher_channel_listing_update_invalid_precision_discount_value(
+ staff_api_client, voucher, permission_manage_discounts, channel_USD,
+):
+ # given
+ voucher_id = graphene.Node.to_global_id("Voucher", voucher.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": voucher_id,
+ "input": {
+ "addChannels": [
+ {
+ "channelId": channel_id,
+ "discountValue": 5.55555,
+ "minAmountSpent": 100.2,
+ }
+ ]
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ VOUCHER_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_discounts,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ errors = content["data"]["voucherChannelListingUpdate"]["discountErrors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "discountValue"
+ assert errors[0]["code"] == DiscountErrorCode.INVALID.name
+ assert errors[0]["channels"] == [channel_id]
+
+
+def test_voucher_channel_listing_update_invalid_precision_min_amount_spent(
+ staff_api_client, voucher, permission_manage_discounts, channel_USD,
+):
+ # given
+ voucher_id = graphene.Node.to_global_id("Voucher", voucher.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": voucher_id,
+ "input": {
+ "addChannels": [
+ {
+ "channelId": channel_id,
+ "discountValue": 5.55,
+ "minAmountSpent": 100.2222,
+ }
+ ]
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ VOUCHER_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_discounts,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ errors = content["data"]["voucherChannelListingUpdate"]["discountErrors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "minAmountSpent"
+ assert errors[0]["code"] == DiscountErrorCode.INVALID.name
+ assert errors[0]["channels"] == [channel_id]
diff --git a/saleor/graphql/discount/tests/test_voucher_sorting_with_channels.py b/saleor/graphql/discount/tests/test_voucher_sorting_with_channels.py
new file mode 100644
index 0000000000..f589da8321
--- /dev/null
+++ b/saleor/graphql/discount/tests/test_voucher_sorting_with_channels.py
@@ -0,0 +1,286 @@
+import pytest
+
+from ....discount import DiscountValueType, VoucherType
+from ....discount.models import Voucher, VoucherChannelListing
+from ...channel.sorters import LACK_OF_CHANNEL_IN_SORTING_MSG
+from ...tests.utils import assert_graphql_error_with_message, get_graphql_content
+
+
+def vouchers_for_sorting_with_channels(db, channel_USD, channel_PLN):
+ vouchers = Voucher.objects.bulk_create(
+ [
+ Voucher(
+ code="Code1",
+ name="Voucher1",
+ discount_value_type=DiscountValueType.PERCENTAGE,
+ usage_limit=10,
+ type=VoucherType.SPECIFIC_PRODUCT,
+ ),
+ Voucher(
+ code="Code2",
+ name="Voucher2",
+ usage_limit=1000,
+ used=10,
+ type=VoucherType.ENTIRE_ORDER,
+ ),
+ Voucher(
+ code="Code3",
+ name="Voucher3",
+ discount_value_type=DiscountValueType.PERCENTAGE,
+ usage_limit=100,
+ used=35,
+ type=VoucherType.ENTIRE_ORDER,
+ ),
+ Voucher(
+ code="Code4",
+ name="Voucher4",
+ usage_limit=100,
+ type=VoucherType.SPECIFIC_PRODUCT,
+ ),
+ Voucher(
+ code="Code15",
+ name="Voucher15",
+ discount_value_type=DiscountValueType.PERCENTAGE,
+ usage_limit=10,
+ ),
+ ]
+ )
+ VoucherChannelListing.objects.bulk_create(
+ [
+ VoucherChannelListing(
+ voucher=vouchers[0],
+ channel=channel_USD,
+ discount_value=1,
+ min_spent_amount=10,
+ currency=channel_USD.currency_code,
+ ),
+ VoucherChannelListing(
+ voucher=vouchers[1],
+ channel=channel_USD,
+ discount_value=7,
+ currency=channel_USD.currency_code,
+ ),
+ VoucherChannelListing(
+ voucher=vouchers[2],
+ channel=channel_USD,
+ discount_value=5,
+ min_spent_amount=12,
+ currency=channel_USD.currency_code,
+ ),
+ VoucherChannelListing(
+ voucher=vouchers[4],
+ channel=channel_USD,
+ discount_value=2,
+ min_spent_amount=100,
+ currency=channel_USD.currency_code,
+ ),
+ # Second channel
+ VoucherChannelListing(
+ voucher=vouchers[0],
+ channel=channel_PLN,
+ discount_value=7,
+ min_spent_amount=10,
+ currency=channel_PLN.currency_code,
+ ),
+ VoucherChannelListing(
+ voucher=vouchers[1],
+ channel=channel_PLN,
+ discount_value=1,
+ min_spent_amount=100,
+ currency=channel_PLN.currency_code,
+ ),
+ VoucherChannelListing(
+ voucher=vouchers[3],
+ channel=channel_PLN,
+ discount_value=2,
+ min_spent_amount=50,
+ currency=channel_PLN.currency_code,
+ ),
+ VoucherChannelListing(
+ voucher=vouchers[4],
+ channel=channel_PLN,
+ discount_value=5,
+ currency=channel_PLN.currency_code,
+ ),
+ ]
+ )
+ return vouchers
+
+
+QUERY_VOUCHERS_WITH_SORTING_AND_FILTERING = """
+ query (
+ $sortBy: VoucherSortingInput, $filter: VoucherFilterInput
+ ){
+ vouchers(
+ first: 10, sortBy: $sortBy, filter: $filter
+ ) {
+ edges {
+ node {
+ name
+ }
+ }
+ }
+ }
+"""
+
+
+ "sort_by",
+ [
+ {"field": "MINIMUM_SPENT_AMOUNT", "direction": "ASC"},
+ {"field": "VALUE", "direction": "ASC"},
+ ],
+)
+def test_voucher_with_sorting_and_without_channel(
+ sort_by, staff_api_client, permission_manage_discounts,
+):
+ # given
+ variables = {"sortBy": sort_by}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_VOUCHERS_WITH_SORTING_AND_FILTERING,
+ variables,
+ permissions=[permission_manage_discounts],
+ check_no_permissions=False,
+ )
+
+ # then
+ assert_graphql_error_with_message(response, LACK_OF_CHANNEL_IN_SORTING_MSG)
+
+
+ "sort_by, vouchers_order",
+ [
+ (
+ {"field": "VALUE", "direction": "ASC"},
+ ["Voucher1", "Voucher15", "Voucher3", "Voucher2", "Voucher4"],
+ ),
+ (
+ {"field": "VALUE", "direction": "DESC"},
+ ["Voucher4", "Voucher2", "Voucher3", "Voucher15", "Voucher1"],
+ ),
+ (
+ {"field": "MINIMUM_SPENT_AMOUNT", "direction": "ASC"},
+ ["Voucher1", "Voucher3", "Voucher15", "Voucher2", "Voucher4"],
+ ),
+ (
+ {"field": "MINIMUM_SPENT_AMOUNT", "direction": "DESC"},
+ ["Voucher4", "Voucher2", "Voucher15", "Voucher3", "Voucher1"],
+ ),
+ ],
+)
+def test_vouchers_with_sorting_and_channel_USD(
+ sort_by,
+ vouchers_order,
+ staff_api_client,
+ permission_manage_discounts,
+ vouchers_for_sorting_with_channels,
+ channel_USD,
+):
+ # given
+ sort_by["channel"] = channel_USD.slug
+ variables = {"sortBy": sort_by}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_VOUCHERS_WITH_SORTING_AND_FILTERING,
+ variables,
+ permissions=[permission_manage_discounts],
+ check_no_permissions=False,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ vouchers_nodes = content["data"]["vouchers"]["edges"]
+ for index, voucher_name in enumerate(vouchers_order):
+ assert voucher_name == vouchers_nodes[index]["node"]["name"]
+
+
+ "sort_by, vouchers_order",
+ [
+ (
+ {"field": "VALUE", "direction": "ASC"},
+ ["Voucher2", "Voucher4", "Voucher15", "Voucher1", "Voucher3"],
+ ),
+ (
+ {"field": "VALUE", "direction": "DESC"},
+ ["Voucher3", "Voucher1", "Voucher15", "Voucher4", "Voucher2"],
+ ),
+ (
+ {"field": "MINIMUM_SPENT_AMOUNT", "direction": "ASC"},
+ ["Voucher1", "Voucher4", "Voucher2", "Voucher15", "Voucher3"],
+ ),
+ (
+ {"field": "MINIMUM_SPENT_AMOUNT", "direction": "DESC"},
+ ["Voucher3", "Voucher15", "Voucher2", "Voucher4", "Voucher1"],
+ ),
+ ],
+)
+def test_vouchers_with_sorting_and_channel_PLN(
+ sort_by,
+ vouchers_order,
+ staff_api_client,
+ permission_manage_discounts,
+ vouchers_for_sorting_with_channels,
+ channel_PLN,
+):
+ # given
+ sort_by["channel"] = channel_PLN.slug
+ variables = {"sortBy": sort_by}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_VOUCHERS_WITH_SORTING_AND_FILTERING,
+ variables,
+ permissions=[permission_manage_discounts],
+ check_no_permissions=False,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ vouchers_nodes = content["data"]["vouchers"]["edges"]
+ for index, voucher_name in enumerate(vouchers_order):
+ assert voucher_name == vouchers_nodes[index]["node"]["name"]
+
+
+ "sort_by",
+ [
+ {"field": "VALUE", "direction": "ASC"},
+ {"field": "MINIMUM_SPENT_AMOUNT", "direction": "ASC"},
+ ],
+)
+def test_vouchers_with_sorting_and_not_existing_channel_asc(
+ sort_by,
+ staff_api_client,
+ permission_manage_discounts,
+ vouchers_for_sorting_with_channels,
+ channel_USD,
+):
+ # given
+ vouchers_order = [
+ "Voucher1",
+ "Voucher15",
+ "Voucher2",
+ "Voucher3",
+ "Voucher4",
+ ]
+ sort_by["channel"] = "Not-existing"
+ variables = {"sortBy": sort_by}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_VOUCHERS_WITH_SORTING_AND_FILTERING,
+ variables,
+ permissions=[permission_manage_discounts],
+ check_no_permissions=False,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ vouchers_nodes = content["data"]["vouchers"]["edges"]
+ for index, voucher_name in enumerate(vouchers_order):
+ assert voucher_name == vouchers_nodes[index]["node"]["name"]
diff --git a/saleor/graphql/discount/types.py b/saleor/graphql/discount/types.py
index 6a44b6facb..54b5a5e8f2 100644
--- a/saleor/graphql/discount/types.py
+++ b/saleor/graphql/discount/types.py
@@ -1,72 +1,175 @@
import graphene
from graphene import relay
+from ...core.permissions import DiscountPermissions
from ...discount import models
+from ..channel.dataloaders import ChannelByIdLoader
+from ..channel.types import ChannelContext, ChannelContextType
from ..core import types
from ..core.connection import CountableDjangoObjectType
-from ..core.fields import PrefetchingConnectionField
+from ..core.fields import (
+ ChannelContextFilterConnectionField,
+ ChannelQsContext,
+ PrefetchingConnectionField,
+)
+from ..core.types import Money
+from ..decorators import permission_required
from ..product.types import Category, Collection, Product
from ..translations.fields import TranslationField
from ..translations.types import SaleTranslation, VoucherTranslation
+from .dataloaders import (
+ SaleChannelListingBySaleIdAndChanneSlugLoader,
+ SaleChannelListingBySaleIdLoader,
+ VoucherChannelListingByVoucherIdAndChanneSlugLoader,
+ VoucherChannelListingByVoucherIdLoader,
+)
from .enums import DiscountValueTypeEnum, VoucherTypeEnum
-class Sale(CountableDjangoObjectType):
+class SaleChannelListing(CountableDjangoObjectType):
+ class Meta:
+ description = "Represents sale channel listing."
+ model = models.SaleChannelListing
+ interfaces = [relay.Node]
+ only_fields = ["id", "channel", "discount_value", "currency"]
+
+ @staticmethod
+ def resolve_channel(root: models.SaleChannelListing, info, **_kwargs):
+ return ChannelByIdLoader(info.context).load(root.channel_id)
+
+
+class Sale(ChannelContextType, CountableDjangoObjectType):
categories = PrefetchingConnectionField(
Category, description="List of categories this sale applies to."
)
- collections = PrefetchingConnectionField(
+ collections = ChannelContextFilterConnectionField(
Collection, description="List of collections this sale applies to."
)
- products = PrefetchingConnectionField(
+ products = ChannelContextFilterConnectionField(
Product, description="List of products this sale applies to."
)
- translation = TranslationField(SaleTranslation, type_name="sale")
+ translation = TranslationField(
+ SaleTranslation,
+ type_name="sale",
+ resolver=ChannelContextType.resolve_translation,
+ )
+ channel_listings = graphene.List(
+ graphene.NonNull(SaleChannelListing),
+ description="List of channels available for the sale.",
+ )
+ discount_value = graphene.Float(description="Sale value.")
+ currency = graphene.String(description="Currency code for sale.")
class Meta:
+ default_resolver = ChannelContextType.resolver_with_context
description = (
"Sales allow creating discounts for categories, collections or products "
"and are visible to all the customers."
)
interfaces = [relay.Node]
model = models.Sale
- only_fields = ["end_date", "id", "name", "start_date", "type", "value"]
+ only_fields = ["end_date", "id", "name", "start_date", "type"]
+
+ @staticmethod
+ def resolve_categories(root: ChannelContext[models.Sale], *_args, **_kwargs):
+ return root.node.categories.all()
@staticmethod
- def resolve_categories(root: models.Sale, *_args, **_kwargs):
- return root.categories.all()
+ @permission_required(DiscountPermissions.MANAGE_DISCOUNTS)
+ def resolve_channel_listings(root: ChannelContext[models.Sale], info, **_kwargs):
+ return SaleChannelListingBySaleIdLoader(info.context).load(root.node.id)
@staticmethod
- def resolve_collections(root: models.Sale, info, **_kwargs):
- return root.collections.visible_to_user(info.context.user)
+ @permission_required(DiscountPermissions.MANAGE_DISCOUNTS)
+ def resolve_collections(root: ChannelContext[models.Sale], info, *_args, **_kwargs):
+ qs = root.node.collections.all()
+ return ChannelQsContext(qs=qs, channel_slug=root.channel_slug)
+
+ @staticmethod
+ @permission_required(DiscountPermissions.MANAGE_DISCOUNTS)
+ def resolve_products(root: ChannelContext[models.Sale], info, **_kwargs):
+ qs = root.node.products.all()
+ return ChannelQsContext(qs=qs, channel_slug=root.channel_slug)
+
+ @staticmethod
+ def resolve_discount_value(root: ChannelContext[models.Sale], info, **_kwargs):
+ if not root.channel_slug:
+ return None
+
+ return (
+ SaleChannelListingBySaleIdAndChanneSlugLoader(info.context)
+ .load((root.node.id, root.channel_slug))
+ .then(
+ lambda channel_listing: channel_listing.discount_value
+ if channel_listing
+ else None
+ )
+ )
+
+ @staticmethod
+ def resolve_currency(root: ChannelContext[models.Sale], info, **_kwargs):
+ if not root.channel_slug:
+ return None
+
+ return (
+ SaleChannelListingBySaleIdAndChanneSlugLoader(info.context)
+ .load((root.node.id, root.channel_slug))
+ .then(
+ lambda channel_listing: channel_listing.currency
+ if channel_listing
+ else None
+ )
+ )
+
+
+class VoucherChannelListing(CountableDjangoObjectType):
+ class Meta:
+ description = "Represents voucher channel listing."
+ model = models.VoucherChannelListing
+ interfaces = [graphene.relay.Node]
+ only_fields = ["id", "channel", "discount_value", "currency", "min_spent"]
@staticmethod
- def resolve_products(root: models.Sale, info, **_kwargs):
- return root.products.visible_to_user(info.context.user)
+ def resolve_channel(root: models.VoucherChannelListing, info, **_kwargs):
+ return ChannelByIdLoader(info.context).load(root.channel_id)
-class Voucher(CountableDjangoObjectType):
+class Voucher(ChannelContextType, CountableDjangoObjectType):
categories = PrefetchingConnectionField(
Category, description="List of categories this voucher applies to."
)
- collections = PrefetchingConnectionField(
+ collections = ChannelContextFilterConnectionField(
Collection, description="List of collections this voucher applies to."
)
- products = PrefetchingConnectionField(
+ products = ChannelContextFilterConnectionField(
Product, description="List of products this voucher applies to."
)
countries = graphene.List(
types.CountryDisplay,
description="List of countries available for the shipping voucher.",
)
- translation = TranslationField(VoucherTranslation, type_name="voucher")
+ translation = TranslationField(
+ VoucherTranslation,
+ type_name="voucher",
+ resolver=ChannelContextType.resolve_translation,
+ )
discount_value_type = DiscountValueTypeEnum(
description="Determines a type of discount for voucher - value or percentage",
required=True,
)
+ discount_value = graphene.Float(description="Voucher value.")
+ currency = graphene.String(description="Currency code for voucher.")
+ min_spent = graphene.Field(
+ Money, description="Minimum order value to apply voucher."
+ )
type = VoucherTypeEnum(description="Determines a type of voucher.", required=True)
+ channel_listings = graphene.List(
+ graphene.NonNull(VoucherChannelListing),
+ description="List of availability in channels for the voucher.",
+ )
class Meta:
+ default_resolver = ChannelContextType.resolver_with_context
description = (
"Vouchers allow giving discounts to particular customers on categories, "
"collections or specific products. They can be used during checkout by "
@@ -76,11 +179,9 @@ class Voucher(CountableDjangoObjectType):
"apply_once_per_order",
"apply_once_per_customer",
"code",
- "discount_value",
"discount_value_type",
"end_date",
"id",
- "min_spent",
"min_checkout_items_quantity",
"name",
"start_date",
@@ -92,20 +193,76 @@ class Voucher(CountableDjangoObjectType):
model = models.Voucher
@staticmethod
- def resolve_categories(root: models.Voucher, *_args, **_kwargs):
- return root.categories.all()
+ def resolve_categories(root: ChannelContext[models.Voucher], *_args, **_kwargs):
+ return root.node.categories.all()
@staticmethod
- def resolve_collections(root: models.Voucher, info, **_kwargs):
- return root.collections.visible_to_user(info.context.user)
+ @permission_required(DiscountPermissions.MANAGE_DISCOUNTS)
+ def resolve_collections(
+ root: ChannelContext[models.Voucher], _info, *_args, **_kwargs
+ ):
+ qs = root.node.collections.all()
+ return ChannelQsContext(qs=qs, channel_slug=root.channel_slug)
@staticmethod
- def resolve_products(root: models.Voucher, info, **_kwargs):
- return root.products.visible_to_user(info.context.user)
+ @permission_required(DiscountPermissions.MANAGE_DISCOUNTS)
+ def resolve_products(root: ChannelContext[models.Voucher], info, **_kwargs):
+ qs = root.node.products.all()
+ return ChannelQsContext(qs=qs, channel_slug=root.channel_slug)
@staticmethod
- def resolve_countries(root: models.Voucher, *_args, **_kwargs):
+ def resolve_countries(root: ChannelContext[models.Voucher], *_args, **_kwargs):
return [
types.CountryDisplay(code=country.code, country=country.name)
- for country in root.countries
+ for country in root.node.countries
]
+
+ @staticmethod
+ def resolve_discount_value(root: ChannelContext[models.Voucher], info, **_kwargs):
+ if not root.channel_slug:
+ return None
+
+ return (
+ VoucherChannelListingByVoucherIdAndChanneSlugLoader(info.context)
+ .load((root.node.id, root.channel_slug))
+ .then(
+ lambda channel_listing: channel_listing.discount_value
+ if channel_listing
+ else None
+ )
+ )
+
+ @staticmethod
+ def resolve_currency(root: ChannelContext[models.Voucher], info, **_kwargs):
+ if not root.channel_slug:
+ return None
+
+ return (
+ VoucherChannelListingByVoucherIdAndChanneSlugLoader(info.context)
+ .load((root.node.id, root.channel_slug))
+ .then(
+ lambda channel_listing: channel_listing.currency
+ if channel_listing
+ else None
+ )
+ )
+
+ @staticmethod
+ def resolve_min_spent(root: ChannelContext[models.Voucher], info, **_kwargs):
+ if not root.channel_slug:
+ return None
+
+ return (
+ VoucherChannelListingByVoucherIdAndChanneSlugLoader(info.context)
+ .load((root.node.id, root.channel_slug))
+ .then(
+ lambda channel_listing: channel_listing.min_spent
+ if channel_listing
+ else None
+ )
+ )
+
+ @staticmethod
+ @permission_required(DiscountPermissions.MANAGE_DISCOUNTS)
+ def resolve_channel_listings(root: ChannelContext[models.Voucher], info, **_kwargs):
+ return VoucherChannelListingByVoucherIdLoader(info.context).load(root.node.id)
diff --git a/saleor/graphql/menu/mutations.py b/saleor/graphql/menu/mutations.py
index 9bf753e333..4f66b9eed4 100644
--- a/saleor/graphql/menu/mutations.py
+++ b/saleor/graphql/menu/mutations.py
@@ -12,6 +12,7 @@ from ...menu import models
from ...menu.error_codes import MenuErrorCode
from ...page import models as page_models
from ...product import models as product_models
+from ..channel import ChannelContext
from ..core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation
from ..core.types.common import MenuError
from ..core.utils import (
@@ -120,7 +121,6 @@ class MenuCreate(ModelMutation):
}
)
items.append(item)
-
cleaned_input["items"] = items
return cleaned_input
@@ -131,6 +131,11 @@ class MenuCreate(ModelMutation):
for item in items:
instance.items.create(**item)
+ @classmethod
+ def success_response(cls, instance):
+ instance = ChannelContext(node=instance, channel_slug=None)
+ return super().success_response(instance)
+
class MenuInput(graphene.InputObjectType):
name = graphene.String(description="Name of the menu.")
@@ -151,6 +156,11 @@ class MenuUpdate(ModelMutation):
error_type_class = MenuError
error_type_field = "menu_errors"
+ @classmethod
+ def success_response(cls, instance):
+ instance = ChannelContext(node=instance, channel_slug=None)
+ return super().success_response(instance)
+
class MenuDelete(ModelDeleteMutation):
class Arguments:
@@ -163,6 +173,11 @@ class MenuDelete(ModelDeleteMutation):
error_type_class = MenuError
error_type_field = "menu_errors"
+ @classmethod
+ def success_response(cls, instance):
+ instance = ChannelContext(node=instance, channel_slug=None)
+ return super().success_response(instance)
+
def _validate_menu_item_instance(
cleaned_input: dict, field: str, expected_model: Type[Model]
@@ -201,6 +216,11 @@ class MenuItemCreate(ModelMutation):
error_type_class = MenuError
error_type_field = "menu_errors"
+ @classmethod
+ def success_response(cls, instance):
+ instance = ChannelContext(node=instance, channel_slug=None)
+ return super().success_response(instance)
+
@classmethod
def clean_input(cls, info, instance, data):
cleaned_input = super().clean_input(info, instance, data)
@@ -264,6 +284,11 @@ class MenuItemDelete(ModelDeleteMutation):
error_type_class = MenuError
error_type_field = "menu_errors"
+ @classmethod
+ def success_response(cls, instance):
+ instance = ChannelContext(node=instance, channel_slug=None)
+ return super().success_response(instance)
+
@dataclass(frozen=True)
class _MenuMoveOperation:
@@ -288,6 +313,11 @@ class MenuItemMove(BaseMutation):
error_type_class = MenuError
error_type_field = "menu_errors"
+ @classmethod
+ def success_response(cls, instance):
+ instance = ChannelContext(node=instance, channel_slug=None)
+ return super().success_response(instance)
+
@staticmethod
def clean_move(move: MenuItemMoveInput):
"""Validate if the given move could be possibly possible."""
@@ -403,7 +433,7 @@ class MenuItemMove(BaseMutation):
perform_reordering(ordering_qs, operations)
menu = qs.get(pk=menu.pk)
- return MenuItemMove(menu=menu)
+ return MenuItemMove(menu=ChannelContext(node=menu, channel_slug=None))
class AssignNavigation(BaseMutation):
@@ -435,4 +465,6 @@ class AssignNavigation(BaseMutation):
site_settings.bottom_menu = menu
site_settings.save(update_fields=["bottom_menu"])
- return AssignNavigation(menu=menu)
+ if menu is None:
+ return AssignNavigation(menu=None)
+ return AssignNavigation(menu=ChannelContext(node=menu, channel_slug=None))
diff --git a/saleor/graphql/menu/resolvers.py b/saleor/graphql/menu/resolvers.py
index edc33dd975..94c1defea8 100644
--- a/saleor/graphql/menu/resolvers.py
+++ b/saleor/graphql/menu/resolvers.py
@@ -1,6 +1,7 @@
import graphene
from ...menu import models
+from ..channel import ChannelContext, ChannelQsContext
from ..core.validators import validate_one_of_args_is_in_query
from ..utils.filters import filter_by_query_param
from .types import Menu
@@ -9,19 +10,21 @@ MENU_SEARCH_FIELDS = ("name",)
MENU_ITEM_SEARCH_FIELDS = ("name",)
-def resolve_menu(info, menu_id=None, name=None, slug=None):
+def resolve_menu(info, channel, menu_id=None, name=None, slug=None):
validate_one_of_args_is_in_query("id", menu_id, "name", name, "slug", slug)
+ menu = None
if menu_id:
- return graphene.Node.get_node_from_global_id(info, menu_id, Menu)
+ menu = graphene.Node.get_node_from_global_id(info, menu_id, Menu)
if name:
- return models.Menu.objects.filter(name=name).first()
+ menu = models.Menu.objects.filter(name=name).first()
if slug:
- return models.Menu.objects.filter(slug=slug).first()
+ menu = models.Menu.objects.filter(slug=slug).first()
+ return ChannelContext(node=menu, channel_slug=channel) if menu else None
-def resolve_menus(info, query, **_kwargs):
- qs = models.Menu.objects.all()
- return filter_by_query_param(qs, query, MENU_SEARCH_FIELDS)
+def resolve_menus(info, channel, query, **_kwargs):
+ qs = filter_by_query_param(models.Menu.objects.all(), query, MENU_SEARCH_FIELDS)
+ return ChannelQsContext(qs=qs, channel_slug=channel)
def resolve_menu_items(info, query, **_kwargs):
diff --git a/saleor/graphql/menu/schema.py b/saleor/graphql/menu/schema.py
index 542cb443b8..8a5e16f686 100644
--- a/saleor/graphql/menu/schema.py
+++ b/saleor/graphql/menu/schema.py
@@ -1,6 +1,8 @@
import graphene
-from ..core.fields import FilterInputConnectionField
+from ..channel import ChannelContext, ChannelQsContext
+from ..channel.utils import get_default_channel_slug_or_graphql_error
+from ..core.fields import ChannelContextFilterConnectionField
from ..translations.mutations import MenuItemTranslate
from .bulk_mutations import MenuBulkDelete, MenuItemBulkDelete
from .filters import MenuFilterInput, MenuItemFilterInput
@@ -22,13 +24,19 @@ from .types import Menu, MenuItem
class MenuQueries(graphene.ObjectType):
menu = graphene.Field(
Menu,
+ channel=graphene.String(
+ description="Slug of a channel for which the data should be returned."
+ ),
id=graphene.Argument(graphene.ID, description="ID of the menu."),
name=graphene.Argument(graphene.String, description="The menu's name."),
slug=graphene.Argument(graphene.String, description="The menu's slug."),
description="Look up a navigation menu by ID or name.",
)
- menus = FilterInputConnectionField(
+ menus = ChannelContextFilterConnectionField(
Menu,
+ channel=graphene.String(
+ description="Slug of a channel for which the data should be returned."
+ ),
sort_by=MenuSortingInput(description="Sort menus."),
filter=MenuFilterInput(description="Filtering options for menus."),
description="List of the storefront's menus.",
@@ -38,26 +46,46 @@ class MenuQueries(graphene.ObjectType):
id=graphene.Argument(
graphene.ID, description="ID of the menu item.", required=True
),
+ channel=graphene.String(
+ description="Slug of a channel for which the data should be returned."
+ ),
description="Look up a menu item by ID.",
)
- menu_items = FilterInputConnectionField(
+ menu_items = ChannelContextFilterConnectionField(
MenuItem,
+ channel=graphene.String(
+ description="Slug of a channel for which the data should be returned."
+ ),
sort_by=MenuItemSortingInput(description="Sort menus items."),
filter=MenuItemFilterInput(description="Filtering options for menu items."),
description="List of the storefronts's menu items.",
)
- def resolve_menu(self, info, **data):
- return resolve_menu(info, data.get("id"), data.get("name"), data.get("slug"))
+ def resolve_menu(self, info, channel=None, **data):
+ if channel is None:
+ channel = get_default_channel_slug_or_graphql_error()
+ return resolve_menu(
+ info, channel, data.get("id"), data.get("name"), data.get("slug")
+ )
- def resolve_menus(self, info, query=None, **kwargs):
- return resolve_menus(info, query, **kwargs)
+ def resolve_menus(self, info, query=None, channel=None, **kwargs):
+ if channel is None:
+ channel = get_default_channel_slug_or_graphql_error()
+ return resolve_menus(info, channel, query, **kwargs)
- def resolve_menu_item(self, info, **data):
- return graphene.Node.get_node_from_global_id(info, data.get("id"), MenuItem)
+ def resolve_menu_item(self, info, channel=None, **data):
+ if channel is None:
+ channel = get_default_channel_slug_or_graphql_error()
+ menu_item = graphene.Node.get_node_from_global_id(
+ info, data.get("id"), MenuItem
+ )
+ return ChannelContext(node=menu_item, channel_slug=channel)
- def resolve_menu_items(self, info, query=None, **kwargs):
- return resolve_menu_items(info, query, **kwargs)
+ def resolve_menu_items(self, info, query=None, channel=None, **kwargs):
+ if channel is None:
+ channel = get_default_channel_slug_or_graphql_error()
+ menu_items = resolve_menu_items(info, query, **kwargs)
+ return ChannelQsContext(qs=menu_items, channel_slug=channel)
class MenuMutations(graphene.ObjectType):
diff --git a/saleor/graphql/menu/sorters.py b/saleor/graphql/menu/sorters.py
index 8e66737283..99367117e1 100644
--- a/saleor/graphql/menu/sorters.py
+++ b/saleor/graphql/menu/sorters.py
@@ -16,7 +16,7 @@ class MenuSortField(graphene.Enum):
raise ValueError("Unsupported enum value: %s" % self.value)
@staticmethod
- def qs_with_items_count(queryset: QuerySet) -> QuerySet:
+ def qs_with_items_count(queryset: QuerySet, **_kwargs) -> QuerySet:
return queryset.annotate(items_count=Count("items__id"))
diff --git a/saleor/graphql/menu/tests/deprecated/__init__.py b/saleor/graphql/menu/tests/deprecated/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/graphql/menu/tests/deprecated/test_menu.py b/saleor/graphql/menu/tests/deprecated/test_menu.py
new file mode 100644
index 0000000000..6f491cfa6b
--- /dev/null
+++ b/saleor/graphql/menu/tests/deprecated/test_menu.py
@@ -0,0 +1,56 @@
+import warnings
+
+import graphene
+
+from .....channel.utils import DEPRECATION_WARNING_MESSAGE
+from .....menu.models import MenuItem
+from ....tests.utils import get_graphql_content
+
+
+def test_menu_items_collection_without_providing_channel(
+ user_api_client, menu_item, published_collection
+):
+ query = """
+ query menuitem($id: ID!, $channel: String) {
+ menuItem(id: $id, channel: $channel) {
+ name
+ children {
+ name
+ }
+ collection {
+ name
+ }
+ category {
+ id
+ }
+ page {
+ id
+ }
+ url
+ }
+ }
+ """
+ menu_item.collection = published_collection
+ menu_item.url = None
+ menu_item.save()
+ child_menu = MenuItem.objects.create(
+ menu=menu_item.menu, name="Link 2", url="http://example2.com/", parent=menu_item
+ )
+ variables = {
+ "id": graphene.Node.to_global_id("MenuItem", menu_item.pk),
+ }
+ with warnings.catch_warnings(record=True) as warns:
+ response = user_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ assert any(
+ [str(warning.message) == DEPRECATION_WARNING_MESSAGE for warning in warns]
+ )
+
+ data = content["data"]["menuItem"]
+ assert data["name"] == menu_item.name
+ assert len(data["children"]) == 1
+ assert data["children"][0]["name"] == child_menu.name
+ assert data["collection"]["name"] == published_collection.name
+ assert not data["category"]
+ assert not data["page"]
+ assert data["url"] is None
diff --git a/saleor/graphql/menu/tests/test_menu.py b/saleor/graphql/menu/tests/test_menu.py
index d8c4f92bae..5b43ff5692 100644
--- a/saleor/graphql/menu/tests/test_menu.py
+++ b/saleor/graphql/menu/tests/test_menu.py
@@ -226,10 +226,12 @@ def test_query_menus_with_sort(
assert menus[order]["node"]["name"] == menu_name
-def test_menu_items_query(user_api_client, menu_item, collection):
+def test_menu_items_query(
+ user_api_client, menu_item, published_collection, channel_USD
+):
query = """
- query menuitem($id: ID!) {
- menuItem(id: $id) {
+ query menuitem($id: ID!, $channel: String) {
+ menuItem(id: $id, channel: $channel) {
name
children {
name
@@ -247,20 +249,68 @@ def test_menu_items_query(user_api_client, menu_item, collection):
}
}
"""
- menu_item.collection = collection
+ menu_item.collection = published_collection
menu_item.url = None
menu_item.save()
child_menu = MenuItem.objects.create(
menu=menu_item.menu, name="Link 2", url="http://example2.com/", parent=menu_item
)
- variables = {"id": graphene.Node.to_global_id("MenuItem", menu_item.pk)}
+ variables = {
+ "id": graphene.Node.to_global_id("MenuItem", menu_item.pk),
+ "channel": channel_USD.slug,
+ }
+ response = user_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["menuItem"]
+ assert data["name"] == menu_item.name
+ assert len(data["children"]) == 1
+ assert data["children"][0]["name"] == child_menu.name
+ assert data["collection"]["name"] == published_collection.name
+ assert not data["category"]
+ assert not data["page"]
+ assert data["url"] is None
+
+
+def test_menu_items_collection_in_other_channel(
+ user_api_client, menu_item, published_collection, channel_PLN
+):
+ query = """
+ query menuitem($id: ID!, $channel: String) {
+ menuItem(id: $id, channel: $channel) {
+ name
+ children {
+ name
+ }
+ collection {
+ name
+ }
+ category {
+ id
+ }
+ page {
+ id
+ }
+ url
+ }
+ }
+ """
+ menu_item.collection = published_collection
+ menu_item.url = None
+ menu_item.save()
+ child_menu = MenuItem.objects.create(
+ menu=menu_item.menu, name="Link 2", url="http://example2.com/", parent=menu_item
+ )
+ variables = {
+ "id": graphene.Node.to_global_id("MenuItem", menu_item.pk),
+ "channel": channel_PLN.slug,
+ }
response = user_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["menuItem"]
assert data["name"] == menu_item.name
assert len(data["children"]) == 1
assert data["children"][0]["name"] == child_menu.name
- assert data["collection"]["name"] == collection.name
+ assert not data["collection"]
assert not data["category"]
assert not data["page"]
assert data["url"] is None
@@ -360,7 +410,7 @@ def test_menu_item_query_static_url(user_api_client, menu_item):
def test_create_menu(
- staff_api_client, collection, category, page, permission_manage_menus
+ staff_api_client, published_collection, category, page, permission_manage_menus
):
query = """
mutation mc($name: String!, $collection: ID,
@@ -386,7 +436,7 @@ def test_create_menu(
"""
category_id = graphene.Node.to_global_id("Category", category.pk)
- collection_id = graphene.Node.to_global_id("Collection", collection.pk)
+ collection_id = graphene.Node.to_global_id("Collection", published_collection.pk)
page_id = graphene.Node.to_global_id("Page", page.pk)
url = "http://www.example.com"
diff --git a/saleor/graphql/menu/types.py b/saleor/graphql/menu/types.py
index 4d08d55ecb..d6c1f06794 100644
--- a/saleor/graphql/menu/types.py
+++ b/saleor/graphql/menu/types.py
@@ -2,11 +2,19 @@ import graphene
from graphene import relay
from ...menu import models
+from ...product.models import Collection
+from ..channel.dataloaders import ChannelBySlugLoader
+from ..channel.types import ChannelContext, ChannelContextType
from ..core.connection import CountableDjangoObjectType
from ..page.dataloaders import PageByIdLoader
-from ..product.dataloaders import CategoryByIdLoader, CollectionByIdLoader
+from ..product.dataloaders import (
+ CategoryByIdLoader,
+ CollectionByIdLoader,
+ CollectionChannelListingByCollectionIdAndChannelSlugLoader,
+)
from ..translations.fields import TranslationField
from ..translations.types import MenuItemTranslation
+from ..utils import get_user_or_app_from_context
from .dataloaders import (
MenuByIdLoader,
MenuItemByIdLoader,
@@ -15,10 +23,11 @@ from .dataloaders import (
)
-class Menu(CountableDjangoObjectType):
+class Menu(ChannelContextType, CountableDjangoObjectType):
items = graphene.List(lambda: MenuItem)
class Meta:
+ default_resolver = ChannelContextType.resolver_with_context
description = (
"Represents a single menu - an object that is used to help navigate "
"through the store."
@@ -28,16 +37,28 @@ class Menu(CountableDjangoObjectType):
model = models.Menu
@staticmethod
- def resolve_items(root: models.Menu, info, **_kwargs):
- return MenuItemsByParentMenuLoader(info.context).load(root.id)
+ def resolve_items(root: ChannelContext[models.Menu], info, **_kwargs):
+ menu_items = MenuItemsByParentMenuLoader(info.context).load(root.node.id)
+ return menu_items.then(
+ lambda menu_items: [
+ ChannelContext(node=menu_item, channel_slug=root.channel_slug)
+ for menu_item in menu_items
+ ]
+ )
-class MenuItem(CountableDjangoObjectType):
+class MenuItem(ChannelContextType, CountableDjangoObjectType):
children = graphene.List(lambda: MenuItem)
url = graphene.String(description="URL to the menu item.")
- translation = TranslationField(MenuItemTranslation, type_name="menu item")
+ translation = TranslationField(
+ MenuItemTranslation,
+ type_name="menu item",
+ resolver=ChannelContextType.resolve_translation,
+ )
class Meta:
+ default_resolver = ChannelContextType.resolver_with_context
+
description = (
"Represents a single item of the related menu. Can store categories, "
"collection or pages."
@@ -56,37 +77,94 @@ class MenuItem(CountableDjangoObjectType):
model = models.MenuItem
@staticmethod
- def resolve_category(root: models.MenuItem, info, **_kwargs):
- if root.category_id:
- return CategoryByIdLoader(info.context).load(root.category_id)
+ def resolve_category(root: ChannelContext[models.MenuItem], info, **_kwargs):
+ if root.node.category_id:
+ return CategoryByIdLoader(info.context).load(root.node.category_id)
return None
@staticmethod
- def resolve_children(root: models.MenuItem, info, **_kwargs):
- return MenuItemChildrenLoader(info.context).load(root.id)
+ def resolve_children(root: ChannelContext[models.MenuItem], info, **_kwargs):
+ menus = MenuItemChildrenLoader(info.context).load(root.node.id)
+ return menus.then(
+ lambda menus: [
+ ChannelContext(node=menu, channel_slug=None) for menu in menus
+ ]
+ )
@staticmethod
- def resolve_collection(root: models.MenuItem, info, **_kwargs):
- if root.collection_id:
- return CollectionByIdLoader(info.context).load(root.collection_id)
- return None
+ def resolve_collection(root: ChannelContext[models.MenuItem], info, **_kwargs):
+ if not root.node.collection_id:
+ return None
+
+ requestor = get_user_or_app_from_context(info.context)
+ requestor_has_access_to_all = Collection.objects.user_has_access_to_all(
+ requestor
+ )
+ if requestor_has_access_to_all:
+ return (
+ CollectionByIdLoader(info.context)
+ .load(root.node.collection_id)
+ .then(
+ lambda collection: ChannelContext(
+ node=collection, channel_slug=root.channel_slug
+ )
+ if collection
+ else None
+ )
+ )
+
+ # If it's a non-staff user with proper permission we should check that
+ # channel is active and collection is visible in this channel
+ channel_slug = str(root.channel_slug)
+ channel = ChannelBySlugLoader(info.context).load(channel_slug)
+
+ def calculate_collection_availability(collection_channel_listing):
+ def calculate_collection_availability_with_channel(channel):
+ collection_is_visible = (
+ collection_channel_listing.is_visible
+ if collection_channel_listing
+ else False
+ )
+ if not channel.is_active or not collection_is_visible:
+ return None
+ return (
+ CollectionByIdLoader(info.context)
+ .load(root.node.collection_id)
+ .then(
+ lambda collection: ChannelContext(
+ node=collection, channel_slug=channel_slug
+ )
+ if collection
+ else None
+ )
+ )
+
+ return channel.then(calculate_collection_availability_with_channel)
+
+ return (
+ CollectionChannelListingByCollectionIdAndChannelSlugLoader(info.context)
+ .load((root.node.collection_id, channel_slug))
+ .then(calculate_collection_availability)
+ )
@staticmethod
- def resolve_menu(root: models.MenuItem, info, **_kwargs):
- if root.menu_id:
- return MenuByIdLoader(info.context).load(root.menu_id)
+ def resolve_menu(root: ChannelContext[models.MenuItem], info, **_kwargs):
+ if root.node.menu_id:
+ menu = MenuByIdLoader(info.context).load(root.node.menu_id)
+ return menu.then(lambda menu: ChannelContext(node=menu, channel_slug=None))
return None
@staticmethod
- def resolve_parent(root: models.MenuItem, info, **_kwargs):
- if root.parent_id:
- return MenuItemByIdLoader(info.context).load(root.parent_id)
+ def resolve_parent(root: ChannelContext[models.MenuItem], info, **_kwargs):
+ if root.node.parent_id:
+ menu = MenuItemByIdLoader(info.context).load(root.node.parent_id)
+ return menu.then(lambda menu: ChannelContext(node=menu, channel_slug=None))
return None
@staticmethod
- def resolve_page(root: models.MenuItem, info, **kwargs):
- if root.page_id:
- return PageByIdLoader(info.context).load(root.page_id)
+ def resolve_page(root: ChannelContext[models.MenuItem], info, **kwargs):
+ if root.node.page_id:
+ return PageByIdLoader(info.context).load(root.node.page_id)
return None
diff --git a/saleor/graphql/meta/mutations.py b/saleor/graphql/meta/mutations.py
index 134deb6d40..597ac0a51e 100644
--- a/saleor/graphql/meta/mutations.py
+++ b/saleor/graphql/meta/mutations.py
@@ -6,6 +6,9 @@ from django.core.exceptions import ValidationError
from ...core import models
from ...core.error_codes import MetadataErrorCode
from ...core.exceptions import PermissionDenied
+from ...product import models as product_models
+from ...shipping import models as shipping_models
+from ..channel import ChannelContext
from ..core.mutations import BaseMutation
from ..core.types.common import MetadataError
from .extra_methods import MODEL_EXTRA_METHODS
@@ -112,6 +115,21 @@ class BaseMetadataMutation(BaseMutation):
@classmethod
def success_response(cls, instance):
"""Return a success response."""
+ # Wrap the instance with ChannelContext for models that use it.
+ use_channel_context = any(
+ [
+ isinstance(instance, Model)
+ for Model in [
+ product_models.Product,
+ product_models.ProductVariant,
+ product_models.Collection,
+ shipping_models.ShippingMethod,
+ shipping_models.ShippingZone,
+ ]
+ ]
+ )
+ if use_channel_context:
+ instance = ChannelContext(node=instance, channel_slug=None)
return cls(**{"item": instance, "errors": []})
diff --git a/saleor/graphql/meta/tests/test_meta_mutations.py b/saleor/graphql/meta/tests/test_meta_mutations.py
index 2e974622c1..730fa92880 100644
--- a/saleor/graphql/meta/tests/test_meta_mutations.py
+++ b/saleor/graphql/meta/tests/test_meta_mutations.py
@@ -381,10 +381,10 @@ def test_add_public_metadata_for_category(
def test_add_public_metadata_for_collection(
- staff_api_client, permission_manage_products, collection
+ staff_api_client, permission_manage_products, published_collection, channel_USD
):
# given
- collection_id = graphene.Node.to_global_id("Collection", collection.pk)
+ collection_id = graphene.Node.to_global_id("Collection", published_collection.pk)
# when
response = execute_update_public_metadata_for_item(
@@ -393,7 +393,7 @@ def test_add_public_metadata_for_collection(
# then
assert item_contains_proper_public_metadata(
- response["data"]["updateMetadata"]["item"], collection, collection_id
+ response["data"]["updateMetadata"]["item"], published_collection, collection_id
)
@@ -933,9 +933,10 @@ def test_delete_public_metadata_for_category(
def test_delete_public_metadata_for_collection(
- staff_api_client, permission_manage_products, collection
+ staff_api_client, permission_manage_products, published_collection, channel_USD
):
# given
+ collection = published_collection
collection.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
collection.save(update_fields=["metadata"])
collection_id = graphene.Node.to_global_id("Collection", collection.pk)
@@ -1547,9 +1548,10 @@ def test_add_private_metadata_for_category(
def test_add_private_metadata_for_collection(
- staff_api_client, permission_manage_products, collection
+ staff_api_client, permission_manage_products, published_collection, channel_USD
):
# given
+ collection = published_collection
collection_id = graphene.Node.to_global_id("Collection", collection.pk)
# when
@@ -2125,9 +2127,10 @@ def test_delete_private_metadata_for_category(
def test_delete_private_metadata_for_collection(
- staff_api_client, permission_manage_products, collection
+ staff_api_client, permission_manage_products, published_collection, channel_USD
):
# given
+ collection = published_collection
collection.store_value_in_private_metadata({PRIVATE_KEY: PRIVATE_VALUE})
collection.save(update_fields=["private_metadata"])
collection_id = graphene.Node.to_global_id("Collection", collection.pk)
diff --git a/saleor/graphql/meta/tests/test_meta_queries.py b/saleor/graphql/meta/tests/test_meta_queries.py
index f7676f93a5..90f41f7087 100644
--- a/saleor/graphql/meta/tests/test_meta_queries.py
+++ b/saleor/graphql/meta/tests/test_meta_queries.py
@@ -143,8 +143,8 @@ def test_query_public_meta_for_staff_as_app(
QUERY_CHECKOUT_PUBLIC_META = """
- query checkoutMeta($token: UUID!){
- checkout(token: $token){
+ query checkoutMeta($token: UUID!, $channel: String!){
+ checkout(token: $token, channel: $channel){
metadata{
key
value
@@ -158,7 +158,7 @@ def test_query_public_meta_for_checkout_as_anonymous_user(api_client, checkout):
# given
checkout.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
checkout.save(update_fields=["metadata"])
- variables = {"token": checkout.pk}
+ variables = {"token": checkout.pk, "channel": checkout.channel.slug}
# when
response = api_client.post_graphql(QUERY_CHECKOUT_PUBLIC_META, variables)
@@ -177,7 +177,7 @@ def test_query_public_meta_for_other_customer_checkout_as_anonymous_user(
checkout.user = customer_user
checkout.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
checkout.save(update_fields=["user", "metadata"])
- variables = {"token": checkout.pk}
+ variables = {"token": checkout.pk, "channel": checkout.channel.slug}
# when
response = api_client.post_graphql(QUERY_CHECKOUT_PUBLIC_META, variables)
@@ -192,7 +192,7 @@ def test_query_public_meta_for_checkout_as_customer(user_api_client, checkout):
checkout.user = user_api_client.user
checkout.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
checkout.save(update_fields=["user", "metadata"])
- variables = {"token": checkout.pk}
+ variables = {"token": checkout.pk, "channel": checkout.channel.slug}
# when
response = user_api_client.post_graphql(QUERY_CHECKOUT_PUBLIC_META, variables)
@@ -211,7 +211,7 @@ def test_query_public_meta_for_checkout_as_staff(
checkout.user = customer_user
checkout.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
checkout.save(update_fields=["user", "metadata"])
- variables = {"token": checkout.pk}
+ variables = {"token": checkout.pk, "channel": checkout.channel.slug}
# when
response = staff_api_client.post_graphql(
@@ -235,7 +235,7 @@ def test_query_public_meta_for_checkout_as_app(
checkout.user = customer_user
checkout.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
checkout.save(update_fields=["user", "metadata"])
- variables = {"token": checkout.pk}
+ variables = {"token": checkout.pk, "channel": checkout.channel.slug}
# when
response = app_api_client.post_graphql(
@@ -802,8 +802,8 @@ def test_query_public_meta_for_category_as_app(
QUERY_COLLECTION_PUBLIC_META = """
- query collectionMeta($id: ID!){
- collection(id: $id){
+ query collectionMeta($id: ID!, $channel: String) {
+ collection(id: $id, channel: $channel) {
metadata{
key
value
@@ -813,12 +813,17 @@ QUERY_COLLECTION_PUBLIC_META = """
"""
-def test_query_public_meta_for_collection_as_anonymous_user(api_client, collection):
+def test_query_public_meta_for_collection_as_anonymous_user(
+ api_client, published_collection, channel_USD
+):
# given
+ collection = published_collection
collection.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
collection.save(update_fields=["metadata"])
- variables = {"id": graphene.Node.to_global_id("Collection", collection.pk)}
-
+ variables = {
+ "id": graphene.Node.to_global_id("Collection", collection.pk),
+ "channel": channel_USD.slug,
+ }
# when
response = api_client.post_graphql(QUERY_COLLECTION_PUBLIC_META, variables)
content = get_graphql_content(response)
@@ -829,11 +834,17 @@ def test_query_public_meta_for_collection_as_anonymous_user(api_client, collecti
assert metadata["value"] == PUBLIC_VALUE
-def test_query_public_meta_for_collection_as_customer(user_api_client, collection):
+def test_query_public_meta_for_collection_as_customer(
+ user_api_client, published_collection, channel_USD
+):
# given
+ collection = published_collection
collection.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
collection.save(update_fields=["metadata"])
- variables = {"id": graphene.Node.to_global_id("Collection", collection.pk)}
+ variables = {
+ "id": graphene.Node.to_global_id("Collection", collection.pk),
+ "channel": channel_USD.slug,
+ }
# when
response = user_api_client.post_graphql(QUERY_COLLECTION_PUBLIC_META, variables)
@@ -846,12 +857,16 @@ def test_query_public_meta_for_collection_as_customer(user_api_client, collectio
def test_query_public_meta_for_collection_as_staff(
- staff_api_client, collection, permission_manage_products
+ staff_api_client, published_collection, permission_manage_products, channel_USD
):
# given
+ collection = published_collection
collection.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
collection.save(update_fields=["metadata"])
- variables = {"id": graphene.Node.to_global_id("Collection", collection.pk)}
+ variables = {
+ "id": graphene.Node.to_global_id("Collection", collection.pk),
+ "channel": channel_USD.slug,
+ }
# when
response = staff_api_client.post_graphql(
@@ -869,13 +884,16 @@ def test_query_public_meta_for_collection_as_staff(
def test_query_public_meta_for_collection_as_app(
- app_api_client, collection, permission_manage_products
+ app_api_client, published_collection, permission_manage_products, channel_USD
):
# given
+ collection = published_collection
collection.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
collection.save(update_fields=["metadata"])
- variables = {"id": graphene.Node.to_global_id("Collection", collection.pk)}
-
+ variables = {
+ "id": graphene.Node.to_global_id("Collection", collection.pk),
+ "channel": channel_USD.slug,
+ }
# when
response = app_api_client.post_graphql(
QUERY_COLLECTION_PUBLIC_META,
@@ -980,8 +998,8 @@ def test_query_public_meta_for_digital_content_as_app(
QUERY_PRODUCT_PUBLIC_META = """
- query productsMeta($id: ID!){
- product(id: $id){
+ query productsMeta($id: ID!, $channel: String){
+ product(id: $id, channel: $channel){
metadata{
key
value
@@ -991,11 +1009,16 @@ QUERY_PRODUCT_PUBLIC_META = """
"""
-def test_query_public_meta_for_product_as_anonymous_user(api_client, product):
+def test_query_public_meta_for_product_as_anonymous_user(
+ api_client, product, channel_USD
+):
# given
product.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
product.save(update_fields=["metadata"])
- variables = {"id": graphene.Node.to_global_id("Product", product.pk)}
+ variables = {
+ "id": graphene.Node.to_global_id("Product", product.pk),
+ "channel": channel_USD.slug,
+ }
# when
response = api_client.post_graphql(QUERY_PRODUCT_PUBLIC_META, variables)
@@ -1007,11 +1030,16 @@ def test_query_public_meta_for_product_as_anonymous_user(api_client, product):
assert metadata["value"] == PUBLIC_VALUE
-def test_query_public_meta_for_product_as_customer(user_api_client, product):
+def test_query_public_meta_for_product_as_customer(
+ user_api_client, product, channel_USD
+):
# given
product.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
product.save(update_fields=["metadata"])
- variables = {"id": graphene.Node.to_global_id("Product", product.pk)}
+ variables = {
+ "id": graphene.Node.to_global_id("Product", product.pk),
+ "channel": channel_USD.slug,
+ }
# when
response = user_api_client.post_graphql(QUERY_PRODUCT_PUBLIC_META, variables)
@@ -1160,8 +1188,8 @@ def test_query_public_meta_for_product_type_as_app(
QUERY_PRODUCT_VARIANT_PUBLIC_META = """
- query productVariantMeta($id: ID!){
- productVariant(id: $id){
+ query productVariantMeta($id: ID!, $channel: String){
+ productVariant(id: $id, channel: $channel){
metadata{
key
value
@@ -1171,11 +1199,16 @@ QUERY_PRODUCT_VARIANT_PUBLIC_META = """
"""
-def test_query_public_meta_for_product_variant_as_anonymous_user(api_client, variant):
+def test_query_public_meta_for_product_variant_as_anonymous_user(
+ api_client, variant, channel_USD
+):
# given
variant.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
variant.save(update_fields=["metadata"])
- variables = {"id": graphene.Node.to_global_id("ProductVariant", variant.pk)}
+ variables = {
+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),
+ "channel": channel_USD.slug,
+ }
# when
response = api_client.post_graphql(QUERY_PRODUCT_VARIANT_PUBLIC_META, variables)
@@ -1187,11 +1220,16 @@ def test_query_public_meta_for_product_variant_as_anonymous_user(api_client, var
assert metadata["value"] == PUBLIC_VALUE
-def test_query_public_meta_for_product_variant_as_customer(user_api_client, variant):
+def test_query_public_meta_for_product_variant_as_customer(
+ user_api_client, variant, channel_USD
+):
# given
variant.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
variant.save(update_fields=["metadata"])
- variables = {"id": graphene.Node.to_global_id("ProductVariant", variant.pk)}
+ variables = {
+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),
+ "channel": channel_USD.slug,
+ }
# when
response = user_api_client.post_graphql(
@@ -1234,7 +1272,9 @@ def test_query_public_meta_for_product_variant_as_app(
# given
variant.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
variant.save(update_fields=["metadata"])
- variables = {"id": graphene.Node.to_global_id("ProductVariant", variant.pk)}
+ variables = {
+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),
+ }
# when
response = app_api_client.post_graphql(
@@ -1475,8 +1515,8 @@ def test_query_private_meta_for_staff_as_app(
QUERY_CHECKOUT_PRIVATE_META = """
- query checkoutMeta($token: UUID!){
- checkout(token: $token){
+ query checkoutMeta($token: UUID!, $channel: String!){
+ checkout(token: $token, channel: $channel){
privateMetadata{
key
value
@@ -1488,7 +1528,7 @@ QUERY_CHECKOUT_PRIVATE_META = """
def test_query_private_meta_for_checkout_as_anonymous_user(api_client, checkout):
# given
- variables = {"token": checkout.pk}
+ variables = {"token": checkout.pk, "channel": checkout.channel.slug}
# when
response = api_client.post_graphql(QUERY_CHECKOUT_PRIVATE_META, variables)
@@ -1503,7 +1543,7 @@ def test_query_private_meta_for_other_customer_checkout_as_anonymous_user(
# given
checkout.user = customer_user
checkout.save(update_fields=["user"])
- variables = {"token": checkout.pk}
+ variables = {"token": checkout.pk, "channel": checkout.channel.slug}
# when
response = api_client.post_graphql(QUERY_CHECKOUT_PRIVATE_META, variables)
@@ -1517,7 +1557,7 @@ def test_query_private_meta_for_checkout_as_customer(user_api_client, checkout):
# given
checkout.user = user_api_client.user
checkout.save(update_fields=["user"])
- variables = {"token": checkout.pk}
+ variables = {"token": checkout.pk, "channel": checkout.channel.slug}
# when
response = user_api_client.post_graphql(QUERY_CHECKOUT_PRIVATE_META, variables)
@@ -1533,7 +1573,7 @@ def test_query_private_meta_for_checkout_as_staff(
checkout.user = customer_user
checkout.store_value_in_private_metadata({PRIVATE_KEY: PRIVATE_VALUE})
checkout.save(update_fields=["user", "private_metadata"])
- variables = {"token": checkout.pk}
+ variables = {"token": checkout.pk, "channel": checkout.channel.slug}
# when
response = staff_api_client.post_graphql(
@@ -1557,7 +1597,7 @@ def test_query_private_meta_for_checkout_as_app(
checkout.user = customer_user
checkout.store_value_in_private_metadata({PRIVATE_KEY: PRIVATE_VALUE})
checkout.save(update_fields=["user", "private_metadata"])
- variables = {"token": checkout.pk}
+ variables = {"token": checkout.pk, "channel": checkout.channel.slug}
# when
response = app_api_client.post_graphql(
@@ -2086,8 +2126,8 @@ def test_query_private_meta_for_category_as_app(
QUERY_COLLECTION_PRIVATE_META = """
- query collectionMeta($id: ID!){
- collection(id: $id){
+ query collectionMeta($id: ID!, $channel: String){
+ collection(id: $id, channel: $channel){
privateMetadata{
key
value
@@ -2097,9 +2137,14 @@ QUERY_COLLECTION_PRIVATE_META = """
"""
-def test_query_private_meta_for_collection_as_anonymous_user(api_client, collection):
+def test_query_private_meta_for_collection_as_anonymous_user(
+ api_client, published_collection, channel_USD
+):
# given
- variables = {"id": graphene.Node.to_global_id("Collection", collection.pk)}
+ variables = {
+ "id": graphene.Node.to_global_id("Collection", published_collection.pk),
+ "channel": channel_USD.slug,
+ }
# when
response = api_client.post_graphql(QUERY_COLLECTION_PRIVATE_META, variables)
@@ -2108,9 +2153,14 @@ def test_query_private_meta_for_collection_as_anonymous_user(api_client, collect
assert_no_permission(response)
-def test_query_private_meta_for_collection_as_customer(user_api_client, collection):
+def test_query_private_meta_for_collection_as_customer(
+ user_api_client, published_collection, channel_USD
+):
# given
- variables = {"id": graphene.Node.to_global_id("Collection", collection.pk)}
+ variables = {
+ "id": graphene.Node.to_global_id("Collection", published_collection.pk),
+ "channel": channel_USD.slug,
+ }
# when
response = user_api_client.post_graphql(QUERY_COLLECTION_PRIVATE_META, variables)
@@ -2120,12 +2170,16 @@ def test_query_private_meta_for_collection_as_customer(user_api_client, collecti
def test_query_private_meta_for_collection_as_staff(
- staff_api_client, collection, permission_manage_products
+ staff_api_client, published_collection, permission_manage_products, channel_USD
):
# given
+ collection = published_collection
collection.store_value_in_private_metadata({PRIVATE_KEY: PRIVATE_VALUE})
collection.save(update_fields=["private_metadata"])
- variables = {"id": graphene.Node.to_global_id("Collection", collection.pk)}
+ variables = {
+ "id": graphene.Node.to_global_id("Collection", published_collection.pk),
+ "channel": channel_USD.slug,
+ }
# when
response = staff_api_client.post_graphql(
@@ -2143,12 +2197,16 @@ def test_query_private_meta_for_collection_as_staff(
def test_query_private_meta_for_collection_as_app(
- app_api_client, collection, permission_manage_products
+ app_api_client, published_collection, permission_manage_products, channel_USD
):
# given
+ collection = published_collection
collection.store_value_in_private_metadata({PRIVATE_KEY: PRIVATE_VALUE})
collection.save(update_fields=["private_metadata"])
- variables = {"id": graphene.Node.to_global_id("Collection", collection.pk)}
+ variables = {
+ "id": graphene.Node.to_global_id("Collection", collection.pk),
+ "channel": channel_USD.slug,
+ }
# when
response = app_api_client.post_graphql(
@@ -2254,8 +2312,8 @@ def test_query_private_meta_for_digital_content_as_app(
QUERY_PRODUCT_PRIVATE_META = """
- query productsMeta($id: ID!){
- product(id: $id){
+ query productsMeta($id: ID!, $channel: String){
+ product(id: $id, channel: $channel){
privateMetadata{
key
value
@@ -2265,9 +2323,14 @@ QUERY_PRODUCT_PRIVATE_META = """
"""
-def test_query_private_meta_for_product_as_anonymous_user(api_client, product):
+def test_query_private_meta_for_product_as_anonymous_user(
+ api_client, product, channel_USD
+):
# given
- variables = {"id": graphene.Node.to_global_id("Product", product.pk)}
+ variables = {
+ "id": graphene.Node.to_global_id("Product", product.pk),
+ "channel": channel_USD.slug,
+ }
# when
response = api_client.post_graphql(QUERY_PRODUCT_PRIVATE_META, variables)
@@ -2276,9 +2339,14 @@ def test_query_private_meta_for_product_as_anonymous_user(api_client, product):
assert_no_permission(response)
-def test_query_private_meta_for_product_as_customer(user_api_client, product):
+def test_query_private_meta_for_product_as_customer(
+ user_api_client, product, channel_USD
+):
# given
- variables = {"id": graphene.Node.to_global_id("Product", product.pk)}
+ variables = {
+ "id": graphene.Node.to_global_id("Product", product.pk),
+ "channel": channel_USD.slug,
+ }
# when
response = user_api_client.post_graphql(QUERY_PRODUCT_PRIVATE_META, variables)
@@ -2316,7 +2384,9 @@ def test_query_private_meta_for_product_as_app(
# given
product.store_value_in_private_metadata({PRIVATE_KEY: PRIVATE_VALUE})
product.save(update_fields=["private_metadata"])
- variables = {"id": graphene.Node.to_global_id("Product", product.pk)}
+ variables = {
+ "id": graphene.Node.to_global_id("Product", product.pk),
+ }
# when
response = app_api_client.post_graphql(
@@ -2416,8 +2486,8 @@ def test_query_private_meta_for_product_type_as_app(
QUERY_PRODUCT_VARIANT_PRIVATE_META = """
- query productVariantMeta($id: ID!){
- productVariant(id: $id){
+ query productVariantMeta($id: ID!, $channel: String){
+ productVariant(id: $id, channel: $channel){
privateMetadata{
key
value
@@ -2427,11 +2497,16 @@ QUERY_PRODUCT_VARIANT_PRIVATE_META = """
"""
-def test_query_private_meta_for_product_variant_as_anonymous_user(api_client, variant):
+def test_query_private_meta_for_product_variant_as_anonymous_user(
+ api_client, variant, channel_USD
+):
# given
variant.store_value_in_private_metadata({PRIVATE_KEY: PRIVATE_VALUE})
variant.save(update_fields=["private_metadata"])
- variables = {"id": graphene.Node.to_global_id("ProductVariant", variant.pk)}
+ variables = {
+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),
+ "channel": channel_USD.slug,
+ }
# when
response = api_client.post_graphql(QUERY_PRODUCT_VARIANT_PRIVATE_META, variables)
@@ -2440,11 +2515,16 @@ def test_query_private_meta_for_product_variant_as_anonymous_user(api_client, va
assert_no_permission(response)
-def test_query_private_meta_for_product_variant_as_customer(user_api_client, variant):
+def test_query_private_meta_for_product_variant_as_customer(
+ user_api_client, variant, channel_USD
+):
# given
variant.store_value_in_private_metadata({PRIVATE_KEY: PRIVATE_VALUE})
variant.save(update_fields=["private_metadata"])
- variables = {"id": graphene.Node.to_global_id("ProductVariant", variant.pk)}
+ variables = {
+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),
+ "channel": channel_USD.slug,
+ }
# when
response = user_api_client.post_graphql(
@@ -2484,7 +2564,9 @@ def test_query_private_meta_for_product_variant_as_app(
# given
variant.store_value_in_private_metadata({PRIVATE_KEY: PRIVATE_VALUE})
variant.save(update_fields=["private_metadata"])
- variables = {"id": graphene.Node.to_global_id("ProductVariant", variant.pk)}
+ variables = {
+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),
+ }
# when
response = app_api_client.post_graphql(
diff --git a/saleor/graphql/meta/types.py b/saleor/graphql/meta/types.py
index cc525a0ca8..16cba9d967 100644
--- a/saleor/graphql/meta/types.py
+++ b/saleor/graphql/meta/types.py
@@ -1,6 +1,7 @@
import graphene
from ...core.models import ModelWithMetadata
+from ..channel import ChannelContext
from .resolvers import (
resolve_metadata,
resolve_object_with_metadata_type,
@@ -40,4 +41,7 @@ class ObjectWithMetadata(graphene.Interface):
@classmethod
def resolve_type(cls, instance: ModelWithMetadata, _info):
+ if isinstance(instance, ChannelContext):
+ # Return instance for types that use ChannelContext
+ instance = instance.node
return resolve_object_with_metadata_type(instance)
diff --git a/saleor/graphql/order/dataloaders.py b/saleor/graphql/order/dataloaders.py
index db087d0222..1c97d12007 100644
--- a/saleor/graphql/order/dataloaders.py
+++ b/saleor/graphql/order/dataloaders.py
@@ -1,9 +1,56 @@
from collections import defaultdict
+from django.db.models import F
+
+from ...order.models import Order, OrderLine
from ...warehouse.models import Allocation
from ..core.dataloaders import DataLoader
+class OrderLinesByVariantIdAndChannelIdLoader(DataLoader):
+ context_key = "orderline_by_variant_and_channel"
+
+ def batch_load(self, keys):
+ channel_ids = [key[1] for key in keys]
+ variant_ids = [key[0] for key in keys]
+ order_lines = OrderLine.objects.filter(
+ order__channel_id__in=channel_ids, variant_id__in=variant_ids
+ ).annotate(channel_id=F("order__channel_id"))
+
+ order_line_by_variant_and_channel_map = defaultdict(list)
+ for order_line in order_lines:
+ key = (order_line.variant_id, order_line.channel_id)
+ order_line_by_variant_and_channel_map[key].append(order_line)
+ return [order_line_by_variant_and_channel_map[key] for key in keys]
+
+
+class OrderByIdLoader(DataLoader):
+ context_key = "order_by_id"
+
+ def batch_load(self, keys):
+ orders = Order.objects.in_bulk(keys)
+ return [orders.get(order_id) for order_id in keys]
+
+
+class OrderLineByIdLoader(DataLoader):
+ context_key = "orderline_by_id"
+
+ def batch_load(self, keys):
+ order_lines = OrderLine.objects.in_bulk(keys)
+ return [order_lines.get(line_id) for line_id in keys]
+
+
+class OrderLinesByOrderIdLoader(DataLoader):
+ context_key = "orderlines_by_order"
+
+ def batch_load(self, keys):
+ lines = OrderLine.objects.filter(order_id__in=keys).order_by("pk")
+ line_map = defaultdict(list)
+ for line in lines.iterator():
+ line_map[line.order_id].append(line)
+ return [line_map.get(order_id, []) for order_id in keys]
+
+
class AllocationsByOrderLineIdLoader(DataLoader):
context_key = "allocations_by_orderline_id"
diff --git a/saleor/graphql/order/mutations/draft_orders.py b/saleor/graphql/order/mutations/draft_orders.py
index 4f5b494726..3bd013ff4c 100644
--- a/saleor/graphql/order/mutations/draft_orders.py
+++ b/saleor/graphql/order/mutations/draft_orders.py
@@ -21,12 +21,17 @@ from ....order.utils import (
from ....warehouse.management import allocate_stock
from ...account.i18n import I18nMixin
from ...account.types import AddressInput
+from ...channel.types import Channel
from ...core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation
from ...core.scalars import PositiveDecimal
from ...core.types.common import OrderError
from ...product.types import ProductVariant
from ..types import Order, OrderLine
-from ..utils import validate_draft_order
+from ..utils import (
+ validate_draft_order,
+ validate_product_is_published_in_channel,
+ validate_variant_channel_listings,
+)
class OrderLineInput(graphene.InputObjectType):
@@ -58,6 +63,9 @@ class DraftOrderInput(InputObjectType):
customer_note = graphene.String(
description="A note from a customer. Visible by customers in the order summary."
)
+ channel = graphene.ID(
+ description="ID of the channel associated with the order.", name="channel"
+ )
class DraftOrderCreateInput(DraftOrderInput):
@@ -82,16 +90,62 @@ class DraftOrderCreate(ModelMutation, I18nMixin):
error_type_class = OrderError
error_type_field = "order_errors"
+ @classmethod
+ def clean_channel_id(cls, instance, channel_id):
+ if channel_id and hasattr(instance, "channel"):
+ raise ValidationError(
+ {
+ "channel": ValidationError(
+ "Can't update existing order channel id.",
+ code=OrderErrorCode.NOT_EDITABLE.value,
+ )
+ }
+ )
+
+ @classmethod
+ def clean_voucher(cls, voucher, channel):
+ if not voucher.channel_listings.filter(channel=channel).exists():
+ raise ValidationError(
+ {
+ "voucher": ValidationError(
+ "Voucher not available for this order.",
+ code=OrderErrorCode.NOT_AVAILABLE_IN_CHANNEL.value,
+ )
+ }
+ )
+
@classmethod
def clean_input(cls, info, instance, data):
shipping_address = data.pop("shipping_address", None)
billing_address = data.pop("billing_address", None)
cleaned_input = super().clean_input(info, instance, data)
-
lines = data.pop("lines", None)
+ channel_id = data.get("channel", None)
+ if "channel" in cleaned_input and channel_id is None:
+ del cleaned_input["channel"]
+ cls.clean_channel_id(instance, channel_id)
+ voucher = cleaned_input.get("voucher", None)
+ if voucher:
+ channel = cleaned_input.get("channel") or instance.channel
+ cls.clean_voucher(voucher, channel)
+
+ channel = instance.channel if hasattr(instance, "channel") else None
+ if not channel and channel_id:
+ channel = cls.get_node_or_error(info, channel_id, only_type=Channel)
+ if channel:
+ cleaned_input["currency"] = channel.currency_code
+
if lines:
variant_ids = [line.get("variant_id") for line in lines]
variants = cls.get_nodes_or_error(variant_ids, "variants", ProductVariant)
+ try:
+ validate_product_is_published_in_channel(variants, channel)
+ validate_variant_channel_listings(variants, channel)
+ except ValidationError as error:
+ field_name = "lines"
+ if error.code == OrderErrorCode.REQUIRED:
+ field_name = "channel"
+ raise ValidationError({field_name: error})
quantities = [line.get("quantity") for line in lines]
cleaned_input["variants"] = variants
cleaned_input["quantities"] = quantities
@@ -279,7 +333,7 @@ class DraftOrderComplete(BaseMutation):
if not order.is_shipping_required():
order.shipping_method_name = None
- order.shipping_price = zero_taxed_money()
+ order.shipping_price = zero_taxed_money(order.currency)
if order.shipping_address:
order.shipping_address.delete()
order.shipping_address = None
@@ -358,7 +412,13 @@ class DraftOrderLinesCreate(BaseMutation):
)
}
)
-
+ variants = [line[1] for line in lines_to_add]
+ try:
+ channel = order.channel
+ validate_product_is_published_in_channel(variants, channel)
+ validate_variant_channel_listings(variants, channel)
+ except ValidationError as error:
+ raise ValidationError({"input": error})
# Add the lines
try:
lines = [
diff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.py
index adfb64dc78..f5d3eed95a 100644
--- a/saleor/graphql/order/mutations/orders.py
+++ b/saleor/graphql/order/mutations/orders.py
@@ -231,7 +231,7 @@ class OrderUpdateShipping(BaseMutation):
)
order.shipping_method = None
- order.shipping_price = zero_taxed_money()
+ order.shipping_price = zero_taxed_money(order.currency)
order.shipping_method_name = None
order.save(
update_fields=[
diff --git a/saleor/graphql/order/resolvers.py b/saleor/graphql/order/resolvers.py
index 60c65bbd2a..653543b9a6 100644
--- a/saleor/graphql/order/resolvers.py
+++ b/saleor/graphql/order/resolvers.py
@@ -1,9 +1,11 @@
import graphene
+from ...channel.models import Channel
from ...order import OrderStatus, models
from ...order.events import OrderEvents
from ...order.models import OrderEvent
from ...order.utils import sum_order_totals
+from ..channel.utils import get_default_channel_slug_or_graphql_error
from ..utils.filters import filter_by_period
from .enums import OrderStatusFilter
from .types import Order
@@ -28,8 +30,10 @@ def filter_orders(qs, info, created, status):
return qs
-def resolve_orders(info, created, status, **_kwargs):
+def resolve_orders(info, created, status, channel_slug, **_kwargs):
qs = models.Order.objects.confirmed()
+ if channel_slug:
+ qs = qs.filter(channel__slug=str(channel_slug))
return filter_orders(qs, info, created, status)
@@ -38,10 +42,19 @@ def resolve_draft_orders(info, created, **_kwargs):
return filter_orders(qs, info, created, None)
-def resolve_orders_total(_info, period):
- qs = models.Order.objects.confirmed().exclude(status=OrderStatus.CANCELED)
+def resolve_orders_total(_info, period, channel_slug):
+ if channel_slug is None:
+ channel_slug = get_default_channel_slug_or_graphql_error()
+ channel = Channel.objects.filter(slug=str(channel_slug)).first()
+ if not channel:
+ return None
+ qs = (
+ models.Order.objects.confirmed()
+ .exclude(status=OrderStatus.CANCELED)
+ .filter(channel__slug=str(channel_slug))
+ )
qs = filter_by_period(qs, period, "created")
- return sum_order_totals(qs)
+ return sum_order_totals(qs, channel.currency_code)
def resolve_order(info, order_id):
diff --git a/saleor/graphql/order/schema.py b/saleor/graphql/order/schema.py
index 80fe1fc5e1..a3a2c4d7b3 100644
--- a/saleor/graphql/order/schema.py
+++ b/saleor/graphql/order/schema.py
@@ -87,6 +87,9 @@ class OrderQueries(graphene.ObjectType):
"This field will be removed after 2020-07-31."
),
),
+ channel=graphene.String(
+ description="Slug of a channel for which the data should be returned."
+ ),
description="List of orders.",
)
draft_orders = FilterInputConnectionField(
@@ -106,6 +109,10 @@ class OrderQueries(graphene.ObjectType):
TaxedMoney,
description="Return the total sales amount from a specific period.",
period=graphene.Argument(ReportingPeriod, description="A period of time."),
+ channel=graphene.Argument(
+ graphene.String,
+ description="Slug of a channel for which the data should be returned.",
+ ),
)
order_by_token = graphene.Field(
Order,
@@ -122,16 +129,16 @@ class OrderQueries(graphene.ObjectType):
return resolve_order(info, data.get("id"))
@permission_required(OrderPermissions.MANAGE_ORDERS)
- def resolve_orders(self, info, created=None, status=None, **_kwargs):
- return resolve_orders(info, created, status)
+ def resolve_orders(self, info, created=None, status=None, channel=None, **_kwargs):
+ return resolve_orders(info, created, status, channel)
@permission_required(OrderPermissions.MANAGE_ORDERS)
def resolve_draft_orders(self, info, created=None, **_kwargs):
return resolve_draft_orders(info, created)
@permission_required(OrderPermissions.MANAGE_ORDERS)
- def resolve_orders_total(self, info, period, **_kwargs):
- return resolve_orders_total(info, period)
+ def resolve_orders_total(self, info, period, channel=None, **_kwargs):
+ return resolve_orders_total(info, period, channel)
def resolve_order_by_token(self, _info, token):
return resolve_order_by_token(token)
diff --git a/saleor/graphql/order/sorters.py b/saleor/graphql/order/sorters.py
index f8f143c465..4a561d64a1 100644
--- a/saleor/graphql/order/sorters.py
+++ b/saleor/graphql/order/sorters.py
@@ -11,7 +11,6 @@ class OrderSortField(graphene.Enum):
CUSTOMER = ["billing_address__last_name", "billing_address__first_name", "pk"]
PAYMENT = ["last_charge_status", "status", "pk"]
FULFILLMENT_STATUS = ["status", "user_email", "pk"]
- TOTAL = ["total_gross_amount", "status", "pk"]
@property
def description(self):
@@ -21,7 +20,7 @@ class OrderSortField(graphene.Enum):
raise ValueError("Unsupported enum value: %s" % self.value)
@staticmethod
- def qs_with_payment(queryset: QuerySet) -> QuerySet:
+ def qs_with_payment(queryset: QuerySet, **_kwargs) -> QuerySet:
subquery = Subquery(
Payment.objects.filter(order_id=OuterRef("pk"))
.order_by("-pk")
diff --git a/saleor/graphql/order/tests/deprecated/__init__.py b/saleor/graphql/order/tests/deprecated/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/graphql/order/tests/deprecated/test_order.py b/saleor/graphql/order/tests/deprecated/test_order.py
new file mode 100644
index 0000000000..13c3d6d5d6
--- /dev/null
+++ b/saleor/graphql/order/tests/deprecated/test_order.py
@@ -0,0 +1,42 @@
+import warnings
+
+from prices import Money
+
+from .....channel.utils import DEPRECATION_WARNING_MESSAGE
+from ....core.enums import ReportingPeriod
+from ....tests.utils import get_graphql_content
+
+QUERY_ORDER_TOTAL = """
+query Orders($period: ReportingPeriod, $channel: String) {
+ ordersTotal(period: $period, channel: $channel ) {
+ gross {
+ amount
+ currency
+ }
+ net {
+ currency
+ amount
+ }
+ }
+}
+"""
+
+
+def test_orders_total(staff_api_client, permission_manage_orders, order_with_lines):
+ # given
+ order = order_with_lines
+ variables = {"period": ReportingPeriod.TODAY.name}
+
+ # when
+ with warnings.catch_warnings(record=True) as warns:
+ response = staff_api_client.post_graphql(
+ QUERY_ORDER_TOTAL, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+
+ # then
+ amount = str(content["data"]["ordersTotal"]["gross"]["amount"])
+ assert Money(amount, "USD") == order.total.gross
+ assert any(
+ [str(warning.message) == DEPRECATION_WARNING_MESSAGE for warning in warns]
+ )
diff --git a/saleor/graphql/order/tests/test_homepage.py b/saleor/graphql/order/tests/test_homepage.py
index a18025e723..42899f338b 100644
--- a/saleor/graphql/order/tests/test_homepage.py
+++ b/saleor/graphql/order/tests/test_homepage.py
@@ -1,4 +1,7 @@
-from ...tests.utils import get_graphql_content
+from prices import Money
+
+from ...core.enums import ReportingPeriod
+from ...tests.utils import assert_no_permission, get_graphql_content
def test_homepage_events(order_events, staff_api_client, permission_manage_orders):
@@ -21,3 +24,287 @@ def test_homepage_events(order_events, staff_api_client, permission_manage_order
edges = content["data"]["homepageEvents"]["edges"]
only_types = {"PLACED", "PLACED_FROM_DRAFT", "ORDER_FULLY_PAID"}
assert {edge["node"]["type"] for edge in edges} == only_types
+
+
+QUERY_ORDER_TOTAL = """
+query Orders($period: ReportingPeriod, $channel: String) {
+ ordersTotal(period: $period, channel: $channel ) {
+ gross {
+ amount
+ currency
+ }
+ net {
+ currency
+ amount
+ }
+ }
+}
+"""
+
+
+def test_orders_total(
+ staff_api_client,
+ permission_manage_orders,
+ order_with_lines,
+ order_with_lines_channel_PLN,
+ channel_USD,
+):
+ # given
+ order = order_with_lines
+ variables = {"period": ReportingPeriod.TODAY.name, "channel": channel_USD.slug}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_ORDER_TOTAL, variables, permissions=[permission_manage_orders]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ amount = str(content["data"]["ordersTotal"]["gross"]["amount"])
+ assert Money(amount, "USD") == order.total.gross
+
+
+def test_orders_total_channel_pln(
+ staff_api_client,
+ permission_manage_orders,
+ order_with_lines,
+ order_with_lines_channel_PLN,
+ channel_PLN,
+):
+ # given
+ order = order_with_lines_channel_PLN
+ variables = {"period": ReportingPeriod.TODAY.name, "channel": channel_PLN.slug}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_ORDER_TOTAL, variables, permissions=[permission_manage_orders]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ amount = str(content["data"]["ordersTotal"]["gross"]["amount"])
+ assert Money(amount, channel_PLN.currency_code) == order.total.gross
+
+
+def test_orders_total_not_existing_channel(
+ staff_api_client,
+ permission_manage_orders,
+ order_with_lines,
+ order_with_lines_channel_PLN,
+):
+ # given
+ variables = {"period": ReportingPeriod.TODAY.name, "channel": "not-existing"}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_ORDER_TOTAL, variables, permissions=[permission_manage_orders]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["ordersTotal"]
+
+
+def test_orders_total_as_staff(
+ staff_api_client,
+ permission_manage_orders,
+ order_with_lines,
+ order_with_lines_channel_PLN,
+ channel_USD,
+):
+ # given
+ order = order_with_lines
+ variables = {"period": ReportingPeriod.TODAY.name, "channel": channel_USD.slug}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_ORDER_TOTAL, variables, permissions=[permission_manage_orders]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ amount = str(content["data"]["ordersTotal"]["gross"]["amount"])
+ assert Money(amount, "USD") == order.total.gross
+
+
+def test_orders_total_as_app(
+ app_api_client,
+ permission_manage_orders,
+ order_with_lines,
+ order_with_lines_channel_PLN,
+ channel_USD,
+):
+ # given
+ order = order_with_lines
+ variables = {"period": ReportingPeriod.TODAY.name, "channel": channel_USD.slug}
+
+ # when
+ response = app_api_client.post_graphql(
+ QUERY_ORDER_TOTAL, variables, permissions=[permission_manage_orders]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ amount = str(content["data"]["ordersTotal"]["gross"]["amount"])
+ assert Money(amount, "USD") == order.total.gross
+
+
+def test_orders_total_as_customer(
+ user_api_client, order_with_lines, order_with_lines_channel_PLN, channel_USD,
+):
+ # given
+ variables = {"period": ReportingPeriod.TODAY.name, "channel": channel_USD.slug}
+
+ # when
+ response = user_api_client.post_graphql(QUERY_ORDER_TOTAL, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_orders_total_as_anonymous(
+ api_client, order_with_lines, order_with_lines_channel_PLN, channel_USD,
+):
+ # given
+ variables = {"period": ReportingPeriod.TODAY.name, "channel": channel_USD.slug}
+
+ # when
+ response = api_client.post_graphql(QUERY_ORDER_TOTAL, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+QUERY_ORDER_TODAY_COUNT = """
+query OrdersToday($created: ReportingPeriod, $channel: String) {
+ orders(created: $created, channel: $channel ) {
+ totalCount
+ }
+}
+"""
+
+
+def test_orders_total_count_without_channel(
+ staff_api_client,
+ permission_manage_orders,
+ order_with_lines,
+ order_with_lines_channel_PLN,
+ channel_USD,
+):
+ # given
+ variables = {"created": ReportingPeriod.TODAY.name}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_ORDER_TODAY_COUNT, variables, permissions=[permission_manage_orders]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"]["orders"]["totalCount"] == 2
+
+
+def test_orders_total_count_channel_USD(
+ staff_api_client,
+ permission_manage_orders,
+ order_with_lines,
+ order_with_lines_channel_PLN,
+ channel_USD,
+):
+ # given
+ variables = {"created": ReportingPeriod.TODAY.name, "channel": channel_USD.slug}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_ORDER_TODAY_COUNT, variables, permissions=[permission_manage_orders]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"]["orders"]["totalCount"] == 1
+
+
+def test_orders_total_count_channel_PLN(
+ staff_api_client,
+ permission_manage_orders,
+ order_with_lines,
+ order_with_lines_channel_PLN,
+ channel_PLN,
+):
+ # given
+ variables = {"created": ReportingPeriod.TODAY.name, "channel": channel_PLN.slug}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_ORDER_TODAY_COUNT, variables, permissions=[permission_manage_orders]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"]["orders"]["totalCount"] == 1
+
+
+def test_orders_total_count_as_staff(
+ staff_api_client,
+ permission_manage_orders,
+ order_with_lines,
+ order_with_lines_channel_PLN,
+ channel_USD,
+):
+ # given
+ variables = {"created": ReportingPeriod.TODAY.name, "channel": channel_USD.slug}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_ORDER_TODAY_COUNT, variables, permissions=[permission_manage_orders]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"]["orders"]["totalCount"] == 1
+
+
+def test_orders_total_count_as_app(
+ app_api_client,
+ permission_manage_orders,
+ order_with_lines,
+ order_with_lines_channel_PLN,
+ channel_USD,
+):
+ # given
+ variables = {"created": ReportingPeriod.TODAY.name, "channel": channel_USD.slug}
+
+ # when
+ response = app_api_client.post_graphql(
+ QUERY_ORDER_TODAY_COUNT, variables, permissions=[permission_manage_orders]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"]["orders"]["totalCount"] == 1
+
+
+def test_orders_total_count_as_customer(
+ user_api_client, order_with_lines, order_with_lines_channel_PLN, channel_USD,
+):
+ # given
+ variables = {"created": ReportingPeriod.TODAY.name, "channel": channel_USD.slug}
+
+ # when
+ response = user_api_client.post_graphql(QUERY_ORDER_TODAY_COUNT, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_orders_total_count_as_anonymous(
+ api_client, order_with_lines, order_with_lines_channel_PLN, channel_USD,
+):
+ # given
+ variables = {"created": ReportingPeriod.TODAY.name, "channel": channel_USD.slug}
+
+ # when
+ response = api_client.post_graphql(QUERY_ORDER_TODAY_COUNT, variables)
+
+ # then
+ assert_no_permission(response)
diff --git a/saleor/graphql/order/tests/test_order.py b/saleor/graphql/order/tests/test_order.py
index 23da015575..3061bd27cb 100644
--- a/saleor/graphql/order/tests/test_order.py
+++ b/saleor/graphql/order/tests/test_order.py
@@ -20,7 +20,6 @@ from ....plugins.manager import PluginsManager
from ....shipping.models import ShippingMethod
from ....warehouse.models import Allocation, Stock
from ....warehouse.tests.utils import get_available_quantity_for_stock
-from ...core.enums import ReportingPeriod
from ...order.mutations.orders import (
clean_order_cancel,
clean_order_capture,
@@ -67,20 +66,39 @@ def draft_orders_query_with_filter():
@pytest.fixture
-def orders(customer_user):
+def orders(customer_user, channel_USD, channel_PLN):
return Order.objects.bulk_create(
[
- Order(user=customer_user, status=OrderStatus.CANCELED, token=uuid.uuid4()),
Order(
- user=customer_user, status=OrderStatus.UNFULFILLED, token=uuid.uuid4()
+ user=customer_user,
+ status=OrderStatus.CANCELED,
+ token=uuid.uuid4(),
+ channel=channel_USD,
+ ),
+ Order(
+ user=customer_user,
+ status=OrderStatus.UNFULFILLED,
+ token=uuid.uuid4(),
+ channel=channel_USD,
),
Order(
user=customer_user,
status=OrderStatus.PARTIALLY_FULFILLED,
token=uuid.uuid4(),
+ channel=channel_USD,
+ ),
+ Order(
+ user=customer_user,
+ status=OrderStatus.FULFILLED,
+ token=uuid.uuid4(),
+ channel=channel_PLN,
+ ),
+ Order(
+ user=customer_user,
+ status=OrderStatus.DRAFT,
+ token=uuid.uuid4(),
+ channel=channel_PLN,
),
- Order(user=customer_user, status=OrderStatus.FULFILLED, token=uuid.uuid4()),
- Order(user=customer_user, status=OrderStatus.DRAFT, token=uuid.uuid4()),
]
)
@@ -209,68 +227,77 @@ def test_order_line_with_allocations(
assert allocations_from_query == allocations_from_db
-def test_order_query(
- staff_api_client, permission_manage_orders, fulfilled_order, shipping_zone
-):
- order = fulfilled_order
- query = """
- query OrdersQuery {
- orders(first: 1) {
- edges {
- node {
- number
- canFinalize
- status
- statusDisplay
- paymentStatus
- paymentStatusDisplay
- userEmail
- isPaid
- shippingPrice {
- gross {
- amount
- }
- }
- lines {
- id
- }
- fulfillments {
- fulfillmentOrder
+ORDERS_QUERY = """
+query OrdersQuery {
+ orders(first: 1) {
+ edges {
+ node {
+ number
+ canFinalize
+ status
+ channel {
+ slug
+ }
+ statusDisplay
+ paymentStatus
+ paymentStatusDisplay
+ userEmail
+ isPaid
+ shippingPrice {
+ gross {
+ amount
}
- payments{
- id
+ }
+ lines {
+ id
+ }
+ fulfillments {
+ fulfillmentOrder
+ }
+ payments{
+ id
+ }
+ subtotal {
+ net {
+ amount
}
- subtotal {
- net {
- amount
- }
+ }
+ total {
+ net {
+ amount
}
- total {
- net {
- amount
- }
+ }
+ availableShippingMethods {
+ id
+ price {
+ amount
}
- availableShippingMethods {
- id
- price {
- amount
- }
- minimumOrderPrice {
- amount
- currency
- }
- type
+ minimumOrderPrice {
+ amount
+ currency
}
+ type
+ }
+ shippingMethod{
+ id
}
}
}
}
- """
+}
+"""
+
+
+def test_order_query(
+ staff_api_client, permission_manage_orders, fulfilled_order, shipping_zone
+):
+ order = fulfilled_order
staff_api_client.user.user_permissions.add(permission_manage_orders)
- response = staff_api_client.post_graphql(query)
+ response = staff_api_client.post_graphql(ORDERS_QUERY)
content = get_graphql_content(response)
order_data = content["data"]["orders"]["edges"][0]["node"]
assert order_data["number"] == str(order.pk)
+ assert order_data["channel"]["slug"] == order.channel.slug
assert order_data["canFinalize"] is True
assert order_data["status"] == order.status.upper()
assert order_data["statusDisplay"] == order.get_status_display()
@@ -294,18 +321,103 @@ def test_order_query(
price=order.get_subtotal().gross,
weight=order.get_total_weight(),
country_code=order.shipping_address.country.code,
+ channel_id=order.channel_id,
+ )
+ assert len(order_data["availableShippingMethods"]) == (expected_methods.count())
+
+ method = order_data["availableShippingMethods"][0]
+ expected_method = expected_methods.first()
+ expected_shipping_price = expected_method.channel_listings.get(
+ channel_id=order.channel_id
+ )
+ assert float(expected_shipping_price.price.amount) == method["price"]["amount"]
+ assert float(expected_shipping_price.minimum_order_price.amount) == (
+ method["minimumOrderPrice"]["amount"]
+ )
+ assert expected_method.type.upper() == method["type"]
+
+
+def test_order_query_in_pln_channel(
+ staff_api_client,
+ permission_manage_orders,
+ order_with_lines_channel_PLN,
+ channel_PLN,
+):
+ order = order_with_lines_channel_PLN
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+ response = staff_api_client.post_graphql(ORDERS_QUERY)
+ content = get_graphql_content(response)
+ order_data = content["data"]["orders"]["edges"][0]["node"]
+ assert order_data["number"] == str(order.pk)
+ assert order_data["channel"]["slug"] == order.channel.slug
+ assert order_data["canFinalize"] is True
+ assert order_data["status"] == order.status.upper()
+ assert order_data["statusDisplay"] == order.get_status_display()
+ payment_status = PaymentChargeStatusEnum.get(order.get_payment_status()).name
+ assert order_data["paymentStatus"] == payment_status
+ payment_status_display = order.get_payment_status_display()
+ assert order_data["paymentStatusDisplay"] == payment_status_display
+ assert order_data["isPaid"] == order.is_fully_paid()
+ assert order_data["userEmail"] == order.user_email
+ expected_price = Money(
+ amount=str(order_data["shippingPrice"]["gross"]["amount"]),
+ currency=channel_PLN.currency_code,
+ )
+ assert expected_price == order.shipping_price.gross
+ assert len(order_data["lines"]) == order.lines.count()
+ assert len(order_data["payments"]) == order.payments.count()
+
+ expected_methods = ShippingMethod.objects.applicable_shipping_methods(
+ price=order.get_subtotal().gross,
+ weight=order.get_total_weight(),
+ country_code=order.shipping_address.country.code,
+ channel_id=order.channel_id,
)
assert len(order_data["availableShippingMethods"]) == (expected_methods.count())
method = order_data["availableShippingMethods"][0]
expected_method = expected_methods.first()
- assert float(expected_method.price.amount) == method["price"]["amount"]
- assert float(expected_method.minimum_order_price.amount) == (
+ expected_shipping_price = expected_method.channel_listings.get(
+ channel_id=order.channel_id
+ )
+ assert float(expected_shipping_price.price.amount) == method["price"]["amount"]
+ assert float(expected_shipping_price.minimum_order_price.amount) == (
method["minimumOrderPrice"]["amount"]
)
assert expected_method.type.upper() == method["type"]
+def test_order_query_without_available_shipping_methods(
+ staff_api_client,
+ permission_manage_orders,
+ order,
+ shipping_method_channel_PLN,
+ channel_USD,
+):
+ order.channel = channel_USD
+ order.shipping_method = shipping_method_channel_PLN
+ order.save()
+ query = """
+ query OrdersQuery {
+ orders(first: 1) {
+ edges {
+ node {
+ availableShippingMethods {
+ name
+ }
+ }
+ }
+ }
+ }
+ """
+
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+ response = staff_api_client.post_graphql(query)
+ content = get_graphql_content(response)
+ order_data = content["data"]["orders"]["edges"][0]["node"]
+ assert len(order_data["availableShippingMethods"]) == 0
+
+
@pytest.mark.parametrize(
"expected_price_type, expected_price, display_gross_prices",
(("gross", 13, True), ("net", 10, False)),
@@ -339,6 +451,9 @@ def test_order_available_shipping_methods_query(
}
"""
shipping_method = shipping_zone.shipping_methods.first()
+ shipping_price = shipping_method.channel_listings.get(
+ channel_id=fulfilled_order.channel_id
+ ).price
taxed_price = TaxedMoney(net=Money(10, "USD"), gross=Money(13, "USD"))
apply_taxes_to_shipping_mock = Mock(return_value=taxed_price)
monkeypatch.setattr(
@@ -353,7 +468,7 @@ 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_method.price, ANY)
+ apply_taxes_to_shipping_mock.assert_called_once_with(shipping_price, ANY)
assert expected_price == method["price"]["amount"]
@@ -425,6 +540,49 @@ def test_order_query_draft_excluded(staff_api_client, permission_manage_orders,
assert len(edges) == Order.objects.confirmed().count()
+def test_orders_with_channel(
+ staff_api_client, permission_manage_orders, orders, channel_USD
+):
+ query = """
+ query OrdersQuery($channel: String) {
+ orders(first: 10, channel: $channel) {
+ edges {
+ node {
+ id
+ }
+ }
+ }
+ }
+ """
+
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+ variables = {"channel": channel_USD.slug}
+ response = staff_api_client.post_graphql(query, variables)
+ edges = get_graphql_content(response)["data"]["orders"]["edges"]
+
+ assert len(edges) == 3
+
+
+def test_orders_without_channel(staff_api_client, permission_manage_orders, orders):
+ query = """
+ query OrdersQuery {
+ orders(first: 10) {
+ edges {
+ node {
+ id
+ }
+ }
+ }
+ }
+ """
+
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+ response = staff_api_client.post_graphql(query)
+ edges = get_graphql_content(response)["data"]["orders"]["edges"]
+
+ assert len(edges) == Order.objects.confirmed().count()
+
+
def test_draft_order_query(staff_api_client, permission_manage_orders, orders):
query = """
query DraftOrdersQuery {
@@ -624,42 +782,544 @@ def test_query_order_as_app(app_api_client, permission_manage_orders, order):
DRAFT_ORDER_CREATE_MUTATION = """
-mutation draftCreate(
- $user: ID, $discount: PositiveDecimal, $lines: [OrderLineCreateInput],
- $shippingAddress: AddressInput, $shippingMethod: ID, $voucher: ID,
- $customerNote: String) {
- draftOrderCreate(
- input: {user: $user, discount: $discount,
- lines: $lines, shippingAddress: $shippingAddress,
- shippingMethod: $shippingMethod, voucher: $voucher,
- customerNote: $customerNote}) {
- orderErrors {
- field
- message
- code
- }
- order {
- discount {
- amount
- }
- discountName
- lines {
- productName
- productSku
- quantity
- }
- status
- voucher {
+ mutation draftCreate(
+ $user: ID, $discount: PositiveDecimal, $lines: [OrderLineCreateInput],
+ $shippingAddress: AddressInput, $shippingMethod: ID, $voucher: ID,
+ $customerNote: String, $channel: ID
+ ) {
+ draftOrderCreate(
+ input: {user: $user, discount: $discount,
+ lines: $lines, shippingAddress: $shippingAddress,
+ shippingMethod: $shippingMethod, voucher: $voucher,
+ channel: $channel,
+ customerNote: $customerNote}) {
+ orderErrors {
+ field
code
+ variants
+ message
+ }
+ order {
+ discount {
+ amount
+ }
+ discountName
+ lines {
+ productName
+ productSku
+ quantity
+ }
+ status
+ voucher {
+ code
+ }
+ customerNote
}
- customerNote
}
- }
+ }
+ """
+
+
+def test_draft_order_create(
+ staff_api_client,
+ permission_manage_orders,
+ staff_user,
+ customer_user,
+ product_without_shipping,
+ shipping_method,
+ variant,
+ voucher,
+ channel_USD,
+ graphql_address_data,
+):
+ variant_0 = variant
+ query = DRAFT_ORDER_CREATE_MUTATION
+
+ # Ensure no events were created yet
+ assert not OrderEvent.objects.exists()
+
+ user_id = graphene.Node.to_global_id("User", customer_user.id)
+ variant_0_id = graphene.Node.to_global_id("ProductVariant", variant_0.id)
+ variant_1 = product_without_shipping.variants.first()
+ variant_1.quantity = 2
+ variant_1.save()
+ variant_1_id = graphene.Node.to_global_id("ProductVariant", variant_1.id)
+ discount = "10"
+ customer_note = "Test note"
+ variant_list = [
+ {"variantId": variant_0_id, "quantity": 2},
+ {"variantId": variant_1_id, "quantity": 1},
+ ]
+ shipping_address = graphql_address_data
+ shipping_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
+ voucher_id = graphene.Node.to_global_id("Voucher", voucher.id)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "user": user_id,
+ "discount": discount,
+ "lines": variant_list,
+ "shippingAddress": shipping_address,
+ "shippingMethod": shipping_id,
+ "voucher": voucher_id,
+ "customerNote": customer_note,
+ "channel": channel_id,
+ }
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ assert not content["data"]["draftOrderCreate"]["orderErrors"]
+ data = content["data"]["draftOrderCreate"]["order"]
+ assert data["status"] == OrderStatus.DRAFT.upper()
+ assert data["voucher"]["code"] == voucher.code
+ assert data["customerNote"] == customer_note
+
+ order = Order.objects.first()
+ assert order.user == customer_user
+ # billing address should be copied
+ assert order.billing_address.pk != customer_user.default_billing_address.pk
+ assert (
+ order.billing_address.as_data()
+ == customer_user.default_billing_address.as_data()
+ )
+ assert order.shipping_method == shipping_method
+ assert order.shipping_address.first_name == graphql_address_data["firstName"]
+
+ # Ensure the correct event was created
+ created_draft_event = OrderEvent.objects.get(
+ type=order_events.OrderEvents.DRAFT_CREATED
+ )
+ assert created_draft_event.user == staff_user
+ assert created_draft_event.parameters == {}
+
+
+def test_draft_order_create_with_inactive_channel(
+ staff_api_client,
+ permission_manage_orders,
+ staff_user,
+ customer_user,
+ product_without_shipping,
+ shipping_method,
+ variant,
+ voucher,
+ channel_USD,
+ graphql_address_data,
+):
+ variant_0 = variant
+ query = DRAFT_ORDER_CREATE_MUTATION
+
+ # Ensure no events were created yet
+ assert not OrderEvent.objects.exists()
+
+ user_id = graphene.Node.to_global_id("User", customer_user.id)
+ channel_USD.is_active = False
+ channel_USD.save()
+ variant_0_id = graphene.Node.to_global_id("ProductVariant", variant_0.id)
+ variant_1 = product_without_shipping.variants.first()
+ variant_1.quantity = 2
+ variant_1.save()
+ variant_1_id = graphene.Node.to_global_id("ProductVariant", variant_1.id)
+ discount = "10"
+ customer_note = "Test note"
+ variant_list = [
+ {"variantId": variant_0_id, "quantity": 2},
+ {"variantId": variant_1_id, "quantity": 1},
+ ]
+ shipping_address = graphql_address_data
+ shipping_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
+ voucher_id = graphene.Node.to_global_id("Voucher", voucher.id)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "user": user_id,
+ "discount": discount,
+ "lines": variant_list,
+ "shippingAddress": shipping_address,
+ "shippingMethod": shipping_id,
+ "voucher": voucher_id,
+ "customerNote": customer_note,
+ "channel": channel_id,
+ }
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ assert not content["data"]["draftOrderCreate"]["orderErrors"]
+ data = content["data"]["draftOrderCreate"]["order"]
+ assert data["status"] == OrderStatus.DRAFT.upper()
+ assert data["voucher"]["code"] == voucher.code
+ assert data["customerNote"] == customer_note
+
+ order = Order.objects.first()
+ assert order.user == customer_user
+ # billing address should be copied
+ assert order.billing_address.pk != customer_user.default_billing_address.pk
+ assert (
+ order.billing_address.as_data()
+ == customer_user.default_billing_address.as_data()
+ )
+ assert order.shipping_method == shipping_method
+ assert order.shipping_address.first_name == graphql_address_data["firstName"]
+
+ # Ensure the correct event was created
+ created_draft_event = OrderEvent.objects.get(
+ type=order_events.OrderEvents.DRAFT_CREATED
+ )
+ assert created_draft_event.user == staff_user
+ assert created_draft_event.parameters == {}
+
+
+def test_draft_order_create_variant_with_0_price(
+ staff_api_client,
+ permission_manage_orders,
+ staff_user,
+ customer_user,
+ product_without_shipping,
+ shipping_method,
+ variant,
+ voucher,
+ graphql_address_data,
+ channel_USD,
+):
+ variant_0 = variant
+ query = DRAFT_ORDER_CREATE_MUTATION
+ # Ensure no events were created yet
+ assert not OrderEvent.objects.exists()
+
+ user_id = graphene.Node.to_global_id("User", customer_user.id)
+ variant_0_id = graphene.Node.to_global_id("ProductVariant", variant_0.id)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variant_1 = product_without_shipping.variants.first()
+ variant_1.quantity = 2
+ variant.price = Money(0, "USD")
+ variant_1.save()
+ variant_1_id = graphene.Node.to_global_id("ProductVariant", variant_1.id)
+ variant_list = [
+ {"variantId": variant_0_id, "quantity": 2},
+ {"variantId": variant_1_id, "quantity": 1},
+ ]
+ shipping_address = graphql_address_data
+ shipping_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
+ variables = {
+ "user": user_id,
+ "lines": variant_list,
+ "shippingAddress": shipping_address,
+ "shippingMethod": shipping_id,
+ "channel": channel_id,
+ }
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ assert not content["data"]["draftOrderCreate"]["orderErrors"]
+ data = content["data"]["draftOrderCreate"]["order"]
+ assert data["status"] == OrderStatus.DRAFT.upper()
+
+ order = Order.objects.first()
+ assert order.user == customer_user
+ # billing address should be copied
+ assert order.billing_address.pk != customer_user.default_billing_address.pk
+ assert (
+ order.billing_address.as_data()
+ == customer_user.default_billing_address.as_data()
+ )
+ assert order.shipping_method == shipping_method
+ assert order.shipping_address.first_name == graphql_address_data["firstName"]
+
+ # Ensure the correct event was created
+ created_draft_event = OrderEvent.objects.get(
+ type=order_events.OrderEvents.DRAFT_CREATED
+ )
+ assert created_draft_event.user == staff_user
+ assert created_draft_event.parameters == {}
+
+
+@patch("saleor.graphql.order.mutations.draft_orders.add_variant_to_draft_order")
+def test_draft_order_create_tax_error(
+ add_variant_to_draft_order_mock,
+ staff_api_client,
+ permission_manage_orders,
+ staff_user,
+ customer_user,
+ product_without_shipping,
+ shipping_method,
+ variant,
+ voucher,
+ graphql_address_data,
+ channel_USD,
+):
+ variant_0 = variant
+ err_msg = "Test error"
+ add_variant_to_draft_order_mock.side_effect = TaxError(err_msg)
+ query = DRAFT_ORDER_CREATE_MUTATION
+ # Ensure no events were created yet
+ assert not OrderEvent.objects.exists()
+
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ user_id = graphene.Node.to_global_id("User", customer_user.id)
+ variant_0_id = graphene.Node.to_global_id("ProductVariant", variant_0.id)
+ variant_1 = product_without_shipping.variants.first()
+ variant_1.quantity = 2
+ variant_1.save()
+ variant_1_id = graphene.Node.to_global_id("ProductVariant", variant_1.id)
+ discount = "10"
+ customer_note = "Test note"
+ variant_list = [
+ {"variantId": variant_0_id, "quantity": 2},
+ {"variantId": variant_1_id, "quantity": 1},
+ ]
+ shipping_address = graphql_address_data
+ shipping_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
+ voucher_id = graphene.Node.to_global_id("Voucher", voucher.id)
+ variables = {
+ "user": user_id,
+ "discount": discount,
+ "lines": variant_list,
+ "shippingAddress": shipping_address,
+ "shippingMethod": shipping_id,
+ "voucher": voucher_id,
+ "customerNote": customer_note,
+ "channel": channel_id,
+ }
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["draftOrderCreate"]
+ errors = data["orderErrors"]
+ assert not data["order"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == OrderErrorCode.TAX_ERROR.name
+ assert errors[0]["message"] == f"Unable to calculate taxes - {err_msg}"
+
+ order_count = Order.objects.all().count()
+ assert order_count == 0
+
+
+def test_draft_order_create_with_voucher_not_assigned_to_order_channel(
+ staff_api_client,
+ permission_manage_orders,
+ staff_user,
+ customer_user,
+ shipping_method,
+ variant,
+ voucher,
+ channel_USD,
+ graphql_address_data,
+):
+ query = DRAFT_ORDER_CREATE_MUTATION
+
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ user_id = graphene.Node.to_global_id("User", customer_user.id)
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ discount = "10"
+ customer_note = "Test note"
+ variant_list = [
+ {"variantId": variant_id, "quantity": 2},
+ ]
+ shipping_address = graphql_address_data
+ shipping_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
+ voucher_id = graphene.Node.to_global_id("Voucher", voucher.id)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ voucher.channel_listings.all().delete()
+ variables = {
+ "user": user_id,
+ "discount": discount,
+ "lines": variant_list,
+ "shippingAddress": shipping_address,
+ "shippingMethod": shipping_id,
+ "voucher": voucher_id,
+ "customerNote": customer_note,
+ "channel": channel_id,
+ }
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ error = content["data"]["draftOrderCreate"]["orderErrors"][0]
+ assert error["code"] == OrderErrorCode.NOT_AVAILABLE_IN_CHANNEL.name
+ assert error["field"] == "voucher"
+
+
+def test_draft_order_create_with_product_and_variant_not_assigned_to_order_channel(
+ staff_api_client,
+ permission_manage_orders,
+ customer_user,
+ shipping_method,
+ variant,
+ channel_USD,
+ graphql_address_data,
+):
+ query = DRAFT_ORDER_CREATE_MUTATION
+ user_id = graphene.Node.to_global_id("User", customer_user.id)
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ discount = "10"
+ customer_note = "Test note"
+ variant_list = [
+ {"variantId": variant_id, "quantity": 2},
+ ]
+ shipping_address = graphql_address_data
+ shipping_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variant.product.channel_listings.all().delete()
+ variant.channel_listings.all().delete()
+ variables = {
+ "user": user_id,
+ "discount": discount,
+ "lines": variant_list,
+ "shippingAddress": shipping_address,
+ "shippingMethod": shipping_id,
+ "customerNote": customer_note,
+ "channel": channel_id,
+ }
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ error = content["data"]["draftOrderCreate"]["orderErrors"][0]
+ assert error["code"] == OrderErrorCode.PRODUCT_NOT_PUBLISHED.name
+ assert error["field"] == "lines"
+ assert error["variants"] == [variant_id]
+
+
+def test_draft_order_create_with_variant_not_assigned_to_order_channel(
+ staff_api_client,
+ permission_manage_orders,
+ customer_user,
+ shipping_method,
+ variant,
+ channel_USD,
+ graphql_address_data,
+):
+ query = DRAFT_ORDER_CREATE_MUTATION
+
+ user_id = graphene.Node.to_global_id("User", customer_user.id)
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ discount = "10"
+ customer_note = "Test note"
+ variant_list = [
+ {"variantId": variant_id, "quantity": 2},
+ ]
+ shipping_address = graphql_address_data
+ shipping_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variant.channel_listings.all().delete()
+ variables = {
+ "user": user_id,
+ "discount": discount,
+ "lines": variant_list,
+ "shippingAddress": shipping_address,
+ "shippingMethod": shipping_id,
+ "customerNote": customer_note,
+ "channel": channel_id,
+ }
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ error = content["data"]["draftOrderCreate"]["orderErrors"][0]
+ assert error["code"] == OrderErrorCode.NOT_AVAILABLE_IN_CHANNEL.name
+ assert error["field"] == "lines"
+ assert error["variants"] == [variant_id]
+
+
+def test_draft_order_create_without_channel(
+ staff_api_client,
+ permission_manage_orders,
+ staff_user,
+ customer_user,
+ product_without_shipping,
+ shipping_method,
+ variant,
+ voucher,
+ graphql_address_data,
+):
+ variant_0 = variant
+ query = DRAFT_ORDER_CREATE_MUTATION
+
+ user_id = graphene.Node.to_global_id("User", customer_user.id)
+ variant_0_id = graphene.Node.to_global_id("ProductVariant", variant_0.id)
+ variant_1 = product_without_shipping.variants.first()
+ variant_1.quantity = 2
+ variant_1.save()
+ variant_1_id = graphene.Node.to_global_id("ProductVariant", variant_1.id)
+ variant_list = [
+ {"variantId": variant_0_id, "quantity": 2},
+ {"variantId": variant_1_id, "quantity": 1},
+ ]
+ variables = {
+ "user": user_id,
+ "lines": variant_list,
+ }
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ error = content["data"]["draftOrderCreate"]["orderErrors"][0]
+ assert error["code"] == OrderErrorCode.REQUIRED.name
+ assert error["field"] == "channel"
+
+
+def test_draft_order_create_with_channel_with_unpublished_product(
+ staff_api_client,
+ permission_manage_orders,
+ staff_user,
+ customer_user,
+ product_without_shipping,
+ shipping_method,
+ variant,
+ voucher,
+ graphql_address_data,
+ channel_USD,
+):
+ variant_0 = variant
+ query = DRAFT_ORDER_CREATE_MUTATION
+
+ # Ensure no events were created yet
+ assert not OrderEvent.objects.exists()
+
+ user_id = graphene.Node.to_global_id("User", customer_user.id)
+ variant_0_id = graphene.Node.to_global_id("ProductVariant", variant_0.id)
+ variant_1 = product_without_shipping.variants.first()
+ channel_listing = variant_1.product.channel_listings.get()
+ channel_listing.is_published = False
+ channel_listing.save()
+
+ variant_1.quantity = 2
+ variant_1.save()
+ variant_1_id = graphene.Node.to_global_id("ProductVariant", variant_1.id)
+ discount = "10"
+ customer_note = "Test note"
+ variant_list = [
+ {"variantId": variant_0_id, "quantity": 2},
+ {"variantId": variant_1_id, "quantity": 1},
+ ]
+ shipping_address = graphql_address_data
+ shipping_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ voucher_id = graphene.Node.to_global_id("Voucher", voucher.id)
+ variables = {
+ "user": user_id,
+ "discount": discount,
+ "channel": channel_id,
+ "lines": variant_list,
+ "shippingAddress": shipping_address,
+ "shippingMethod": shipping_id,
+ "voucher": voucher_id,
+ "customerNote": customer_note,
}
-"""
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ error = content["data"]["draftOrderCreate"]["orderErrors"][0]
-def test_draft_order_create(
+ assert error["field"] == "lines"
+ assert error["code"] == OrderErrorCode.PRODUCT_NOT_PUBLISHED.name
+ assert error["variants"] == [variant_1_id]
+
+
+def test_draft_order_create_with_channel_with_unpublished_product_by_date(
staff_api_client,
permission_manage_orders,
staff_user,
@@ -669,15 +1329,21 @@ def test_draft_order_create(
variant,
voucher,
graphql_address_data,
+ channel_USD,
):
variant_0 = variant
query = DRAFT_ORDER_CREATE_MUTATION
+
# Ensure no events were created yet
assert not OrderEvent.objects.exists()
-
+ next_day = date.today() + timedelta(days=1)
user_id = graphene.Node.to_global_id("User", customer_user.id)
variant_0_id = graphene.Node.to_global_id("ProductVariant", variant_0.id)
variant_1 = product_without_shipping.variants.first()
+ channel_listing = variant_1.product.channel_listings.get()
+ channel_listing.publication_date = next_day
+ channel_listing.save()
+
variant_1.quantity = 2
variant_1.save()
variant_1_id = graphene.Node.to_global_id("ProductVariant", variant_1.id)
@@ -689,46 +1355,31 @@ def test_draft_order_create(
]
shipping_address = graphql_address_data
shipping_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
voucher_id = graphene.Node.to_global_id("Voucher", voucher.id)
variables = {
"user": user_id,
"discount": discount,
+ "channel": channel_id,
"lines": variant_list,
"shippingAddress": shipping_address,
"shippingMethod": shipping_id,
"voucher": voucher_id,
"customerNote": customer_note,
}
+
response = staff_api_client.post_graphql(
query, variables, permissions=[permission_manage_orders]
)
content = get_graphql_content(response)
- assert not content["data"]["draftOrderCreate"]["orderErrors"]
- data = content["data"]["draftOrderCreate"]["order"]
- assert data["status"] == OrderStatus.DRAFT.upper()
- assert data["voucher"]["code"] == voucher.code
- assert data["customerNote"] == customer_note
-
- order = Order.objects.first()
- assert order.user == customer_user
- # billing address should be copied
- assert order.billing_address.pk != customer_user.default_billing_address.pk
- assert (
- order.billing_address.as_data()
- == customer_user.default_billing_address.as_data()
- )
- assert order.shipping_method == shipping_method
- assert order.shipping_address.first_name == graphql_address_data["firstName"]
+ error = content["data"]["draftOrderCreate"]["orderErrors"][0]
- # Ensure the correct event was created
- created_draft_event = OrderEvent.objects.get(
- type=order_events.OrderEvents.DRAFT_CREATED
- )
- assert created_draft_event.user == staff_user
- assert created_draft_event.parameters == {}
+ assert error["field"] == "lines"
+ assert error["code"] == "PRODUCT_NOT_PUBLISHED"
+ assert error["variants"] == [variant_1_id]
-def test_draft_order_create_variant_with_0_price(
+def test_draft_order_create_with_channel(
staff_api_client,
permission_manage_orders,
staff_user,
@@ -738,30 +1389,40 @@ def test_draft_order_create_variant_with_0_price(
variant,
voucher,
graphql_address_data,
+ channel_USD,
):
variant_0 = variant
query = DRAFT_ORDER_CREATE_MUTATION
+
# Ensure no events were created yet
assert not OrderEvent.objects.exists()
user_id = graphene.Node.to_global_id("User", customer_user.id)
variant_0_id = graphene.Node.to_global_id("ProductVariant", variant_0.id)
variant_1 = product_without_shipping.variants.first()
+
variant_1.quantity = 2
- variant.price = Money(0, "USD")
variant_1.save()
variant_1_id = graphene.Node.to_global_id("ProductVariant", variant_1.id)
+ discount = "10"
+ customer_note = "Test note"
variant_list = [
{"variantId": variant_0_id, "quantity": 2},
{"variantId": variant_1_id, "quantity": 1},
]
shipping_address = graphql_address_data
shipping_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ voucher_id = graphene.Node.to_global_id("Voucher", voucher.id)
variables = {
"user": user_id,
+ "discount": discount,
+ "channel": channel_id,
"lines": variant_list,
"shippingAddress": shipping_address,
"shippingMethod": shipping_id,
+ "voucher": voucher_id,
+ "customerNote": customer_note,
}
response = staff_api_client.post_graphql(
query, variables, permissions=[permission_manage_orders]
@@ -770,9 +1431,12 @@ def test_draft_order_create_variant_with_0_price(
assert not content["data"]["draftOrderCreate"]["orderErrors"]
data = content["data"]["draftOrderCreate"]["order"]
assert data["status"] == OrderStatus.DRAFT.upper()
+ assert data["voucher"]["code"] == voucher.code
+ assert data["customerNote"] == customer_note
order = Order.objects.first()
assert order.user == customer_user
+ assert order.channel.id == channel_USD.id
# billing address should be copied
assert order.billing_address.pk != customer_user.default_billing_address.pk
assert (
@@ -790,63 +1454,84 @@ def test_draft_order_create_variant_with_0_price(
assert created_draft_event.parameters == {}
-@patch("saleor.graphql.order.mutations.draft_orders.add_variant_to_draft_order")
-def test_draft_order_create_tax_error(
- add_variant_to_draft_order_mock,
- staff_api_client,
- permission_manage_orders,
- staff_user,
- customer_user,
- product_without_shipping,
- shipping_method,
- variant,
- voucher,
- graphql_address_data,
+DRAFT_UPDATE_QUERY = """
+ mutation draftUpdate(
+ $id: ID!,
+ $voucher: ID,
+ $channel: ID,
+ $customerNote: String
+ ) {
+ draftOrderUpdate(
+ id: $id,
+ input: {
+ voucher: $voucher,
+ customerNote: $customerNote
+ channel: $channel
+ }) {
+ orderErrors {
+ field
+ code
+ message
+ }
+ order {
+ userEmail
+ channel {
+ id
+ }
+ }
+ }
+ }
+ """
+
+
+def test_draft_order_update_existing_channel_id(
+ staff_api_client, permission_manage_orders, order_with_lines, channel_PLN
):
- variant_0 = variant
- err_msg = "Test error"
- add_variant_to_draft_order_mock.side_effect = TaxError(err_msg)
- query = DRAFT_ORDER_CREATE_MUTATION
- # Ensure no events were created yet
- assert not OrderEvent.objects.exists()
+ order = order_with_lines
+ order.status = OrderStatus.DRAFT
+ order.save()
+ query = DRAFT_UPDATE_QUERY
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ variables = {
+ "id": order_id,
+ "channel": channel_id,
+ }
- user_id = graphene.Node.to_global_id("User", customer_user.id)
- variant_0_id = graphene.Node.to_global_id("ProductVariant", variant_0.id)
- variant_1 = product_without_shipping.variants.first()
- variant_1.quantity = 2
- variant_1.save()
- variant_1_id = graphene.Node.to_global_id("ProductVariant", variant_1.id)
- discount = "10"
- customer_note = "Test note"
- variant_list = [
- {"variantId": variant_0_id, "quantity": 2},
- {"variantId": variant_1_id, "quantity": 1},
- ]
- shipping_address = graphql_address_data
- shipping_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ error = content["data"]["draftOrderUpdate"]["orderErrors"][0]
+
+ assert error["code"] == OrderErrorCode.NOT_EDITABLE.name
+ assert error["field"] == "channel"
+
+
+def test_draft_order_update_voucher_not_available(
+ staff_api_client, permission_manage_orders, order_with_lines, voucher
+):
+ order = order_with_lines
+ order.status = OrderStatus.DRAFT
+ order.save()
+ assert order.voucher is None
+ query = DRAFT_UPDATE_QUERY
+ order_id = graphene.Node.to_global_id("Order", order.id)
voucher_id = graphene.Node.to_global_id("Voucher", voucher.id)
+ voucher.channel_listings.all().delete()
variables = {
- "user": user_id,
- "discount": discount,
- "lines": variant_list,
- "shippingAddress": shipping_address,
- "shippingMethod": shipping_id,
+ "id": order_id,
"voucher": voucher_id,
- "customerNote": customer_note,
}
+
response = staff_api_client.post_graphql(
query, variables, permissions=[permission_manage_orders]
)
content = get_graphql_content(response)
- data = content["data"]["draftOrderCreate"]
- errors = data["orderErrors"]
- assert not data["order"]
- assert len(errors) == 1
- assert errors[0]["code"] == OrderErrorCode.TAX_ERROR.name
- assert errors[0]["message"] == f"Unable to calculate taxes - {err_msg}"
+ error = content["data"]["draftOrderUpdate"]["orderErrors"][0]
- order_count = Order.objects.all().count()
- assert order_count == 0
+ assert error["code"] == OrderErrorCode.NOT_AVAILABLE_IN_CHANNEL.name
+ assert error["field"] == "voucher"
DRAFT_ORDER_UPDATE_MUTATION = """
@@ -882,7 +1567,12 @@ def test_draft_order_update(
order_id = graphene.Node.to_global_id("Order", order.id)
voucher_id = graphene.Node.to_global_id("Voucher", voucher.id)
customer_note = "Test customer note"
- variables = {"id": order_id, "voucher": voucher_id, "customerNote": customer_note}
+ variables = {
+ "id": order_id,
+ "voucher": voucher_id,
+ "customerNote": customer_note,
+ }
+
response = staff_api_client.post_graphql(
query, variables, permissions=[permission_manage_orders]
)
@@ -1039,8 +1729,33 @@ def test_can_finalize_order_product_unavailable_for_purchase(
order.save(update_fields=["status"])
product = order.lines.first().variant.product
- product.available_for_purchase = date.today() + timedelta(days=1)
- product.save(update_fields=["available_for_purchase"])
+ product.channel_listings.update(available_for_purchase=None)
+
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variables = {"id": order_id}
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_CAN_FINALIZE_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"]["order"]["canFinalize"] is False
+
+
+def test_can_finalize_order_product_available_for_purchase_from_tomorrow(
+ staff_api_client, permission_manage_orders, draft_order
+):
+ # given
+ order = draft_order
+
+ order.status = OrderStatus.DRAFT
+ order.save(update_fields=["status"])
+
+ product = order.lines.first().variant.product
+ product.channel_listings.update(
+ available_for_purchase=date.today() + timedelta(days=1)
+ )
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id}
@@ -1097,8 +1812,9 @@ def test_validate_draft_order_with_unpublished_product(draft_order):
order = draft_order
line = order.lines.first()
variant = line.variant
- variant.product.is_published = False
- variant.product.save()
+ product_channel_listing = variant.product.channel_listings.get()
+ product_channel_listing.is_published = False
+ product_channel_listing.save(update_fields=["is_published"])
line.refresh_from_db()
with pytest.raises(ValidationError) as e:
@@ -1114,8 +1830,7 @@ def test_validate_draft_order_with_unavailable_for_purchase_product(draft_order)
order = draft_order
line = order.lines.first()
variant = line.variant
- variant.product.available_for_purchase = None
- variant.product.save(update_fields=["available_for_purchase"])
+ variant.product.channel_listings.update(available_for_purchase=None)
line.refresh_from_db()
with pytest.raises(ValidationError) as e:
@@ -1133,8 +1848,9 @@ def test_validate_draft_order_with_product_available_for_purchase_in_future(
order = draft_order
line = order.lines.first()
variant = line.variant
- variant.product.available_for_purchase = date.today() + timedelta(days=2)
- variant.product.save(update_fields=["available_for_purchase"])
+ variant.product.channel_listings.update(
+ available_for_purchase=date.today() + timedelta(days=2)
+ )
line.refresh_from_db()
with pytest.raises(ValidationError) as e:
@@ -1157,7 +1873,7 @@ def test_validate_draft_order_out_of_stock_variant(draft_order):
with pytest.raises(ValidationError) as e:
validate_draft_order(order, "US")
- msg = "Insufficient product stock: SKU_A"
+ msg = "Insufficient product stock: SKU_AA"
assert e.value.error_dict["lines"][0].message == msg
@@ -1261,6 +1977,25 @@ def test_draft_order_complete(
assert draft_placed_event.parameters == {}
+def test_draft_order_complete_with_inactive_channel(
+ staff_api_client, permission_manage_orders, staff_user, draft_order,
+):
+ order = draft_order
+ channel = order.channel
+ channel.is_active = False
+ channel.save()
+
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variables = {"id": order_id}
+ response = staff_api_client.post_graphql(
+ DRAFT_ORDER_COMPLETE_MUTATION, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["draftOrderComplete"]
+ assert data["orderErrors"][0]["code"] == OrderErrorCode.CHANNEL_INACTIVE.name
+ assert data["orderErrors"][0]["field"] == "channel"
+
+
def test_draft_order_complete_product_without_inventory_tracking(
staff_api_client,
shipping_method,
@@ -1411,8 +2146,9 @@ def test_draft_order_complete_unavailable_for_purchase(
assert not OrderEvent.objects.exists()
product = order.lines.first().variant.product
- product.available_for_purchase = date.today() + timedelta(days=5)
- product.save(update_fields=["available_for_purchase"])
+ product.channel_listings.update(
+ available_for_purchase=date.today() + timedelta(days=5)
+ )
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id}
@@ -1437,9 +2173,11 @@ DRAFT_ORDER_LINES_CREATE_MUTATION = """
draftOrderLinesCreate(id: $orderId,
input: [{variantId: $variantId, quantity: $quantity}]) {
- errors {
+ orderErrors {
field
+ code
message
+ variants
}
orderLines {
id
@@ -1488,8 +2226,60 @@ def test_draft_order_lines_create(
response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["draftOrderLinesCreate"]
- assert data["errors"]
- assert data["errors"][0]["field"] == "quantity"
+ assert data["orderErrors"]
+ assert data["orderErrors"][0]["field"] == "quantity"
+
+
+def test_draft_order_lines_create_with_product_and_variant_not_assigned_to_channel(
+ draft_order, permission_manage_orders, staff_api_client, variant
+):
+ query = DRAFT_ORDER_LINES_CREATE_MUTATION
+ order = draft_order
+ line = order.lines.first()
+ assert variant != line.variant
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ variables = {"orderId": order_id, "variantId": variant_id, "quantity": 1}
+ variant.product.channel_listings.all().delete()
+ variant.channel_listings.all().delete()
+
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ error = content["data"]["draftOrderLinesCreate"]["orderErrors"][0]
+ assert error["code"] == OrderErrorCode.PRODUCT_NOT_PUBLISHED.name
+ assert error["field"] == "input"
+ assert error["variants"] == [variant_id]
+
+
+def test_draft_order_lines_create_with_variant_not_assigned_to_channel(
+ draft_order,
+ staff_api_client,
+ permission_manage_orders,
+ customer_user,
+ shipping_method,
+ variant,
+ channel_USD,
+ graphql_address_data,
+):
+ query = DRAFT_ORDER_LINES_CREATE_MUTATION
+ order = draft_order
+ line = order.lines.first()
+ assert variant != line.variant
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ variables = {"orderId": order_id, "variantId": variant_id, "quantity": 1}
+ variant.channel_listings.all().delete()
+
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ error = content["data"]["draftOrderLinesCreate"]["orderErrors"][0]
+ assert error["code"] == OrderErrorCode.NOT_AVAILABLE_IN_CHANNEL.name
+ assert error["field"] == "input"
+ assert error["variants"] == [variant_id]
def test_require_draft_order_when_creating_lines(
@@ -1507,7 +2297,7 @@ def test_require_draft_order_when_creating_lines(
)
content = get_graphql_content(response)
data = content["data"]["draftOrderLinesCreate"]
- assert data["errors"]
+ assert data["orderErrors"]
DRAFT_ORDER_LINE_UPDATE_MUTATION = """
@@ -2438,7 +3228,9 @@ def test_order_update_shipping(
assert data["order"]["id"] == order_id
order.refresh_from_db()
- shipping_total = shipping_method.get_total()
+ shipping_total = shipping_method.channel_listings.get(
+ channel_id=order.channel_id
+ ).get_total()
shipping_price = TaxedMoney(shipping_total, shipping_total)
assert order.status == OrderStatus.UNFULFILLED
assert order.shipping_method == shipping_method
@@ -2451,7 +3243,10 @@ def test_order_update_shipping_clear_shipping_method(
staff_api_client, permission_manage_orders, order, staff_user, shipping_method
):
order.shipping_method = shipping_method
- shipping_total = shipping_method.get_total()
+ shipping_total = shipping_method.channel_listings.get(
+ channel_id=order.channel_id,
+ ).get_total()
+
shipping_price = TaxedMoney(shipping_total, shipping_total)
order.shipping_price = shipping_price
order.shipping_method_name = "Example shipping"
@@ -2469,7 +3264,7 @@ def test_order_update_shipping_clear_shipping_method(
order.refresh_from_db()
assert order.shipping_method is None
- assert order.shipping_price == zero_taxed_money()
+ assert order.shipping_price == zero_taxed_money(order.currency)
assert order.shipping_method_name is None
@@ -2558,34 +3353,10 @@ def test_draft_order_clear_shipping_method(
assert data["order"]["id"] == order_id
draft_order.refresh_from_db()
assert draft_order.shipping_method is None
- assert draft_order.shipping_price == zero_taxed_money()
+ assert draft_order.shipping_price == zero_taxed_money(draft_order.currency)
assert draft_order.shipping_method_name is None
-def test_orders_total(staff_api_client, permission_manage_orders, order_with_lines):
- query = """
- query Orders($period: ReportingPeriod) {
- ordersTotal(period: $period) {
- gross {
- amount
- currency
- }
- net {
- currency
- amount
- }
- }
- }
- """
- variables = {"period": ReportingPeriod.TODAY.name}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_orders]
- )
- content = get_graphql_content(response)
- amount = str(content["data"]["ordersTotal"]["gross"]["amount"])
- assert Money(amount, "USD") == order_with_lines.total.gross
-
-
ORDER_BY_TOKEN_QUERY = """
query OrderByToken($token: UUID!) {
orderByToken(token: $token) {
@@ -3101,7 +3872,7 @@ def test_order_bulk_cancel_as_app(
calls = [call(order=order, user=AnonymousUser()) for order in orders]
mock_cancel_order.assert_has_calls(calls, any_order=True)
- mock_cancel_order.call_count == expected_count
+ assert mock_cancel_order.call_count == expected_count
@pytest.mark.parametrize(
@@ -3128,10 +3899,11 @@ def test_order_query_with_filter_created(
orders_query_with_filter,
staff_api_client,
permission_manage_orders,
+ channel_USD,
):
- Order.objects.create()
+ Order.objects.create(channel=channel_USD)
with freeze_time("2012-01-14"):
- Order.objects.create()
+ Order.objects.create(channel=channel_USD)
variables = {"filter": orders_filter}
staff_api_client.user.user_permissions.add(permission_manage_orders)
response = staff_api_client.post_graphql(orders_query_with_filter, variables)
@@ -3161,12 +3933,13 @@ def test_order_query_with_filter_payment_status(
staff_api_client,
payment_dummy,
permission_manage_orders,
+ channel_PLN,
):
payment_dummy.charge_status = payment_status
payment_dummy.save()
payment_dummy.id = None
- payment_dummy.order = Order.objects.create()
+ payment_dummy.order = Order.objects.create(channel=channel_PLN)
payment_dummy.charge_status = ChargeStatus.NOT_CHARGED
payment_dummy.save()
@@ -3197,11 +3970,12 @@ def test_order_query_with_filter_status(
payment_dummy,
permission_manage_orders,
order,
+ channel_USD,
):
order.status = status
order.save()
- Order.objects.create()
+ Order.objects.create(channel=channel_USD)
variables = {"filter": orders_filter}
staff_api_client.user.user_permissions.add(permission_manage_orders)
@@ -3231,13 +4005,16 @@ def test_order_query_with_filter_customer_fields(
staff_api_client,
permission_manage_orders,
customer_user,
+ channel_USD,
):
setattr(customer_user, user_field, user_value)
customer_user.save()
customer_user.refresh_from_db()
- order = Order(user=customer_user, token=str(uuid.uuid4()))
- Order.objects.bulk_create([order, Order(token=str(uuid.uuid4()))])
+ order = Order(user=customer_user, token=str(uuid.uuid4()), channel=channel_USD)
+ Order.objects.bulk_create(
+ [order, Order(token=str(uuid.uuid4()), channel=channel_USD)]
+ )
variables = {"filter": orders_filter}
staff_api_client.user.user_permissions.add(permission_manage_orders)
@@ -3266,14 +4043,25 @@ def test_draft_order_query_with_filter_customer_fields(
staff_api_client,
permission_manage_orders,
customer_user,
+ channel_USD,
):
setattr(customer_user, user_field, user_value)
customer_user.save()
customer_user.refresh_from_db()
- order = Order(status=OrderStatus.DRAFT, user=customer_user, token=str(uuid.uuid4()))
+ order = Order(
+ status=OrderStatus.DRAFT,
+ user=customer_user,
+ token=str(uuid.uuid4()),
+ channel=channel_USD,
+ )
Order.objects.bulk_create(
- [order, Order(token=str(uuid.uuid4()), status=OrderStatus.DRAFT)]
+ [
+ order,
+ Order(
+ token=str(uuid.uuid4()), status=OrderStatus.DRAFT, channel=channel_USD
+ ),
+ ]
)
variables = {"filter": orders_filter}
@@ -3311,10 +4099,11 @@ def test_draft_order_query_with_filter_created_(
draft_orders_query_with_filter,
staff_api_client,
permission_manage_orders,
+ channel_USD,
):
- Order.objects.create(status=OrderStatus.DRAFT)
+ Order.objects.create(status=OrderStatus.DRAFT, channel=channel_USD)
with freeze_time("2012-01-14"):
- Order.objects.create(status=OrderStatus.DRAFT)
+ Order.objects.create(status=OrderStatus.DRAFT, channel=channel_USD)
variables = {"filter": orders_filter}
staff_api_client.user.user_permissions.add(permission_manage_orders)
response = staff_api_client.post_graphql(draft_orders_query_with_filter, variables)
@@ -3348,12 +4137,15 @@ QUERY_ORDER_WITH_SORT = """
({"field": "CUSTOMER", "direction": "DESC"}, [1, 0, 2]),
({"field": "FULFILLMENT_STATUS", "direction": "ASC"}, [2, 1, 0]),
({"field": "FULFILLMENT_STATUS", "direction": "DESC"}, [0, 1, 2]),
- ({"field": "TOTAL", "direction": "ASC"}, [0, 2, 1]),
- ({"field": "TOTAL", "direction": "DESC"}, [1, 2, 0]),
],
)
def test_query_orders_with_sort(
- order_sort, result_order, staff_api_client, permission_manage_orders, address
+ order_sort,
+ result_order,
+ staff_api_client,
+ permission_manage_orders,
+ address,
+ channel_USD,
):
created_orders = []
with freeze_time("2017-01-14"):
@@ -3363,6 +4155,7 @@ def test_query_orders_with_sort(
billing_address=address,
status=OrderStatus.PARTIALLY_FULFILLED,
total=TaxedMoney(net=Money(10, "USD"), gross=Money(13, "USD")),
+ channel=channel_USD,
)
)
with freeze_time("2012-01-14"):
@@ -3375,6 +4168,7 @@ def test_query_orders_with_sort(
billing_address=address2,
status=OrderStatus.FULFILLED,
total=TaxedMoney(net=Money(100, "USD"), gross=Money(130, "USD")),
+ channel=channel_USD,
)
)
address3 = address.get_copy()
@@ -3386,6 +4180,7 @@ def test_query_orders_with_sort(
billing_address=address3,
status=OrderStatus.CANCELED,
total=TaxedMoney(net=Money(20, "USD"), gross=Money(26, "USD")),
+ channel=channel_USD,
)
)
variables = {"sort_by": order_sort}
@@ -3420,12 +4215,15 @@ QUERY_DRAFT_ORDER_WITH_SORT = """
({"field": "CREATION_DATE", "direction": "DESC"}, [2, 0, 1]),
({"field": "CUSTOMER", "direction": "ASC"}, [2, 0, 1]),
({"field": "CUSTOMER", "direction": "DESC"}, [1, 0, 2]),
- ({"field": "TOTAL", "direction": "ASC"}, [0, 2, 1]),
- ({"field": "TOTAL", "direction": "DESC"}, [1, 2, 0]),
],
)
def test_query_draft_orders_with_sort(
- draft_order_sort, result_order, staff_api_client, permission_manage_orders, address
+ draft_order_sort,
+ result_order,
+ staff_api_client,
+ permission_manage_orders,
+ address,
+ channel_USD,
):
created_orders = []
with freeze_time("2017-01-14"):
@@ -3435,6 +4233,7 @@ def test_query_draft_orders_with_sort(
billing_address=address,
status=OrderStatus.DRAFT,
total=TaxedMoney(net=Money(10, "USD"), gross=Money(13, "USD")),
+ channel=channel_USD,
)
)
with freeze_time("2012-01-14"):
@@ -3447,6 +4246,7 @@ def test_query_draft_orders_with_sort(
billing_address=address2,
status=OrderStatus.DRAFT,
total=TaxedMoney(net=Money(100, "USD"), gross=Money(130, "USD")),
+ channel=channel_USD,
)
)
address3 = address.get_copy()
@@ -3458,6 +4258,7 @@ def test_query_draft_orders_with_sort(
billing_address=address3,
status=OrderStatus.DRAFT,
total=TaxedMoney(net=Money(20, "USD"), gross=Money(26, "USD")),
+ channel=channel_USD,
)
)
variables = {"sort_by": draft_order_sort}
@@ -3494,6 +4295,7 @@ def test_orders_query_with_filter_search(
staff_api_client,
permission_manage_orders,
customer_user,
+ channel_USD,
):
orders = Order.objects.bulk_create(
[
@@ -3503,13 +4305,19 @@ def test_orders_query_with_filter_search(
discount_name="test_discount1",
user_email="[email protected]",
translated_discount_name="translated_discount1_name",
+ channel=channel_USD,
+ ),
+ Order(
+ token=str(uuid.uuid4()),
+ user_email="[email protected]",
+ channel=channel_USD,
),
- Order(token=str(uuid.uuid4()), user_email="[email protected]"),
Order(
token=str(uuid.uuid4()),
user_email="[email protected]",
discount_name="test_discount2",
translated_discount_name="translated_discount2_name",
+ channel=channel_USD,
),
]
)
@@ -3526,7 +4334,11 @@ def test_orders_query_with_filter_search(
def test_orders_query_with_filter_search_by_global_payment_id(
- orders_query_with_filter, staff_api_client, permission_manage_orders, customer_user,
+ orders_query_with_filter,
+ staff_api_client,
+ permission_manage_orders,
+ customer_user,
+ channel_USD,
):
orders = Order.objects.bulk_create(
@@ -3534,11 +4346,16 @@ def test_orders_query_with_filter_search_by_global_payment_id(
Order(
user=customer_user,
token=str(uuid.uuid4()),
+ channel=channel_USD,
discount_name="test_discount1",
user_email="[email protected]",
translated_discount_name="translated_discount1_name",
),
- Order(token=str(uuid.uuid4()), user_email="[email protected]"),
+ Order(
+ token=str(uuid.uuid4()),
+ channel=channel_USD,
+ user_email="[email protected]",
+ ),
]
)
order_with_payment = orders[0]
@@ -3583,6 +4400,7 @@ def test_draft_orders_query_with_filter_search(
staff_api_client,
permission_manage_orders,
customer_user,
+ channel_USD,
):
Order.objects.bulk_create(
[
@@ -3593,11 +4411,13 @@ def test_draft_orders_query_with_filter_search(
user_email="[email protected]",
translated_discount_name="translated_discount1_name",
status=OrderStatus.DRAFT,
+ channel=channel_USD,
),
Order(
token=str(uuid.uuid4()),
user_email="[email protected]",
status=OrderStatus.DRAFT,
+ channel=channel_USD,
),
Order(
token=str(uuid.uuid4()),
@@ -3605,6 +4425,7 @@ def test_draft_orders_query_with_filter_search(
discount_name="test_discount2",
translated_discount_name="translated_discount2_name",
status=OrderStatus.DRAFT,
+ channel=channel_USD,
),
]
)
diff --git a/saleor/graphql/order/tests/test_pagination.py b/saleor/graphql/order/tests/test_pagination.py
index 72bcbd3b5c..d6f442f783 100644
--- a/saleor/graphql/order/tests/test_pagination.py
+++ b/saleor/graphql/order/tests/test_pagination.py
@@ -12,20 +12,23 @@ from ...tests.utils import get_graphql_content
@pytest.fixture()
-def orders_for_pagination(db):
+def orders_for_pagination(db, channel_USD):
orders = Order.objects.bulk_create(
[
Order(
token=str(uuid.uuid4()),
total=TaxedMoney(net=Money(1, "USD"), gross=Money(1, "USD")),
+ channel=channel_USD,
),
Order(
token=str(uuid.uuid4()),
total=TaxedMoney(net=Money(2, "USD"), gross=Money(2, "USD")),
+ channel=channel_USD,
),
Order(
token=str(uuid.uuid4()),
total=TaxedMoney(net=Money(3, "USD"), gross=Money(3, "USD")),
+ channel=channel_USD,
),
]
)
@@ -33,23 +36,26 @@ def orders_for_pagination(db):
@pytest.fixture()
-def draft_orders_for_pagination(db):
+def draft_orders_for_pagination(db, channel_USD):
orders = Order.objects.bulk_create(
[
Order(
token=str(uuid.uuid4()),
total=TaxedMoney(net=Money(1, "USD"), gross=Money(1, "USD")),
status=OrderStatus.DRAFT,
+ channel=channel_USD,
),
Order(
token=str(uuid.uuid4()),
total=TaxedMoney(net=Money(2, "USD"), gross=Money(2, "USD")),
status=OrderStatus.DRAFT,
+ channel=channel_USD,
),
Order(
token=str(uuid.uuid4()),
total=TaxedMoney(net=Money(3, "USD"), gross=Money(3, "USD")),
status=OrderStatus.DRAFT,
+ channel=channel_USD,
),
]
)
@@ -146,9 +152,10 @@ def test_order_query_pagination_with_filter_created(
staff_api_client,
permission_manage_orders,
orders_for_pagination,
+ channel_USD,
):
with freeze_time("2012-01-14"):
- Order.objects.create()
+ Order.objects.create(channel=channel_USD)
page_size = 2
variables = {"first": page_size, "after": None, "filter": orders_filter}
staff_api_client.user.user_permissions.add(permission_manage_orders)
@@ -247,8 +254,6 @@ def test_order_query_pagination_with_filter_status(
response = staff_api_client.post_graphql(QUERY_ORDERS_WITH_PAGINATION, variables)
content = get_graphql_content(response)
- orders = content["data"]["orders"]["edges"]
-
orders = content["data"]["orders"]["edges"]
total_count = content["data"]["orders"]["totalCount"]
assert total_count == expected_total_count
@@ -273,12 +278,15 @@ def test_order_query_pagination_with_filter_customer_fields(
permission_manage_orders,
customer_user,
orders_for_pagination,
+ channel_USD,
):
setattr(customer_user, user_field, user_value)
customer_user.save()
customer_user.refresh_from_db()
- order = Order.objects.create(user=customer_user, token=str(uuid.uuid4()))
+ order = Order.objects.create(
+ user=customer_user, token=str(uuid.uuid4()), channel=channel_USD
+ )
page_size = 2
variables = {"first": page_size, "after": None, "filter": orders_filter}
@@ -308,13 +316,17 @@ def test_draft_order_query_pagination_with_filter_customer_fields(
permission_manage_orders,
customer_user,
draft_orders_for_pagination,
+ channel_USD,
):
setattr(customer_user, user_field, user_value)
customer_user.save()
customer_user.refresh_from_db()
order = Order.objects.create(
- status=OrderStatus.DRAFT, user=customer_user, token=str(uuid.uuid4())
+ status=OrderStatus.DRAFT,
+ user=customer_user,
+ token=str(uuid.uuid4()),
+ channel=channel_USD,
)
page_size = 2
@@ -357,9 +369,10 @@ def test_draft_order_query_pagination_with_filter_created(
staff_api_client,
permission_manage_orders,
draft_orders_for_pagination,
+ channel_USD,
):
with freeze_time("2012-01-14"):
- Order.objects.create(status=OrderStatus.DRAFT)
+ Order.objects.create(status=OrderStatus.DRAFT, channel=channel_USD)
page_size = 2
variables = {"first": page_size, "after": None, "filter": orders_filter}
staff_api_client.user.user_permissions.add(permission_manage_orders)
@@ -399,6 +412,7 @@ def test_orders_query_pagination_with_filter_search(
permission_manage_orders,
customer_user,
orders_for_pagination,
+ channel_USD,
):
Order.objects.bulk_create(
[
@@ -408,13 +422,19 @@ def test_orders_query_pagination_with_filter_search(
discount_name="test_discount1",
user_email="[email protected]",
translated_discount_name="translated_discount1_name",
+ channel=channel_USD,
+ ),
+ Order(
+ token=str(uuid.uuid4()),
+ user_email="[email protected]",
+ channel=channel_USD,
),
- Order(token=str(uuid.uuid4()), user_email="[email protected]"),
Order(
token=str(uuid.uuid4()),
user_email="[email protected]",
discount_name="test_discount2",
translated_discount_name="translated_discount2_name",
+ channel=channel_USD,
),
]
)
@@ -465,6 +485,7 @@ def test_draft_orders_query_pagination_with_filter_search(
permission_manage_orders,
customer_user,
draft_orders_for_pagination,
+ channel_USD,
):
Order.objects.bulk_create(
[
@@ -475,11 +496,13 @@ def test_draft_orders_query_pagination_with_filter_search(
user_email="[email protected]",
translated_discount_name="translated_discount1_name",
status=OrderStatus.DRAFT,
+ channel=channel_USD,
),
Order(
token=str(uuid.uuid4()),
user_email="[email protected]",
status=OrderStatus.DRAFT,
+ channel=channel_USD,
),
Order(
token=str(uuid.uuid4()),
@@ -487,6 +510,7 @@ def test_draft_orders_query_pagination_with_filter_search(
discount_name="test_discount2",
translated_discount_name="translated_discount2_name",
status=OrderStatus.DRAFT,
+ channel=channel_USD,
),
]
)
@@ -533,12 +557,15 @@ def test_draft_orders_query_pagination_with_filter_search_by_id(
({"field": "CUSTOMER", "direction": "DESC"}, [1, 0]),
({"field": "FULFILLMENT_STATUS", "direction": "ASC"}, [2, 1]),
({"field": "FULFILLMENT_STATUS", "direction": "DESC"}, [0, 1]),
- ({"field": "TOTAL", "direction": "ASC"}, [0, 2]),
- ({"field": "TOTAL", "direction": "DESC"}, [1, 2]),
],
)
def test_query_orders_pagination_with_sort(
- order_sort, result_order, staff_api_client, permission_manage_orders, address
+ order_sort,
+ result_order,
+ staff_api_client,
+ permission_manage_orders,
+ address,
+ channel_USD,
):
created_orders = []
with freeze_time("2017-01-14"):
@@ -548,6 +575,7 @@ def test_query_orders_pagination_with_sort(
billing_address=address,
status=OrderStatus.PARTIALLY_FULFILLED,
total=TaxedMoney(net=Money(10, "USD"), gross=Money(13, "USD")),
+ channel=channel_USD,
)
)
with freeze_time("2012-01-14"):
@@ -560,6 +588,7 @@ def test_query_orders_pagination_with_sort(
billing_address=address2,
status=OrderStatus.FULFILLED,
total=TaxedMoney(net=Money(100, "USD"), gross=Money(130, "USD")),
+ channel=channel_USD,
)
)
address3 = address.get_copy()
@@ -571,6 +600,7 @@ def test_query_orders_pagination_with_sort(
billing_address=address3,
status=OrderStatus.CANCELED,
total=TaxedMoney(net=Money(20, "USD"), gross=Money(26, "USD")),
+ channel=channel_USD,
)
)
page_size = 2
diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.py
index 293a352a3b..fe1ee77790 100644
--- a/saleor/graphql/order/types.py
+++ b/saleor/graphql/order/types.py
@@ -1,6 +1,7 @@
import graphene
from django.core.exceptions import ValidationError
from graphene import relay
+from promise import Promise
from ...core.anonymize import obfuscate_address, obfuscate_email
from ...core.exceptions import PermissionDenied
@@ -15,18 +16,23 @@ from ...product.templatetags.product_images import get_product_image_thumbnail
from ...warehouse import models as warehouse_models
from ..account.types import User
from ..account.utils import requestor_has_access
+from ..channel import ChannelContext
+from ..channel.dataloaders import ChannelByIdLoader, ChannelByOrderLineIdLoader
from ..core.connection import CountableDjangoObjectType
from ..core.types.common import Image
from ..core.types.money import Money, TaxedMoney
from ..decorators import one_of_permissions_required, permission_required
+from ..discount.dataloaders import VoucherByIdLoader
from ..giftcard.types import GiftCard
from ..invoice.types import Invoice
from ..meta.types import ObjectWithMetadata
from ..payment.types import OrderAction, Payment, PaymentChargeStatusEnum
+from ..product.resolvers import resolve_variant
from ..product.types import ProductVariant
+from ..shipping.dataloaders import ShippingMethodByIdLoader
from ..shipping.types import ShippingMethod
from ..warehouse.types import Allocation, Warehouse
-from .dataloaders import AllocationsByOrderLineIdLoader
+from .dataloaders import AllocationsByOrderLineIdLoader, OrderLinesByOrderIdLoader
from .enums import OrderEventsEmailsEnum, OrderEventsEnum
from .utils import validate_draft_order
@@ -294,6 +300,11 @@ class OrderLine(CountableDjangoObjectType):
def resolve_translated_variant_name(root: models.OrderLine, _info):
return root.translated_variant_name
+ @staticmethod
+ def resolve_variant(root: models.OrderLine, info):
+ dataloader = ChannelByOrderLineIdLoader(info.context)
+ return resolve_variant(info, root, dataloader)
+
@staticmethod
@one_of_permissions_required(
[ProductPermissions.MANAGE_PRODUCTS, OrderPermissions.MANAGE_ORDERS]
@@ -372,6 +383,7 @@ class Order(CountableDjangoObjectType):
"billing_address",
"created",
"customer_note",
+ "channel",
"discount",
"discount_name",
"display_gross_prices",
@@ -455,8 +467,8 @@ class Order(CountableDjangoObjectType):
return qs.order_by("pk")
@staticmethod
- def resolve_lines(root: models.Order, _info):
- return root.lines.all().order_by("pk")
+ def resolve_lines(root: models.Order, info):
+ return OrderLinesByOrderIdLoader(info.context).load(root.id)
@staticmethod
@permission_required(OrderPermissions.MANAGE_ORDERS)
@@ -513,24 +525,55 @@ class Order(CountableDjangoObjectType):
raise PermissionDenied()
@staticmethod
+ def resolve_shipping_method(root: models.Order, info):
+ if not root.shipping_method_id:
+ return None
+
+ def wrap_shipping_method_with_channel_context(data):
+ shipping_method, channel = data
+ return ChannelContext(node=shipping_method, channel_slug=channel.slug)
+
+ shipping_method = ShippingMethodByIdLoader(info.context).load(
+ root.shipping_method_id
+ )
+ channel = ChannelByIdLoader(info.context).load(root.channel_id)
+
+ return Promise.all([shipping_method, channel]).then(
+ wrap_shipping_method_with_channel_context
+ )
+
+ @staticmethod
+ # TODO: We should optimize it in/after PR#5819
def resolve_available_shipping_methods(root: models.Order, _info):
available = get_valid_shipping_methods_for_order(root)
if available is None:
return []
-
+ available_shipping_methods = []
manager = get_plugins_manager()
display_gross = display_gross_prices()
for shipping_method in available:
# Ignore typing check because it is checked in
# get_valid_shipping_methods_for_order
- taxed_price = manager.apply_taxes_to_shipping(
- shipping_method.price, root.shipping_address # type: ignore
- )
- if display_gross:
- shipping_method.price = taxed_price.gross
- else:
- shipping_method.price = taxed_price.net
- return available
+ shipping_channel_listing = shipping_method.channel_listings.filter(
+ channel=root.channel
+ ).first()
+ if shipping_channel_listing:
+ taxed_price = manager.apply_taxes_to_shipping(
+ shipping_channel_listing.price,
+ root.shipping_address, # type: ignore
+ )
+ 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
+ ]
+
+ return instances
@staticmethod
def resolve_invoices(root: models.Order, info):
@@ -546,3 +589,17 @@ class Order(CountableDjangoObjectType):
@staticmethod
def resolve_gift_cards(root: models.Order, _info):
return root.gift_cards.all()
+
+ @staticmethod
+ def resolve_voucher(root: models.Order, info):
+ if not root.voucher_id:
+ return None
+
+ def wrap_voucher_with_channel_context(data):
+ voucher, channel = data
+ return ChannelContext(node=voucher, channel_slug=channel.slug)
+
+ voucher = VoucherByIdLoader(info.context).load(root.voucher_id)
+ channel = ChannelByIdLoader(info.context).load(root.channel_id)
+
+ return Promise.all([voucher, channel]).then(wrap_voucher_with_channel_context)
diff --git a/saleor/graphql/order/utils.py b/saleor/graphql/order/utils.py
index 1227dbc7e5..5bc749c23b 100644
--- a/saleor/graphql/order/utils.py
+++ b/saleor/graphql/order/utils.py
@@ -1,7 +1,9 @@
+import graphene
from django.core.exceptions import ValidationError
from ...core.exceptions import InsufficientStock
from ...order.error_codes import OrderErrorCode
+from ...product.models import Product, ProductVariant, ProductVariantChannelListing
from ...warehouse.availability import check_stock_quantity
@@ -91,21 +93,88 @@ def validate_order_lines(order, country):
def validate_product_is_published(order):
+ variant_ids = []
for line in order:
- if not line.variant.product.is_published:
- raise ValidationError(
- {
- "lines": ValidationError(
- "Can't finalize draft with unpublished product.",
- code=OrderErrorCode.PRODUCT_NOT_PUBLISHED,
- )
- }
- )
+ variant_ids.append(line.variant_id)
+ unpublished_product = Product.objects.filter(
+ variants__id__in=variant_ids
+ ).not_published(order.channel.slug)
+ if unpublished_product.exists():
+ raise ValidationError(
+ {
+ "lines": ValidationError(
+ "Can't finalize draft with unpublished product.",
+ code=OrderErrorCode.PRODUCT_NOT_PUBLISHED,
+ )
+ }
+ )
+
+
+def validate_product_is_published_in_channel(variants, channel):
+ if not channel:
+ raise ValidationError(
+ "Can't add product variant for draft order without channel",
+ code=OrderErrorCode.REQUIRED,
+ )
+ variant_ids = [variant.id for variant in variants]
+ unpublished_product = list(
+ Product.objects.filter(variants__id__in=variant_ids).not_published(channel.slug)
+ )
+ if unpublished_product:
+ unpublished_variants = ProductVariant.objects.filter(
+ product_id__in=unpublished_product, id__in=variant_ids
+ ).values_list("pk", flat=True)
+ unpublished_variants_global_ids = [
+ graphene.Node.to_global_id("ProductVariant", unpublished_variant)
+ for unpublished_variant in unpublished_variants
+ ]
+ raise ValidationError(
+ "Can't add product variant that are not published in "
+ "the channel associated with this draft order.",
+ code=OrderErrorCode.PRODUCT_NOT_PUBLISHED,
+ params={"variants": unpublished_variants_global_ids},
+ )
+
+
+def validate_variant_channel_listings(variants, channel):
+ if not channel:
+ raise ValidationError(
+ "Can't add product variant for draft order without channel",
+ code=OrderErrorCode.REQUIRED,
+ )
+ variant_ids = set([variant.id for variant in variants])
+ variant_channel_listings = ProductVariantChannelListing.objects.filter(
+ channel=channel, variant_id__in=variant_ids
+ )
+ variant_ids_in_channel = set(
+ [
+ variant_channel_listing.variant_id
+ for variant_channel_listing in variant_channel_listings
+ ]
+ )
+ missing_variant_ids_in_channel = variant_ids - variant_ids_in_channel
+ if missing_variant_ids_in_channel:
+ missing_variant_global_ids = [
+ graphene.Node.to_global_id("ProductVariant", missing_variant_id_in_channel)
+ for missing_variant_id_in_channel in missing_variant_ids_in_channel
+ ]
+ raise ValidationError(
+ "Can't add product variant that are don't have price in"
+ "the channel associated with this draft order.",
+ code=OrderErrorCode.NOT_AVAILABLE_IN_CHANNEL,
+ params={"variants": missing_variant_global_ids},
+ )
def validate_product_is_available_for_purchase(order):
for line in order:
- if not line.variant.product.is_available_for_purchase():
+ product_channel_listing = line.variant.product.channel_listings.filter(
+ channel_id=order.channel_id
+ ).first()
+ if not (
+ product_channel_listing
+ and product_channel_listing.is_available_for_purchase()
+ ):
raise ValidationError(
{
"lines": ValidationError(
@@ -116,13 +185,25 @@ def validate_product_is_available_for_purchase(order):
)
+def validate_channel_is_active(channel):
+ if not channel.is_active:
+ raise ValidationError(
+ {
+ "channel": ValidationError(
+ "Cannot complete draft order with inactive channel.",
+ code=OrderErrorCode.CHANNEL_INACTIVE.value,
+ )
+ }
+ )
+
+
def validate_draft_order(order, country):
"""Check if the given order contains the proper data.
- Has proper customer data,
- Shipping address and method are set up,
- Product variants for order lines still exists in database.
- - Product variants are availale in requested quantity.
+ - Product variants are available in requested quantity.
- Product variants are published.
Returns a list of errors if any were found.
@@ -135,3 +216,4 @@ def validate_draft_order(order, country):
validate_order_lines(order, country)
validate_product_is_published(order)
validate_product_is_available_for_purchase(order)
+ validate_channel_is_active(order.channel)
diff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.py
index 1ae22f3ed9..6b8bf5aced 100644
--- a/saleor/graphql/payment/mutations.py
+++ b/saleor/graphql/payment/mutations.py
@@ -1,5 +1,4 @@
import graphene
-from django.conf import settings
from django.core.exceptions import ValidationError
from ...checkout.calculations import calculate_checkout_total_with_gift_cards
@@ -174,7 +173,7 @@ class CheckoutPaymentCreate(BaseMutation, I18nMixin):
gateway=gateway,
payment_token=data.get("token", ""),
total=amount,
- currency=settings.DEFAULT_CURRENCY,
+ currency=checkout.currency,
email=checkout.email,
extra_data=extra_data,
# FIXME this is not a customer IP address. It is a client storefront ip
diff --git a/saleor/graphql/product/bulk_mutations/products.py b/saleor/graphql/product/bulk_mutations/products.py
index 903e1eba11..d4acbc7321 100644
--- a/saleor/graphql/product/bulk_mutations/products.py
+++ b/saleor/graphql/product/bulk_mutations/products.py
@@ -8,17 +8,14 @@ from ....core.permissions import ProductPermissions, ProductTypePermissions
from ....order import OrderStatus, models as order_models
from ....product import models
from ....product.error_codes import ProductErrorCode
-from ....product.tasks import update_product_minimal_variant_price_task
+from ....product.tasks import update_product_discounted_price_task
from ....product.utils import delete_categories
from ....product.utils.attributes import generate_name_for_variant
from ....warehouse import models as warehouse_models
from ....warehouse.error_codes import StockErrorCode
-from ...core.mutations import (
- BaseBulkMutation,
- BaseMutation,
- ModelBulkDeleteMutation,
- ModelMutation,
-)
+from ...channel import ChannelContext
+from ...channel.types import Channel
+from ...core.mutations import BaseMutation, ModelBulkDeleteMutation, ModelMutation
from ...core.types.common import (
BulkProductError,
BulkStockError,
@@ -29,6 +26,7 @@ from ...core.utils import get_duplicated_values
from ...core.validators import validate_price_precision
from ...utils import resolve_global_ids_to_primary_keys
from ...warehouse.types import Warehouse
+from ..mutations.channels import ProductVariantChannelListingAddInput
from ..mutations.products import (
AttributeAssignmentMixin,
AttributeValueInput,
@@ -72,30 +70,6 @@ class CollectionBulkDelete(ModelBulkDeleteMutation):
error_type_field = "product_errors"
-class CollectionBulkPublish(BaseBulkMutation):
- class Arguments:
- ids = graphene.List(
- graphene.ID,
- required=True,
- description="List of collections IDs to (un)publish.",
- )
- is_published = graphene.Boolean(
- required=True,
- description="Determine if collections will be published or not.",
- )
-
- class Meta:
- description = "Publish collections."
- model = models.Collection
- permissions = (ProductPermissions.MANAGE_PRODUCTS,)
- error_type_class = ProductError
- error_type_field = "product_errors"
-
- @classmethod
- def bulk_action(cls, queryset, is_published):
- queryset.update(is_published=is_published)
-
-
class ProductBulkDelete(ModelBulkDeleteMutation):
class Arguments:
ids = graphene.List(
@@ -139,6 +113,11 @@ class ProductVariantBulkCreateInput(ProductVariantInput):
description=("Stocks of a product available for sale."),
required=False,
)
+ channel_listings = graphene.List(
+ graphene.NonNull(ProductVariantChannelListingAddInput),
+ description="List of prices assigned to channels.",
+ required=False,
+ )
sku = graphene.String(required=True, description="Stock keeping unit.")
@@ -186,24 +165,6 @@ class ProductVariantBulkCreate(BaseMutation):
info, instance, data, input_cls=ProductVariantBulkCreateInput
)
- cost_price_amount = cleaned_input.pop("cost_price", None)
- if cost_price_amount is not None:
- try:
- validate_price_precision(cost_price_amount)
- except ValidationError as error:
- error.code = ProductErrorCode.INVALID.value
- raise ValidationError({"cost_price": error})
- cleaned_input["cost_price_amount"] = cost_price_amount
-
- price_amount = cleaned_input.pop("price", None)
- if price_amount is not None:
- try:
- validate_price_precision(price_amount)
- except ValidationError as error:
- error.code = ProductErrorCode.INVALID.value
- raise ValidationError({"price": error})
- cleaned_input["price_amount"] = price_amount
-
attributes = cleaned_input.get("attributes")
if attributes:
try:
@@ -214,12 +175,92 @@ class ProductVariantBulkCreate(BaseMutation):
exc.params = {"index": variant_index}
errors["attributes"] = exc
+ channel_listings = cleaned_input.get("channel_listings")
+ if channel_listings:
+ cleaned_input["channel_listings"] = cls.clean_channel_listings(
+ channel_listings, errors, data["product"], variant_index
+ )
+
stocks = cleaned_input.get("stocks")
if stocks:
cls.clean_stocks(stocks, errors, variant_index)
return cleaned_input
+ @classmethod
+ def clean_price(
+ cls, price, field_name, currency, channel_id, variant_index, errors
+ ):
+ try:
+ validate_price_precision(price, currency)
+ except ValidationError as error:
+ error.code = ProductErrorCode.INVALID.value
+ error.params = {
+ "channels": [channel_id],
+ "index": variant_index,
+ }
+ errors[field_name].append(error)
+
+ @classmethod
+ def clean_channel_listings(cls, channels_data, errors, product, variant_index):
+ channel_ids = [
+ channel_listing["channel_id"] for channel_listing in channels_data
+ ]
+ duplicates = get_duplicated_values(channel_ids)
+ if duplicates:
+ errors["channel_listings"] = ValidationError(
+ "Duplicated channel ID.",
+ code=ProductErrorCode.DUPLICATED_INPUT_ITEM.value,
+ params={"channels": duplicates, "index": variant_index},
+ )
+ return channels_data
+ channels = cls.get_nodes_or_error(
+ channel_ids, "channel_listings", only_type=Channel
+ )
+ for index, channel_listing_data in enumerate(channels_data):
+ channel_listing_data["channel"] = channels[index]
+
+ for channel_listing_data in channels_data:
+ price = channel_listing_data.get("price")
+ cost_price = channel_listing_data.get("cost_price")
+ channel_id = channel_listing_data["channel_id"]
+ currency_code = channel_listing_data["channel"].currency_code
+ cls.clean_price(
+ price, "price", currency_code, channel_id, variant_index, errors
+ )
+ cls.clean_price(
+ cost_price,
+ "cost_price",
+ currency_code,
+ channel_id,
+ variant_index,
+ errors,
+ )
+
+ channels_not_assigned_to_product = []
+ channels_assigned_to_product = list(
+ models.ProductChannelListing.objects.filter(product=product.id).values_list(
+ "channel_id", flat=True
+ )
+ )
+ for channel_listing_data in channels_data:
+ if not channel_listing_data["channel"].id in channels_assigned_to_product:
+ channels_not_assigned_to_product.append(
+ channel_listing_data["channel_id"]
+ )
+ if channels_not_assigned_to_product:
+ errors["channel_id"].append(
+ ValidationError(
+ "Product not available in channels.",
+ code=ProductErrorCode.PRODUCT_NOT_ASSIGNED_TO_CHANNEL.value,
+ params={
+ "index": variant_index,
+ "channels": channels_not_assigned_to_product,
+ },
+ )
+ )
+ return channels_data
+
@classmethod
def clean_stocks(cls, stocks_data, errors, variant_index):
warehouse_ids = [stock["warehouse"] for stock in stocks_data]
@@ -227,7 +268,7 @@ class ProductVariantBulkCreate(BaseMutation):
if duplicates:
errors["stocks"] = ValidationError(
"Duplicated warehouse ID.",
- code=ProductErrorCode.DUPLICATED_INPUT_ITEM,
+ code=ProductErrorCode.DUPLICATED_INPUT_ITEM.value,
params={"warehouses": duplicates, "index": variant_index},
)
@@ -295,6 +336,7 @@ class ProductVariantBulkCreate(BaseMutation):
cleaned_input = None
variant_data["product_type"] = product.product_type
+ variant_data["product"] = product
cleaned_input = cls.clean_variant_input(
info, None, variant_data, errors, index
)
@@ -306,6 +348,29 @@ class ProductVariantBulkCreate(BaseMutation):
cls.validate_duplicated_sku(variant_data.sku, index, sku_list, errors)
return cleaned_inputs
+ @classmethod
+ def create_variant_channel_listings(cls, variant, cleaned_input):
+ channel_listings_data = cleaned_input.get("channel_listings")
+ if not channel_listings_data:
+ return
+ variant_channel_listings = []
+ for channel_listing_data in channel_listings_data:
+ channel = channel_listing_data["channel"]
+ price = channel_listing_data["price"]
+ cost_price = channel_listing_data.get("cost_price")
+ variant_channel_listings.append(
+ models.ProductVariantChannelListing(
+ channel=channel,
+ variant=variant,
+ price_amount=price,
+ cost_price_amount=cost_price,
+ currency=channel.currency_code,
+ )
+ )
+ models.ProductVariantChannelListing.objects.bulk_create(
+ variant_channel_listings
+ )
+
@classmethod
@transaction.atomic
def save_variants(cls, info, instances, product, cleaned_inputs):
@@ -315,6 +380,7 @@ class ProductVariantBulkCreate(BaseMutation):
for instance, cleaned_input in zip(instances, cleaned_inputs):
cls.save(info, instance, cleaned_input)
cls.create_variant_stocks(instance, cleaned_input)
+ cls.create_variant_channel_listings(instance, cleaned_input)
if not product.default_variant:
product.default_variant = instances[0]
product.save(update_fields=["default_variant", "updated_at"])
@@ -341,9 +407,12 @@ class ProductVariantBulkCreate(BaseMutation):
raise ValidationError(errors)
cls.save_variants(info, instances, product, cleaned_inputs)
- # Recalculate the "minimal variant price" for the parent product
- update_product_minimal_variant_price_task.delay(product.pk)
+ # Recalculate the "discounted price" for the parent product
+ update_product_discounted_price_task.delay(product.pk)
+ instances = [
+ ChannelContext(node=instance, channel_slug=None) for instance in instances
+ ]
return ProductVariantBulkCreate(
count=len(instances), product_variants=instances
)
@@ -431,6 +500,8 @@ class ProductVariantStocksCreate(BaseMutation):
if errors:
raise ValidationError(errors)
create_stocks(variant, stocks, warehouses)
+
+ variant = ChannelContext(node=variant, channel_slug=None)
return cls(product_variant=variant)
@classmethod
@@ -499,6 +570,8 @@ class ProductVariantStocksUpdate(ProductVariantStocksCreate):
warehouse_ids, "warehouse", only_type=Warehouse
)
cls.update_or_create_variant_stocks(variant, stocks, warehouses)
+
+ variant = ChannelContext(node=variant, channel_slug=None)
return cls(product_variant=variant)
@classmethod
@@ -543,6 +616,8 @@ class ProductVariantStocksDelete(BaseMutation):
warehouse_models.Stock.objects.filter(
product_variant=variant, warehouse__pk__in=warehouses_pks
).delete()
+
+ variant = ChannelContext(node=variant, channel_slug=None)
return cls(product_variant=variant)
@@ -576,24 +651,3 @@ class ProductImageBulkDelete(ModelBulkDeleteMutation):
permissions = (ProductPermissions.MANAGE_PRODUCTS,)
error_type_class = ProductError
error_type_field = "product_errors"
-
-
-class ProductBulkPublish(BaseBulkMutation):
- class Arguments:
- ids = graphene.List(
- graphene.ID, required=True, description="List of products IDs to publish."
- )
- is_published = graphene.Boolean(
- required=True, description="Determine if products will be published or not."
- )
-
- class Meta:
- description = "Publish products."
- model = models.Product
- permissions = (ProductPermissions.MANAGE_PRODUCTS,)
- error_type_class = ProductError
- error_type_field = "product_errors"
-
- @classmethod
- def bulk_action(cls, queryset, is_published):
- queryset.update(is_published=is_published)
diff --git a/saleor/graphql/product/dataloaders/__init__.py b/saleor/graphql/product/dataloaders/__init__.py
index e047b45640..b2c3b86c10 100644
--- a/saleor/graphql/product/dataloaders/__init__.py
+++ b/saleor/graphql/product/dataloaders/__init__.py
@@ -8,28 +8,48 @@ from .attributes import (
from .products import (
CategoryByIdLoader,
CollectionByIdLoader,
+ CollectionChannelListingByCollectionIdAndChannelSlugLoader,
+ CollectionChannelListingByCollectionIdLoader,
+ CollectionChannelListingByIdLoader,
CollectionsByProductIdLoader,
ImagesByProductIdLoader,
ImagesByProductVariantIdLoader,
ProductByIdLoader,
+ ProductChannelListingByIdLoader,
+ ProductChannelListingByProductIdAndChannelSlugLoader,
+ ProductChannelListingByProductIdLoader,
ProductTypeByIdLoader,
ProductVariantByIdLoader,
+ ProductVariantChannelListingByIdLoader,
ProductVariantsByProductIdLoader,
+ VariantChannelListingByVariantIdAndChannelSlugLoader,
+ VariantChannelListingByVariantIdLoader,
+ VariantsChannelListingByProductIdAndChanneSlugLoader,
)
__all__ = [
"AttributeValuesByAttributeIdLoader",
"CategoryByIdLoader",
"CollectionByIdLoader",
+ "CollectionChannelListingByCollectionIdAndChannelSlugLoader",
+ "CollectionChannelListingByCollectionIdLoader",
+ "CollectionChannelListingByIdLoader",
"CollectionsByProductIdLoader",
"ImagesByProductIdLoader",
"ProductAttributesByProductTypeIdLoader",
"ProductByIdLoader",
+ "ProductChannelListingByIdLoader",
+ "ProductChannelListingByProductIdLoader",
+ "ProductChannelListingByProductIdAndChannelSlugLoader",
"ProductTypeByIdLoader",
"ProductVariantByIdLoader",
+ "ProductVariantChannelListingByIdLoader",
"ProductVariantsByProductIdLoader",
"ImagesByProductVariantIdLoader",
"SelectedAttributesByProductIdLoader",
"SelectedAttributesByProductVariantIdLoader",
"VariantAttributesByProductTypeIdLoader",
+ "VariantChannelListingByVariantIdAndChannelSlugLoader",
+ "VariantChannelListingByVariantIdLoader",
+ "VariantsChannelListingByProductIdAndChanneSlugLoader",
]
diff --git a/saleor/graphql/product/dataloaders/products.py b/saleor/graphql/product/dataloaders/products.py
index d493503cba..0574ba5f24 100644
--- a/saleor/graphql/product/dataloaders/products.py
+++ b/saleor/graphql/product/dataloaders/products.py
@@ -1,17 +1,25 @@
from collections import defaultdict
+from typing import DefaultDict, Dict, Iterable, List, Optional, Tuple
+
+from django.db.models import F
from ....product.models import (
Category,
Collection,
+ CollectionChannelListing,
CollectionProduct,
Product,
+ ProductChannelListing,
ProductImage,
ProductType,
ProductVariant,
+ ProductVariantChannelListing,
VariantImage,
)
from ...core.dataloaders import DataLoader
-from ...utils import get_user_or_app_from_context
+
+ProductIdAndChannelSlug = Tuple[int, str]
+VariantIdAndChannelSlug = Tuple[int, str]
class CategoryByIdLoader(DataLoader):
@@ -26,11 +34,85 @@ class ProductByIdLoader(DataLoader):
context_key = "product_by_id"
def batch_load(self, keys):
- requestor = get_user_or_app_from_context(self.context)
- products = Product.objects.visible_to_user(requestor).in_bulk(keys)
+ products = Product.objects.all().in_bulk(keys)
return [products.get(product_id) for product_id in keys]
+class ProductChannelListingByIdLoader(DataLoader[int, ProductChannelListing]):
+ context_key = "productchannelisting_by_id"
+
+ def batch_load(self, keys):
+ product_channel_listings = ProductChannelListing.objects.in_bulk(keys)
+ return [product_channel_listings.get(key) for key in keys]
+
+
+class ProductChannelListingByProductIdLoader(DataLoader[int, ProductChannelListing]):
+ context_key = "productchannelisting_by_product"
+
+ def batch_load(self, keys):
+ product_channel_listings = ProductChannelListing.objects.filter(
+ product_id__in=keys
+ )
+ product_id_variant_channel_listings_map = defaultdict(list)
+ for product_channel_listing in product_channel_listings:
+ product_id_variant_channel_listings_map[
+ product_channel_listing.product_id
+ ].append(product_channel_listing)
+ return [
+ product_id_variant_channel_listings_map.get(product_id, [])
+ for product_id in keys
+ ]
+
+
+class ProductChannelListingByProductIdAndChannelSlugLoader(
+ DataLoader[ProductIdAndChannelSlug, ProductChannelListing]
+):
+ context_key = "productchannelisting_by_product_and_channel"
+
+ def batch_load(self, keys):
+ # Split the list of keys by channel first. A typical query will only touch
+ # a handful of unique countries but may access thousands of product variants
+ # so it's cheaper to execute one query per channel.
+ product_channel_listing_by_channel: DefaultDict[str, List[int]] = defaultdict(
+ list
+ )
+ for product_id, channel_slug in keys:
+ product_channel_listing_by_channel[channel_slug].append(product_id)
+
+ # For each channel execute a single query for all products.
+ product_channel_listing_by_product_and_channel: DefaultDict[
+ ProductIdAndChannelSlug, Optional[ProductChannelListing]
+ ] = defaultdict()
+ for channel_slug, product_ids in product_channel_listing_by_channel.items():
+ product_channel_listings = self.batch_load_channel(
+ channel_slug, product_ids
+ )
+ for product_id, product_channel_listing in product_channel_listings:
+ product_channel_listing_by_product_and_channel[
+ (product_id, channel_slug)
+ ] = product_channel_listing
+
+ return [product_channel_listing_by_product_and_channel[key] for key in keys]
+
+ def batch_load_channel(
+ self, channel_slug: str, products_ids: Iterable[int]
+ ) -> Iterable[Tuple[int, Optional[ProductChannelListing]]]:
+ product_channel_listings = ProductChannelListing.objects.filter(
+ channel__slug=channel_slug, product_id__in=products_ids
+ )
+
+ product_channel_listings_map: Dict[int, ProductChannelListing] = {}
+ for product_channel_listing in product_channel_listings.iterator():
+ product_channel_listings_map[
+ product_channel_listing.product_id
+ ] = product_channel_listing
+
+ return [
+ (products_id, product_channel_listings_map.get(products_id))
+ for products_id in products_ids
+ ]
+
+
class ProductTypeByIdLoader(DataLoader):
context_key = "product_type_by_id"
@@ -71,6 +153,132 @@ class ProductVariantsByProductIdLoader(DataLoader):
return [variant_map.get(product_id, []) for product_id in keys]
+class ProductVariantChannelListingByIdLoader(DataLoader):
+ context_key = "productvariantchannelisting_by_id"
+
+ def batch_load(self, keys):
+ variants = ProductVariantChannelListing.objects.in_bulk(keys)
+ return [variants.get(key) for key in keys]
+
+
+class VariantChannelListingByVariantIdLoader(DataLoader):
+ context_key = "productvariantchannelisting_by_productvariant"
+
+ def batch_load(self, keys):
+ variant_channel_listings = ProductVariantChannelListing.objects.filter(
+ variant_id__in=keys
+ )
+ variant_id_variant_channel_listings_map = defaultdict(list)
+ for variant_channel_listing in variant_channel_listings:
+ variant_id_variant_channel_listings_map[
+ variant_channel_listing.variant_id
+ ].append(variant_channel_listing)
+ return [
+ variant_id_variant_channel_listings_map.get(variant_id, [])
+ for variant_id in keys
+ ]
+
+
+class VariantChannelListingByVariantIdAndChannelSlugLoader(
+ DataLoader[VariantIdAndChannelSlug, ProductVariantChannelListing]
+):
+ context_key = "variantchannelisting_by_variant_and_channel"
+
+ def batch_load(self, keys):
+ # Split the list of keys by channel first. A typical query will only touch
+ # a handful of unique countries but may access thousands of product variants
+ # so it's cheaper to execute one query per channel.
+ variant_channel_listing_by_channel: DefaultDict[str, List[int]] = defaultdict(
+ list
+ )
+ for variant_id, channel_slug in keys:
+ variant_channel_listing_by_channel[channel_slug].append(variant_id)
+
+ # For each channel execute a single query for all product variants.
+ variant_channel_listing_by_variant_and_channel: DefaultDict[
+ VariantIdAndChannelSlug, Optional[ProductVariantChannelListing]
+ ] = defaultdict()
+ for channel_slug, variant_ids in variant_channel_listing_by_channel.items():
+ variant_channel_listings = self.batch_load_channel(
+ channel_slug, variant_ids
+ )
+ for variant_id, variant_channel_listing in variant_channel_listings:
+ variant_channel_listing_by_variant_and_channel[
+ (variant_id, channel_slug)
+ ] = variant_channel_listing
+
+ return [variant_channel_listing_by_variant_and_channel[key] for key in keys]
+
+ def batch_load_channel(
+ self, channel_slug: str, variant_ids: Iterable[int]
+ ) -> Iterable[Tuple[int, Optional[ProductVariantChannelListing]]]:
+ variant_channel_listings = ProductVariantChannelListing.objects.filter(
+ channel__slug=channel_slug, variant_id__in=variant_ids
+ )
+
+ variant_channel_listings_map: Dict[int, ProductVariantChannelListing] = {}
+ for variant_channel_listing in variant_channel_listings.iterator():
+ variant_channel_listings_map[
+ variant_channel_listing.variant_id
+ ] = variant_channel_listing
+
+ return [
+ (variant_id, variant_channel_listings_map.get(variant_id))
+ for variant_id in variant_ids
+ ]
+
+
+class VariantsChannelListingByProductIdAndChanneSlugLoader(
+ DataLoader[ProductIdAndChannelSlug, Iterable[ProductVariantChannelListing]]
+):
+ context_key = "variantschannelisting_by_product_and_channel"
+
+ def batch_load(self, keys):
+ # Split the list of keys by channel first. A typical query will only touch
+ # a handful of unique countries but may access thousands of product variants
+ # so it's cheaper to execute one query per channel.
+ variant_channel_listing_by_channel: DefaultDict[str, List[int]] = defaultdict(
+ list
+ )
+ for product_id, channel_slug in keys:
+ variant_channel_listing_by_channel[channel_slug].append(product_id)
+
+ # For each channel execute a single query for all product variants.
+ variant_channel_listing_by_product_and_channel: DefaultDict[
+ ProductIdAndChannelSlug, Optional[Iterable[ProductVariantChannelListing]]
+ ] = defaultdict()
+ for channel_slug, product_ids in variant_channel_listing_by_channel.items():
+ varaint_channel_listings = self.batch_load_channel(
+ channel_slug, product_ids
+ )
+ for product_id, variants_channel_listing in varaint_channel_listings:
+ variant_channel_listing_by_product_and_channel[
+ (product_id, channel_slug)
+ ] = variants_channel_listing
+
+ return [variant_channel_listing_by_product_and_channel[key] for key in keys]
+
+ def batch_load_channel(
+ self, channel_slug: str, products_ids: Iterable[int]
+ ) -> Iterable[Tuple[int, Optional[List[ProductVariantChannelListing]]]]:
+ variants_channel_listings = ProductVariantChannelListing.objects.filter(
+ channel__slug=channel_slug, variant__product_id__in=products_ids
+ ).annotate(product_id=F("variant__product_id"))
+
+ variants_channel_listings_map: Dict[
+ int, List[ProductVariantChannelListing]
+ ] = defaultdict(list)
+ for variant_channel_listing in variants_channel_listings.iterator():
+ variants_channel_listings_map[variant_channel_listing.product_id].append(
+ variant_channel_listing
+ )
+
+ return [
+ (products_id, variants_channel_listings_map.get(products_id))
+ for products_id in products_ids
+ ]
+
+
class ImagesByProductVariantIdLoader(DataLoader):
context_key = "images_by_product_variant"
@@ -115,3 +323,53 @@ class CollectionsByProductIdLoader(DataLoader):
.load_many(set(cid for pid, cid in product_collection_pairs))
.then(map_collections)
)
+
+
+class CollectionChannelListingByIdLoader(DataLoader):
+ context_key = "collectionchannelisting_by_id"
+
+ def batch_load(self, keys):
+ collections = CollectionChannelListing.objects.in_bulk(keys)
+ return [collections.get(key) for key in keys]
+
+
+class CollectionChannelListingByCollectionIdLoader(DataLoader):
+ context_key = "collectionchannelisting_by_collection"
+
+ def batch_load(self, keys):
+ collections_channel_listings = CollectionChannelListing.objects.filter(
+ collection_id__in=keys
+ )
+ collection_id_collection_channel_listings_map = defaultdict(list)
+ for collection_channel_listing in collections_channel_listings:
+ collection_id_collection_channel_listings_map[
+ collection_channel_listing.collection_id
+ ].append(collection_channel_listing)
+ return [
+ collection_id_collection_channel_listings_map.get(collection_id, [])
+ for collection_id in keys
+ ]
+
+
+class CollectionChannelListingByCollectionIdAndChannelSlugLoader(DataLoader):
+ context_key = "collectionchannelisting_by_collection_and_channel"
+
+ def batch_load(self, keys):
+ collection_ids = [key[0] for key in keys]
+ channel_slugs = [key[1] for key in keys]
+ collections_channel_listings = CollectionChannelListing.objects.filter(
+ collection_id__in=collection_ids, channel__slug__in=channel_slugs
+ ).annotate(channel_slug=F("channel__slug"))
+ collections_channel_listings_by_collection_and_channel_map = {}
+ for collections_channel_listing in collections_channel_listings:
+ key = (
+ collections_channel_listing.collection_id,
+ collections_channel_listing.channel_slug,
+ )
+ collections_channel_listings_by_collection_and_channel_map[
+ key
+ ] = collections_channel_listing
+ return [
+ collections_channel_listings_by_collection_and_channel_map.get(key, None)
+ for key in keys
+ ]
diff --git a/saleor/graphql/product/filters.py b/saleor/graphql/product/filters.py
index 11607773f9..72d80626e1 100644
--- a/saleor/graphql/product/filters.py
+++ b/saleor/graphql/product/filters.py
@@ -19,8 +19,9 @@ from ...product.models import (
)
from ...search.backends import picker
from ...warehouse.models import Stock
+from ..channel.filters import get_channel_slug_from_filter_data
from ..core.filters import EnumFilter, ListObjectTypeFilter, ObjectTypeFilter
-from ..core.types import FilterInputObjectType
+from ..core.types import ChannelFilterInputObjectType, FilterInputObjectType
from ..core.types.common import IntRangeInput, PriceRangeInput
from ..core.utils import from_global_id_strict_type
from ..utils import (
@@ -107,21 +108,33 @@ def filter_products_by_attributes(qs, filter_value):
return filter_products_by_attributes_values(qs, queries)
-def filter_products_by_variant_price(qs, price_lte=None, price_gte=None):
+def filter_products_by_variant_price(qs, channel_slug, price_lte=None, price_gte=None):
if price_lte:
- qs = qs.filter(variants__price_amount__lte=price_lte)
+ qs = qs.filter(
+ variants__channel_listings__price_amount__lte=price_lte,
+ variants__channel_listings__channel__slug=channel_slug,
+ )
if price_gte:
- qs = qs.filter(variants__price_amount__gte=price_gte)
+ qs = qs.filter(
+ variants__channel_listings__price_amount__gte=price_gte,
+ variants__channel_listings__channel__slug=channel_slug,
+ )
return qs
def filter_products_by_minimal_price(
- qs, minimal_price_lte=None, minimal_price_gte=None
+ qs, channel_slug, minimal_price_lte=None, minimal_price_gte=None
):
if minimal_price_lte:
- qs = qs.filter(minimal_variant_price_amount__lte=minimal_price_lte)
+ qs = qs.filter(
+ channel_listings__discounted_price_amount__lte=minimal_price_lte,
+ channel_listings__channel__slug=channel_slug,
+ )
if minimal_price_gte:
- qs = qs.filter(minimal_variant_price_amount__gte=minimal_price_gte)
+ qs = qs.filter(
+ channel_listings__discounted_price_amount__gte=minimal_price_gte,
+ channel_listings__channel__slug=channel_slug,
+ )
return qs
@@ -185,16 +198,26 @@ def filter_collections(qs, _, value):
return qs
-def filter_variant_price(qs, _, value):
+def _filter_is_published(qs, _, value, channel_slug):
+ return qs.filter(
+ channel_listings__is_published=value,
+ channel_listings__channel__slug=channel_slug,
+ )
+
+
+def _filter_variant_price(qs, _, value, channel_slug):
qs = filter_products_by_variant_price(
- qs, price_lte=value.get("lte"), price_gte=value.get("gte")
+ qs, channel_slug, price_lte=value.get("lte"), price_gte=value.get("gte")
)
return qs
-def filter_minimal_price(qs, _, value):
+def _filter_minimal_price(qs, _, value, channel_slug):
qs = filter_products_by_minimal_price(
- qs, minimal_price_lte=value.get("lte"), minimal_price_gte=value.get("gte")
+ qs,
+ channel_slug,
+ minimal_price_lte=value.get("lte"),
+ minimal_price_gte=value.get("gte"),
)
return qs
@@ -212,14 +235,6 @@ def filter_search(qs, _, value):
return qs
-def filter_collection_publish(qs, _, value):
- if value == CollectionPublished.PUBLISHED:
- qs = qs.filter(is_published=True)
- elif value == CollectionPublished.HIDDEN:
- qs = qs.filter(is_published=False)
- return qs
-
-
def filter_product_type_configurable(qs, _, value):
if value == ProductTypeConfigurable.CONFIGURABLE:
qs = qs.filter(has_variants=True)
@@ -236,11 +251,11 @@ def filter_product_type(qs, _, value):
return qs
-def filter_attributes_by_product_types(qs, field, value, requestor):
+def filter_attributes_by_product_types(qs, field, value, requestor, channel_slug):
if not value:
return qs
- product_qs = Product.objects.visible_to_user(requestor)
+ product_qs = Product.objects.visible_to_user(requestor, channel_slug)
if field == "in_category":
category_id = from_global_id_strict_type(
@@ -255,7 +270,9 @@ def filter_attributes_by_product_types(qs, field, value, requestor):
product_qs = product_qs.filter(category__in=tree)
if not product_qs.user_has_access_to_all(requestor):
- product_qs = product_qs.exclude(visible_in_listings=False)
+ product_qs = product_qs.annotate_visible_in_listings(channel_slug).exclude(
+ visible_in_listings=False
+ )
elif field == "in_collection":
collection_id = from_global_id_strict_type(
@@ -331,14 +348,14 @@ class ProductStockFilterInput(graphene.InputObjectType):
class ProductFilter(django_filters.FilterSet):
- is_published = django_filters.BooleanFilter()
+ is_published = django_filters.BooleanFilter(method="filter_is_published")
collections = GlobalIDMultipleChoiceFilter(method=filter_collections)
categories = GlobalIDMultipleChoiceFilter(method=filter_categories)
has_category = django_filters.BooleanFilter(method=filter_has_category)
- price = ObjectTypeFilter(input_class=PriceRangeInput, method=filter_variant_price)
+ price = ObjectTypeFilter(input_class=PriceRangeInput, method="filter_variant_price")
minimal_price = ObjectTypeFilter(
input_class=PriceRangeInput,
- method=filter_minimal_price,
+ method="filter_minimal_price",
field_name="minimal_price_amount",
)
attributes = ListObjectTypeFilter(
@@ -368,6 +385,18 @@ class ProductFilter(django_filters.FilterSet):
"search",
]
+ def filter_variant_price(self, queryset, name, value):
+ channel_slug = get_channel_slug_from_filter_data(self.data)
+ return _filter_variant_price(queryset, name, value, channel_slug)
+
+ def filter_minimal_price(self, queryset, name, value):
+ channel_slug = get_channel_slug_from_filter_data(self.data)
+ return _filter_minimal_price(queryset, name, value, channel_slug)
+
+ def filter_is_published(self, queryset, name, value):
+ channel_slug = get_channel_slug_from_filter_data(self.data)
+ return _filter_is_published(queryset, name, value, channel_slug)
+
class ProductVariantFilter(django_filters.FilterSet):
search = django_filters.CharFilter(
@@ -382,7 +411,7 @@ class ProductVariantFilter(django_filters.FilterSet):
class CollectionFilter(django_filters.FilterSet):
published = EnumFilter(
- input_class=CollectionPublished, method=filter_collection_publish
+ input_class=CollectionPublished, method="filter_is_published"
)
search = django_filters.CharFilter(
method=filter_fields_containing_value("slug", "name")
@@ -393,6 +422,14 @@ class CollectionFilter(django_filters.FilterSet):
model = Collection
fields = ["published", "search"]
+ def filter_is_published(self, queryset, name, value):
+ channel_slug = get_channel_slug_from_filter_data(self.data)
+ if value == CollectionPublished.PUBLISHED:
+ return _filter_is_published(queryset, name, True, channel_slug)
+ elif value == CollectionPublished.HIDDEN:
+ return _filter_is_published(queryset, name, False, channel_slug)
+ return queryset
+
class CategoryFilter(django_filters.FilterSet):
search = django_filters.CharFilter(
@@ -445,14 +482,20 @@ class AttributeFilter(django_filters.FilterSet):
def filter_in_collection(self, queryset, name, value):
requestor = get_user_or_app_from_context(self.request)
- return filter_attributes_by_product_types(queryset, name, value, requestor)
+ channel_slug = get_channel_slug_from_filter_data(self.data)
+ return filter_attributes_by_product_types(
+ queryset, name, value, requestor, channel_slug
+ )
def filter_in_category(self, queryset, name, value):
requestor = get_user_or_app_from_context(self.request)
- return filter_attributes_by_product_types(queryset, name, value, requestor)
+ channel_slug = get_channel_slug_from_filter_data(self.data)
+ return filter_attributes_by_product_types(
+ queryset, name, value, requestor, channel_slug
+ )
-class ProductFilterInput(FilterInputObjectType):
+class ProductFilterInput(ChannelFilterInputObjectType):
class Meta:
filterset_class = ProductFilter
@@ -462,7 +505,7 @@ class ProductVariantFilterInput(FilterInputObjectType):
filterset_class = ProductVariantFilter
-class CollectionFilterInput(FilterInputObjectType):
+class CollectionFilterInput(ChannelFilterInputObjectType):
class Meta:
filterset_class = CollectionFilter
@@ -477,6 +520,6 @@ class ProductTypeFilterInput(FilterInputObjectType):
filterset_class = ProductTypeFilter
-class AttributeFilterInput(FilterInputObjectType):
+class AttributeFilterInput(ChannelFilterInputObjectType):
class Meta:
filterset_class = AttributeFilter
diff --git a/saleor/graphql/product/mutations/channels.py b/saleor/graphql/product/mutations/channels.py
new file mode 100644
index 0000000000..c19cdc7039
--- /dev/null
+++ b/saleor/graphql/product/mutations/channels.py
@@ -0,0 +1,426 @@
+import datetime
+from collections import defaultdict
+from typing import TYPE_CHECKING, DefaultDict, Dict, List
+
+import graphene
+from django.core.exceptions import ValidationError
+from django.db import transaction
+
+from ....core.permissions import ProductPermissions
+from ....product.error_codes import CollectionErrorCode, ProductErrorCode
+from ....product.models import (
+ CollectionChannelListing,
+ ProductChannelListing,
+ ProductVariantChannelListing,
+)
+from ....product.tasks import update_product_discounted_price_task
+from ...channel import ChannelContext
+from ...channel.mutations import BaseChannelListingMutation
+from ...channel.types import Channel
+from ...core.mutations import BaseMutation
+from ...core.scalars import PositiveDecimal
+from ...core.types.common import (
+ CollectionChannelListingError,
+ ProductChannelListingError,
+)
+from ...core.utils import get_duplicated_values
+from ...core.validators import validate_price_precision
+from ..types.products import Collection, Product, ProductVariant
+
+if TYPE_CHECKING:
+ from ....product.models import (
+ Product as ProductModel,
+ Collection as CollectionModel,
+ ProductVariant as ProductVariantModel,
+ )
+ from ....channel.models import Channel as ChannelModel
+
+ErrorType = DefaultDict[str, List[ValidationError]]
+
+
+class PublishableChannelListingInput(graphene.InputObjectType):
+ channel_id = graphene.ID(required=True, description="ID of a channel.")
+ is_published = graphene.Boolean(
+ description="Determines if object is visible to customers."
+ )
+ publication_date = graphene.types.datetime.Date(
+ description="Publication date. ISO 8601 standard."
+ )
+
+
+class ProductChannelListingAddInput(PublishableChannelListingInput):
+ visible_in_listings = graphene.Boolean(
+ description=(
+ "Determines if product is visible in product listings "
+ "(doesn't apply to product collections)."
+ )
+ )
+ is_available_for_purchase = graphene.Boolean(
+ description="Determine if product should be available for purchase.",
+ )
+ available_for_purchase_date = graphene.Date(
+ description=(
+ "A start date from which a product will be available for purchase. "
+ "When not set and isAvailable is set to True, "
+ "the current day is assumed."
+ )
+ )
+
+
+class ProductChannelListingUpdateInput(graphene.InputObjectType):
+ add_channels = graphene.List(
+ graphene.NonNull(ProductChannelListingAddInput),
+ description="List of channels to which the product should be assigned.",
+ required=False,
+ )
+ remove_channels = graphene.List(
+ graphene.NonNull(graphene.ID),
+ description="List of channels from which the product should be unassigned.",
+ required=False,
+ )
+
+
+class ProductChannelListingUpdate(BaseChannelListingMutation):
+ product = graphene.Field(Product, description="An updated product instance.")
+
+ class Arguments:
+ id = graphene.ID(required=True, description="ID of a product to update.")
+ input = ProductChannelListingUpdateInput(
+ required=True,
+ description="Fields required to create or update product channel listings.",
+ )
+
+ class Meta:
+ description = "Manage product's availability in channels."
+ permissions = (ProductPermissions.MANAGE_PRODUCTS,)
+ error_type_class = ProductChannelListingError
+ error_type_field = "product_channel_listing_errors"
+
+ @classmethod
+ def clean_available_for_purchase(cls, cleaned_input, errors: ErrorType):
+ channels_with_invalid_available_for_purchase = []
+ for add_channel in cleaned_input.get("add_channels", []):
+ is_available_for_purchase = add_channel.get("is_available_for_purchase")
+ available_for_purchase_date = add_channel.get("available_for_purchase_date")
+ if not is_available_for_purchase and available_for_purchase_date:
+ channels_with_invalid_available_for_purchase.append(
+ add_channel["channel_id"]
+ )
+ if channels_with_invalid_available_for_purchase:
+ error_msg = (
+ "Cannot set available for purchase date when"
+ " isAvailableForPurchase is false."
+ )
+ errors["available_for_purchase_date"].append(
+ ValidationError(
+ error_msg,
+ code=ProductErrorCode.INVALID.value,
+ params={"channels": channels_with_invalid_available_for_purchase},
+ )
+ )
+
+ @classmethod
+ def validate_product_without_category(cls, cleaned_input, errors: ErrorType):
+ channels_with_published_product_without_category = []
+ for add_channel in cleaned_input.get("add_channels", []):
+ if add_channel.get("is_published") is True:
+ channels_with_published_product_without_category.append(
+ add_channel["channel_id"]
+ )
+ if channels_with_published_product_without_category:
+ errors["is_published"].append(
+ ValidationError(
+ "You must select a category to be able to publish.",
+ code=ProductErrorCode.PRODUCT_WITHOUT_CATEGORY.value,
+ params={
+ "channels": channels_with_published_product_without_category
+ },
+ )
+ )
+
+ @classmethod
+ def add_channels(cls, product: "ProductModel", add_channels: List[Dict]):
+ for add_channel in add_channels:
+ channel = add_channel["channel"]
+ defaults = {"currency": channel.currency_code}
+ for field in ["is_published", "publication_date", "visible_in_listings"]:
+ if field in add_channel.keys():
+ defaults[field] = add_channel.get(field, None)
+ is_available_for_purchase = add_channel.get("is_available_for_purchase")
+ available_for_purchase_date = add_channel.get("available_for_purchase_date")
+ if is_available_for_purchase is not None:
+ if is_available_for_purchase is False:
+ defaults["available_for_purchase"] = None
+ elif (
+ is_available_for_purchase is True
+ and not available_for_purchase_date
+ ):
+ defaults["available_for_purchase"] = datetime.date.today()
+ else:
+ defaults["available_for_purchase"] = available_for_purchase_date
+ ProductChannelListing.objects.update_or_create(
+ product=product, channel=channel, defaults=defaults
+ )
+
+ @classmethod
+ def remove_channels(cls, product: "ProductModel", remove_channels: List[int]):
+ ProductChannelListing.objects.filter(
+ product=product, channel_id__in=remove_channels
+ ).delete()
+ ProductVariantChannelListing.objects.filter(
+ variant__product_id=product.pk, channel_id__in=remove_channels
+ ).delete()
+
+ @classmethod
+ @transaction.atomic()
+ def save(cls, info, product: "ProductModel", cleaned_input: Dict):
+ cls.add_channels(product, cleaned_input.get("add_channels", []))
+ cls.remove_channels(product, cleaned_input.get("remove_channels", []))
+ info.context.plugins.product_updated(product)
+
+ @classmethod
+ def perform_mutation(cls, _root, info, id, input):
+ product = cls.get_node_or_error(info, id, only_type=Product, field="id")
+ errors = defaultdict(list)
+
+ cleaned_input = cls.clean_channels(
+ info, input, errors, ProductErrorCode.DUPLICATED_INPUT_ITEM.value,
+ )
+ cls.clean_publication_date(cleaned_input)
+ cls.clean_available_for_purchase(cleaned_input, errors)
+ if not product.category:
+ cls.validate_product_without_category(cleaned_input, errors)
+ if errors:
+ raise ValidationError(errors)
+
+ cls.save(info, product, cleaned_input)
+ return ProductChannelListingUpdate(
+ product=ChannelContext(node=product, channel_slug=None)
+ )
+
+
+class ProductVariantChannelListingAddInput(graphene.InputObjectType):
+ channel_id = graphene.ID(required=True, description="ID of a channel.")
+ price = PositiveDecimal(
+ required=True, description="Price of the particular variant in channel."
+ )
+ cost_price = PositiveDecimal(description="Cost price of the variant in channel.")
+
+
+class ProductVariantChannelListingUpdate(BaseMutation):
+ variant = graphene.Field(
+ ProductVariant, description="An updated product variant instance."
+ )
+
+ class Arguments:
+ id = graphene.ID(
+ required=True, description="ID of a product variant to update."
+ )
+ input = graphene.List(
+ graphene.NonNull(ProductVariantChannelListingAddInput),
+ required=True,
+ description=(
+ "List of fields required to create or upgrade product variant ",
+ "channel listings.",
+ ),
+ )
+
+ class Meta:
+ description = "Manage product variant prices in channels."
+ permissions = (ProductPermissions.MANAGE_PRODUCTS,)
+ error_type_class = ProductChannelListingError
+ error_type_field = "product_channel_listing_errors"
+
+ @classmethod
+ def clean_channels(cls, info, input, errors: ErrorType) -> List:
+ add_channels_ids = [
+ channel_listing_data["channel_id"] for channel_listing_data in input
+ ]
+ cleaned_input = []
+
+ duplicates = get_duplicated_values(add_channels_ids)
+ if duplicates:
+ errors["channelId"].append(
+ ValidationError(
+ "Duplicated channel ID.",
+ code=ProductErrorCode.DUPLICATED_INPUT_ITEM.value,
+ params={"channels": duplicates},
+ )
+ )
+ else:
+ channels: List["ChannelModel"] = []
+ if add_channels_ids:
+ channels = cls.get_nodes_or_error(
+ add_channels_ids, "channel_id", Channel
+ )
+ for channel_listing_data, channel in zip(input, channels):
+ channel_listing_data["channel"] = channel
+ cleaned_input.append(channel_listing_data)
+ return cleaned_input
+
+ @classmethod
+ def validate_product_assigned_to_channel(
+ cls, variant: "ProductVariantModel", cleaned_input: List, errors: ErrorType
+ ):
+ channel_pks = [
+ channel_listing_data["channel"].pk for channel_listing_data in cleaned_input
+ ]
+ channels_assigned_to_product = list(
+ ProductChannelListing.objects.filter(
+ product=variant.product_id
+ ).values_list("channel_id", flat=True)
+ )
+ channels_not_assigned_to_product = set(channel_pks) - set(
+ channels_assigned_to_product
+ )
+ if channels_not_assigned_to_product:
+ channel_global_ids = []
+ for channel_listing_data in cleaned_input:
+ if (
+ channel_listing_data["channel"].pk
+ in channels_not_assigned_to_product
+ ):
+ channel_global_ids.append(channel_listing_data["channel_id"])
+ errors["input"].append(
+ ValidationError(
+ "Product not available in channels.",
+ code=ProductErrorCode.PRODUCT_NOT_ASSIGNED_TO_CHANNEL.value,
+ params={"channels": channel_global_ids},
+ )
+ )
+
+ @classmethod
+ def clean_price(cls, price, field_name, currency, channel_id, errors: ErrorType):
+ try:
+ validate_price_precision(price, currency)
+ except ValidationError as error:
+ error.code = ProductErrorCode.INVALID.value
+ error.params = {
+ "channels": [channel_id],
+ }
+ errors[field_name].append(error)
+
+ @classmethod
+ def clean_prices(cls, info, cleaned_input, errors: ErrorType) -> List:
+ for channel_listing_data in cleaned_input:
+ price = channel_listing_data.get("price")
+ cost_price = channel_listing_data.get("cost_price")
+ channel_id = channel_listing_data["channel_id"]
+ currency_code = channel_listing_data["channel"].currency_code
+
+ cls.clean_price(price, "price", currency_code, channel_id, errors)
+ cls.clean_price(cost_price, "cost_price", currency_code, channel_id, errors)
+
+ return cleaned_input
+
+ @classmethod
+ @transaction.atomic()
+ def save(cls, info, variant: "ProductVariantModel", cleaned_input: List):
+ for channel_listing_data in cleaned_input:
+ channel = channel_listing_data["channel"]
+ defaults = {"currency": channel.currency_code}
+ if "price" in channel_listing_data.keys():
+ defaults["price_amount"] = channel_listing_data.get("price", None)
+ if "cost_price" in channel_listing_data.keys():
+ defaults["cost_price_amount"] = channel_listing_data.get(
+ "cost_price", None
+ )
+ ProductVariantChannelListing.objects.update_or_create(
+ variant=variant, channel=channel, defaults=defaults,
+ )
+ update_product_discounted_price_task.delay(variant.product_id)
+ info.context.plugins.product_updated(variant.product)
+
+ @classmethod
+ def perform_mutation(cls, _root, info, id, input):
+ variant: "ProductVariantModel" = cls.get_node_or_error( # type: ignore
+ info, id, only_type=ProductVariant, field="id"
+ )
+ errors = defaultdict(list)
+
+ cleaned_input = cls.clean_channels(info, input, errors)
+ cls.validate_product_assigned_to_channel(variant, cleaned_input, errors)
+ cleaned_input = cls.clean_prices(info, cleaned_input, errors)
+
+ if errors:
+ raise ValidationError(errors)
+
+ cls.save(info, variant, cleaned_input)
+
+ return ProductVariantChannelListingUpdate(
+ variant=ChannelContext(node=variant, channel_slug=None)
+ )
+
+
+class CollectionChannelListingUpdateInput(graphene.InputObjectType):
+ add_channels = graphene.List(
+ graphene.NonNull(PublishableChannelListingInput),
+ description="List of channels to which the collection should be assigned.",
+ required=False,
+ )
+ remove_channels = graphene.List(
+ graphene.NonNull(graphene.ID),
+ description="List of channels from which the collection should be unassigned.",
+ required=False,
+ )
+
+
+class CollectionChannelListingUpdate(BaseChannelListingMutation):
+ collection = graphene.Field(
+ Collection, description="An updated collection instance."
+ )
+
+ class Arguments:
+ id = graphene.ID(required=True, description="ID of a collection to update.")
+ input = CollectionChannelListingUpdateInput(
+ required=True,
+ description=(
+ "Fields required to create or update collection channel listings."
+ ),
+ )
+
+ class Meta:
+ description = "Manage collection's availability in channels."
+ permissions = (ProductPermissions.MANAGE_PRODUCTS,)
+ error_type_class = CollectionChannelListingError
+ error_type_field = "collection_channel_listing_errors"
+
+ @classmethod
+ def add_channels(cls, collection: "CollectionModel", add_channels: List[Dict]):
+ for add_channel in add_channels:
+ defaults = {}
+ for field in ["is_published", "publication_date"]:
+ if field in add_channel.keys():
+ defaults[field] = add_channel.get(field, None)
+ CollectionChannelListing.objects.update_or_create(
+ collection=collection, channel=add_channel["channel"], defaults=defaults
+ )
+
+ @classmethod
+ def remove_channels(cls, collection: "CollectionModel", remove_channels: List[int]):
+ CollectionChannelListing.objects.filter(
+ collection=collection, channel_id__in=remove_channels
+ ).delete()
+
+ @classmethod
+ @transaction.atomic()
+ def save(cls, info, collection: "CollectionModel", cleaned_input: Dict):
+ cls.add_channels(collection, cleaned_input.get("add_channels", []))
+ cls.remove_channels(collection, cleaned_input.get("remove_channels", []))
+
+ @classmethod
+ def perform_mutation(cls, _root, info, id, input):
+ collection = cls.get_node_or_error(info, id, only_type=Collection, field="id")
+ errors = defaultdict(list)
+
+ cleaned_input = cls.clean_channels(
+ info, input, errors, CollectionErrorCode.DUPLICATED_INPUT_ITEM.value,
+ )
+ cls.clean_publication_date(cleaned_input)
+ if errors:
+ raise ValidationError(errors)
+
+ cls.save(info, collection, cleaned_input)
+ return CollectionChannelListingUpdate(
+ collection=ChannelContext(node=collection, channel_slug=None)
+ )
diff --git a/saleor/graphql/product/mutations/digital_contents.py b/saleor/graphql/product/mutations/digital_contents.py
index b5d209644b..9fea598c85 100644
--- a/saleor/graphql/product/mutations/digital_contents.py
+++ b/saleor/graphql/product/mutations/digital_contents.py
@@ -4,6 +4,7 @@ from django.core.exceptions import ValidationError
from ....core.permissions import ProductPermissions
from ....product import models
from ....product.error_codes import ProductErrorCode
+from ...channel import ChannelContext
from ...core.mutations import BaseMutation, ModelMutation
from ...core.types import Upload
from ...core.types.common import ProductError
@@ -113,7 +114,9 @@ class DigitalContentCreate(BaseMutation):
variant.digital_content = digital_content
variant.digital_content.save()
- return DigitalContentCreate(content=digital_content)
+
+ variant = ChannelContext(node=variant, channel_slug=None)
+ return DigitalContentCreate(content=digital_content, variant=variant)
class DigitalContentDelete(BaseMutation):
@@ -140,6 +143,7 @@ class DigitalContentDelete(BaseMutation):
if hasattr(variant, "digital_content"):
variant.digital_content.delete()
+ variant = ChannelContext(node=variant, channel_slug=None)
return DigitalContentDelete(variant=variant)
@@ -218,6 +222,7 @@ class DigitalContentUpdate(BaseMutation):
variant.digital_content = digital_content
variant.digital_content.save()
+ variant = ChannelContext(node=variant, channel_slug=None)
return DigitalContentUpdate(content=digital_content, variant=variant)
diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.py
index 5a31cc0106..07e97997f9 100644
--- a/saleor/graphql/product/mutations/products.py
+++ b/saleor/graphql/product/mutations/products.py
@@ -14,10 +14,10 @@ from ....core.exceptions import PermissionDenied
from ....core.permissions import ProductPermissions, ProductTypePermissions
from ....order import OrderStatus, models as order_models
from ....product import models
-from ....product.error_codes import ProductErrorCode
+from ....product.error_codes import CollectionErrorCode, ProductErrorCode
from ....product.tasks import (
- update_product_minimal_variant_price_task,
- update_products_minimal_variant_prices_of_catalogues_task,
+ update_product_discounted_price_task,
+ update_products_discounted_prices_of_catalogues_task,
update_variants_names,
)
from ....product.thumbnails import (
@@ -25,15 +25,16 @@ from ....product.thumbnails import (
create_collection_background_image_thumbnails,
create_product_thumbnails,
)
-from ....product.utils import delete_categories
+from ....product.utils import delete_categories, get_products_ids_without_variants
from ....product.utils.attributes import (
associate_attribute_values_to_instance,
generate_name_for_variant,
)
+from ...channel import ChannelContext
from ...core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation
-from ...core.scalars import PositiveDecimal, WeightScalar
+from ...core.scalars import WeightScalar
from ...core.types import SeoInput, Upload
-from ...core.types.common import ProductError
+from ...core.types.common import CollectionError, ProductError
from ...core.utils import (
clean_seo_fields,
from_global_id_strict_type,
@@ -42,7 +43,6 @@ from ...core.utils import (
validate_slug_and_generate_if_needed,
)
from ...core.utils.reordering import perform_reordering
-from ...core.validators import validate_price_precision
from ...warehouse.types import Warehouse
from ..types import (
Category,
@@ -204,8 +204,8 @@ class CollectionCreate(ModelMutation):
description = "Creates a new collection."
model = models.Collection
permissions = (ProductPermissions.MANAGE_PRODUCTS,)
- error_type_class = ProductError
- error_type_field = "product_errors"
+ error_type_class = CollectionError
+ error_type_field = "collection_errors"
@classmethod
def clean_input(cls, info, instance, data):
@@ -215,7 +215,7 @@ class CollectionCreate(ModelMutation):
instance, "name", cleaned_input
)
except ValidationError as error:
- error.code = ProductErrorCode.REQUIRED.value
+ error.code = CollectionErrorCode.REQUIRED.value
raise ValidationError({"slug": error})
if data.get("background_image"):
image_data = info.context.FILES.get(data["background_image"])
@@ -233,6 +233,13 @@ class CollectionCreate(ModelMutation):
if cleaned_input.get("background_image"):
create_collection_background_image_thumbnails.delay(instance.pk)
+ @classmethod
+ def perform_mutation(cls, _root, info, **kwargs):
+ result = super().perform_mutation(_root, info, **kwargs)
+ return CollectionCreate(
+ collection=ChannelContext(node=result.collection, channel_slug=None)
+ )
+
class CollectionUpdate(CollectionCreate):
class Arguments:
@@ -245,8 +252,8 @@ class CollectionUpdate(CollectionCreate):
description = "Updates a collection."
model = models.Collection
permissions = (ProductPermissions.MANAGE_PRODUCTS,)
- error_type_class = ProductError
- error_type_field = "product_errors"
+ error_type_class = CollectionError
+ error_type_field = "collection_errors"
@classmethod
def save(cls, info, instance, cleaned_input):
@@ -263,8 +270,15 @@ class CollectionDelete(ModelDeleteMutation):
description = "Deletes a collection."
model = models.Collection
permissions = (ProductPermissions.MANAGE_PRODUCTS,)
- error_type_class = ProductError
- error_type_field = "product_errors"
+ error_type_class = CollectionError
+ error_type_field = "collection_errors"
+
+ @classmethod
+ def perform_mutation(cls, _root, info, **kwargs):
+ result = super().perform_mutation(_root, info, **kwargs)
+ return CollectionDelete(
+ collection=ChannelContext(node=result.collection, channel_slug=None)
+ )
class MoveProductInput(graphene.InputObjectType):
@@ -289,8 +303,8 @@ class CollectionReorderProducts(BaseMutation):
class Meta:
description = "Reorder the products of a collection."
permissions = (ProductPermissions.MANAGE_PRODUCTS,)
- error_type_class = ProductError
- error_type_field = "product_errors"
+ error_type_class = CollectionError
+ error_type_field = "collection_errors"
class Arguments:
collection_id = graphene.Argument(
@@ -339,7 +353,7 @@ class CollectionReorderProducts(BaseMutation):
{
"moves": ValidationError(
f"Couldn't resolve to a product: {move_info.product_id}",
- code=ProductErrorCode.NOT_FOUND,
+ code=CollectionErrorCode.NOT_FOUND.value,
)
}
)
@@ -347,6 +361,7 @@ class CollectionReorderProducts(BaseMutation):
with transaction.atomic():
perform_reordering(m2m_related_field, operations)
+ collection = ChannelContext(node=collection, channel_slug=None)
return CollectionReorderProducts(collection=collection)
@@ -366,8 +381,8 @@ class CollectionAddProducts(BaseMutation):
class Meta:
description = "Adds products to a collection."
permissions = (ProductPermissions.MANAGE_PRODUCTS,)
- error_type_class = ProductError
- error_type_field = "product_errors"
+ error_type_class = CollectionError
+ error_type_field = "collection_errors"
@classmethod
@transaction.atomic()
@@ -376,13 +391,31 @@ class CollectionAddProducts(BaseMutation):
info, collection_id, field="collection_id", only_type=Collection
)
products = cls.get_nodes_or_error(products, "products", Product)
+ cls.clean_products(products)
collection.products.add(*products)
if collection.sale_set.exists():
# Updated the db entries, recalculating discounts of affected products
- update_products_minimal_variant_prices_of_catalogues_task.delay(
- product_ids=[p.pk for p in products]
+ update_products_discounted_prices_of_catalogues_task.delay(
+ product_ids=[pq.pk for pq in products]
+ )
+ return CollectionAddProducts(
+ collection=ChannelContext(node=collection, channel_slug=None)
+ )
+
+ @classmethod
+ def clean_products(cls, products):
+ products_ids_without_variants = get_products_ids_without_variants(products)
+ if products_ids_without_variants:
+ code = CollectionErrorCode.CANNOT_MANAGE_PRODUCT_WITHOUT_VARIANT.value
+ raise ValidationError(
+ {
+ "products": ValidationError(
+ "Cannot manage products without variants.",
+ code=code,
+ params={"products": products_ids_without_variants},
+ )
+ }
)
- return CollectionAddProducts(collection=collection)
class CollectionRemoveProducts(BaseMutation):
@@ -401,8 +434,8 @@ class CollectionRemoveProducts(BaseMutation):
class Meta:
description = "Remove products from a collection."
permissions = (ProductPermissions.MANAGE_PRODUCTS,)
- error_type_class = ProductError
- error_type_field = "product_errors"
+ error_type_class = CollectionError
+ error_type_field = "collection_errors"
@classmethod
def perform_mutation(cls, _root, info, collection_id, products):
@@ -413,10 +446,12 @@ class CollectionRemoveProducts(BaseMutation):
collection.products.remove(*products)
if collection.sale_set.exists():
# Updated the db entries, recalculating discounts of affected products
- update_products_minimal_variant_prices_of_catalogues_task.delay(
+ update_products_discounted_prices_of_catalogues_task.delay(
product_ids=[p.pk for p in products]
)
- return CollectionRemoveProducts(collection=collection)
+ return CollectionRemoveProducts(
+ collection=ChannelContext(node=collection, channel_slug=None)
+ )
class AttributeValueInput(InputObjectType):
@@ -433,9 +468,6 @@ class AttributeValueInput(InputObjectType):
class ProductInput(graphene.InputObjectType):
attributes = graphene.List(AttributeValueInput, description="List of attributes.")
- publication_date = graphene.types.datetime.Date(
- description="Publication date. ISO 8601 standard."
- )
category = graphene.ID(description="ID of the product's category.", name="category")
charge_taxes = graphene.Boolean(
description="Determine if taxes are being charged for the product."
@@ -447,39 +479,11 @@ class ProductInput(graphene.InputObjectType):
)
description = graphene.String(description="Product description (HTML/text).")
description_json = graphene.JSONString(description="Product description (JSON).")
- is_published = graphene.Boolean(
- description="Determines if product is visible to customers."
- )
name = graphene.String(description="Product name.")
slug = graphene.String(description="Product slug.")
tax_code = graphene.String(description="Tax rate for enabled tax gateway.")
seo = SeoInput(description="Search engine optimization fields.")
weight = WeightScalar(description="Weight of the Product.", required=False)
- sku = graphene.String(
- description=(
- "Stock keeping unit of a product. Note: this field is only used if "
- "a product doesn't use variants."
- )
- )
- track_inventory = graphene.Boolean(
- description=(
- "Determines if the inventory of this product should be tracked. If false, "
- "the quantity won't change when customers buy this item. Note: this field "
- "is only used if a product doesn't use variants."
- )
- )
- base_price = PositiveDecimal(
- description=(
- "Default price for product variant. "
- "Note: this field is only used if a product doesn't use variants."
- )
- )
- visible_in_listings = graphene.Boolean(
- description=(
- "Determines if product is visible in product listings "
- "(doesn't apply to product collections)."
- )
- )
rating = graphene.Float(description="Defines the product rating value.")
@@ -496,14 +500,6 @@ class ProductCreateInput(ProductInput):
name="productType",
required=True,
)
- stocks = graphene.List(
- graphene.NonNull(StockInput),
- description=(
- "Stocks of a product available for sale. Note: this field is "
- "only used if a product doesn't use variants."
- ),
- required=False,
- )
T_INPUT_MAP = List[Tuple[models.Attribute, List[str]]]
@@ -773,13 +769,6 @@ class ProductCreate(ModelMutation):
}
)
- base_price = cleaned_input.get("base_price")
- try:
- validate_price_precision(base_price, instance.currency)
- except ValidationError as error:
- error.code = ProductErrorCode.INVALID.value
- raise ValidationError({"base_price": error})
-
# Attributes are provided as list of `AttributeValueInput` objects.
# We need to transform them into the format they're stored in the
# `Product` model, which is HStore field that maps attribute's PK to
@@ -816,68 +805,9 @@ class ProductCreate(ModelMutation):
except ValidationError as exc:
raise ValidationError({"attributes": exc})
- is_published = cleaned_input.get("is_published")
- publication_date = cleaned_input.get("publication_date")
- if is_published and not publication_date:
- cleaned_input["publication_date"] = datetime.date.today()
- category = cleaned_input.get("category")
- if not category and is_published:
- raise ValidationError(
- {
- "category": ValidationError(
- "You must select a category to be able to publish",
- code=ProductErrorCode.REQUIRED,
- )
- }
- )
-
clean_seo_fields(cleaned_input)
- cls.clean_sku(product_type, cleaned_input)
- stocks = cleaned_input.get("stocks")
- if stocks:
- cls.check_for_duplicates_in_stocks(stocks)
return cleaned_input
- @classmethod
- def clean_sku(cls, product_type, cleaned_input):
- """Validate SKU input field.
-
- When creating products that don't use variants, SKU is required in
- the input in order to create the default variant underneath.
- See the documentation for `has_variants` field for details:
- http://docs.getsaleor.com/en/latest/architecture/products.html#product-types
- """
- if product_type and not product_type.has_variants:
- input_sku = cleaned_input.get("sku")
- if not input_sku:
- raise ValidationError(
- {
- "sku": ValidationError(
- "This field cannot be blank.",
- code=ProductErrorCode.REQUIRED,
- )
- }
- )
- elif models.ProductVariant.objects.filter(sku=input_sku).exists():
- raise ValidationError(
- {
- "sku": ValidationError(
- "Product with this SKU already exists.",
- code=ProductErrorCode.ALREADY_EXISTS,
- )
- }
- )
-
- @classmethod
- def check_for_duplicates_in_stocks(cls, stocks_data):
- warehouse_ids = [stock["warehouse"] for stock in stocks_data]
- duplicates = get_duplicated_values(warehouse_ids)
- if duplicates:
- error_msg = "Duplicated warehouse ID: {}".format(duplicates.join(", "))
- raise ValidationError(
- {"stocks": ValidationError(error_msg, code=ProductErrorCode.UNIQUE)}
- )
-
@classmethod
def get_instance(cls, info, **data):
"""Prefetch related fields that are needed to process the mutation."""
@@ -900,36 +830,11 @@ class ProductCreate(ModelMutation):
@transaction.atomic
def save(cls, info, instance, cleaned_input):
instance.save()
- if not instance.product_type.has_variants:
- site_settings = info.context.site.settings
- track_inventory = cleaned_input.get(
- "track_inventory", site_settings.track_inventory_by_default
- )
- sku = cleaned_input.get("sku")
- variant_price = cleaned_input.get("base_price")
-
- variant = models.ProductVariant.objects.create(
- product=instance,
- track_inventory=track_inventory,
- sku=sku,
- price_amount=variant_price,
- )
- stocks = cleaned_input.get("stocks")
- if stocks:
- cls.create_variant_stocks(variant, stocks)
attributes = cleaned_input.get("attributes")
if attributes:
AttributeAssignmentMixin.save(instance, attributes)
- @classmethod
- def create_variant_stocks(cls, variant, stocks):
- warehouse_ids = [stock["warehouse"] for stock in stocks]
- warehouses = cls.get_nodes_or_error(
- warehouse_ids, "warehouse", only_type=Warehouse
- )
- create_stocks(variant, stocks, warehouses)
-
@classmethod
def _save_m2m(cls, info, instance, cleaned_data):
collections = cleaned_data.get("collections", None)
@@ -939,7 +844,15 @@ class ProductCreate(ModelMutation):
@classmethod
def perform_mutation(cls, _root, info, **data):
response = super().perform_mutation(_root, info, **data)
- info.context.plugins.product_created(response.product)
+ product = getattr(response, cls._meta.return_field_name)
+ info.context.plugins.product_created(product)
+
+ # Wrap product instance with ChannelContext in response
+ setattr(
+ response,
+ cls._meta.return_field_name,
+ ChannelContext(node=product, channel_slug=None),
+ )
return response
@@ -957,44 +870,10 @@ class ProductUpdate(ProductCreate):
error_type_class = ProductError
error_type_field = "product_errors"
- @classmethod
- def clean_sku(cls, product_type, cleaned_input):
- input_sku = cleaned_input.get("sku")
- if (
- not product_type.has_variants
- and input_sku
- and models.ProductVariant.objects.filter(sku=input_sku).exists()
- ):
- raise ValidationError(
- {
- "sku": ValidationError(
- "Product with this SKU already exists.",
- code=ProductErrorCode.ALREADY_EXISTS,
- )
- }
- )
-
@classmethod
@transaction.atomic
def save(cls, info, instance, cleaned_input):
instance.save()
- if not instance.product_type.has_variants:
- variant = instance.variants.first()
- update_fields = []
- if "track_inventory" in cleaned_input:
- variant.track_inventory = cleaned_input["track_inventory"]
- update_fields.append("track_inventory")
- if "sku" in cleaned_input:
- variant.sku = cleaned_input["sku"]
- update_fields.append("sku")
- if "base_price" in cleaned_input:
- variant.price_amount = cleaned_input["base_price"]
- update_fields.append("price_amount")
- if update_fields:
- variant.save(update_fields=update_fields)
- # Recalculate the "minimal variant price"
- update_product_minimal_variant_price_task.delay(instance.pk)
-
attributes = cleaned_input.get("attributes")
if attributes:
AttributeAssignmentMixin.save(instance, attributes)
@@ -1012,6 +891,11 @@ class ProductDelete(ModelDeleteMutation):
error_type_class = ProductError
error_type_field = "product_errors"
+ @classmethod
+ def success_response(cls, instance):
+ instance = ChannelContext(node=instance, channel_slug=None)
+ return super().success_response(instance)
+
@classmethod
def perform_mutation(cls, _root, info, **data):
node_id = data.get("id")
@@ -1038,8 +922,6 @@ class ProductVariantInput(graphene.InputObjectType):
required=False,
description="List of attributes specific to this variant.",
)
- cost_price = PositiveDecimal(description="Cost price of the variant.")
- price = PositiveDecimal(description="Price of the particular variant.")
sku = graphene.String(description="Stock keeping unit.")
track_inventory = graphene.Boolean(
description=(
@@ -1124,34 +1006,6 @@ class ProductVariantCreate(ModelMutation):
}
)
- if "cost_price" in cleaned_input:
- cost_price = cleaned_input.pop("cost_price")
- try:
- validate_price_precision(cost_price, instance.currency)
- except ValidationError as error:
- error.code = ProductErrorCode.INVALID.value
- raise ValidationError({"cost_price": error})
- cleaned_input["cost_price_amount"] = cost_price
-
- price = cleaned_input.get("price")
- if price is None and instance.price is None:
- raise ValidationError(
- {
- "price": ValidationError(
- "Variant price is required.",
- code=ProductErrorCode.REQUIRED.value,
- )
- }
- )
-
- if "price" in cleaned_input:
- try:
- validate_price_precision(price, instance.currency)
- except ValidationError as error:
- error.code = ProductErrorCode.INVALID.value
- raise ValidationError({"price": error})
- cleaned_input["price_amount"] = price
-
stocks = cleaned_input.get("stocks")
if stocks:
cls.check_for_duplicates_in_stocks(stocks)
@@ -1202,7 +1056,11 @@ class ProductVariantCreate(ModelMutation):
if duplicates:
error_msg = "Duplicated warehouse ID: {}".format(", ".join(duplicates))
raise ValidationError(
- {"stocks": ValidationError(error_msg, code=ProductErrorCode.UNIQUE)}
+ {
+ "stocks": ValidationError(
+ error_msg, code=ProductErrorCode.UNIQUE.value
+ )
+ }
)
@classmethod
@@ -1234,8 +1092,8 @@ class ProductVariantCreate(ModelMutation):
if not instance.product.default_variant:
instance.product.default_variant = instance
instance.product.save(update_fields=["default_variant", "updated_at"])
- # Recalculate the "minimal variant price" for the parent product
- update_product_minimal_variant_price_task.delay(instance.product_id)
+ # Recalculate the "discounted price" for the parent product
+ update_product_discounted_price_task.delay(instance.product_id)
stocks = cleaned_input.get("stocks")
if stocks:
cls.create_variant_stocks(instance, stocks)
@@ -1255,6 +1113,11 @@ class ProductVariantCreate(ModelMutation):
)
create_stocks(variant, stocks, warehouses)
+ @classmethod
+ def success_response(cls, instance):
+ instance = ChannelContext(node=instance, channel_slug=None)
+ return super().success_response(instance)
+
class ProductVariantUpdate(ProductVariantCreate):
class Arguments:
@@ -1305,13 +1168,14 @@ class ProductVariantDelete(ModelDeleteMutation):
@classmethod
def success_response(cls, instance):
- # Update the "minimal_variant_prices" of the parent product
- update_product_minimal_variant_price_task.delay(instance.product_id)
+ # Update the "discounted_prices" of the parent product
+ update_product_discounted_price_task.delay(instance.product_id)
product = models.Product.objects.get(id=instance.product_id)
# if the product default variant has been removed set the new one
if not product.default_variant:
product.default_variant = product.variants.first()
product.save(update_fields=["default_variant"])
+ instance = ChannelContext(node=instance, channel_slug=None)
return super().success_response(instance)
@classmethod
@@ -1520,11 +1384,13 @@ class ProductImageCreate(BaseMutation):
product = cls.get_node_or_error(
info, data["product"], field="product", only_type=Product
)
+
image_data = info.context.FILES.get(data["image"])
validate_image_file(image_data, "image")
image = product.images.create(image=image_data, alt=data.get("alt", ""))
create_product_thumbnails.delay(image.pk)
+ product = ChannelContext(node=product, channel_slug=None)
return ProductImageCreate(product=product, image=image)
@@ -1556,6 +1422,7 @@ class ProductImageUpdate(BaseMutation):
if alt is not None:
image.alt = alt
image.save(update_fields=["alt"])
+ product = ChannelContext(node=product, channel_slug=None)
return ProductImageUpdate(product=product, image=image)
@@ -1616,6 +1483,7 @@ class ProductImageReorder(BaseMutation):
image.sort_order = order
image.save(update_fields=["sort_order"])
+ product = ChannelContext(node=product, channel_slug=None)
return ProductImageReorder(product=product, images=images)
@@ -1664,6 +1532,7 @@ class ProductVariantSetDefault(BaseMutation):
product.default_variant = variant
product.save(update_fields=["default_variant", "updated_at"])
info.context.plugins.product_updated(product)
+ product = ChannelContext(node=product, channel_slug=None)
return ProductVariantSetDefault(product=product)
@@ -1733,6 +1602,7 @@ class ProductVariantReorder(BaseMutation):
product.save(update_fields=["updated_at"])
info.context.plugins.product_updated(product)
+ product = ChannelContext(node=product, channel_slug=None)
return ProductVariantReorder(product=product)
@@ -1755,7 +1625,8 @@ class ProductImageDelete(BaseMutation):
image_id = image.id
image.delete()
image.id = image_id
- return ProductImageDelete(product=image.product, image=image)
+ product = ChannelContext(node=image.product, channel_slug=None)
+ return ProductImageDelete(product=product, image=image)
class VariantImageAssign(BaseMutation):
@@ -1798,6 +1669,7 @@ class VariantImageAssign(BaseMutation):
)
}
)
+ variant = ChannelContext(node=variant, channel_slug=None)
return VariantImageAssign(product_variant=variant, image=image)
@@ -1843,61 +1715,5 @@ class VariantImageUnassign(BaseMutation):
else:
variant_image.delete()
+ variant = ChannelContext(node=variant, channel_slug=None)
return VariantImageUnassign(product_variant=variant, image=image)
-
-
-class ProductSetAvailabilityForPurchase(BaseMutation):
- product = graphene.Field(Product)
-
- class Arguments:
- product_id = graphene.ID(
- required=True,
- description=(
- "Id of product that availability for purchase should be changed."
- ),
- )
- is_available = graphene.Boolean(
- description="Determine if product should be available for purchase.",
- required=True,
- )
- start_date = graphene.Date(
- description=(
- "A start date from which a product will be available for purchase. "
- "When not set and isAvailable is set to True, "
- "the current day is assumed."
- ),
- required=False,
- )
-
- class Meta:
- description = "Set product availability for purchase date."
- permissions = (ProductPermissions.MANAGE_PRODUCTS,)
- error_type_class = ProductError
- error_type_field = "product_errors"
-
- @classmethod
- def perform_mutation(cls, _root, info, **data):
- product = cls.get_node_or_error(info, data.get("product_id"), only_type=Product)
- is_available = data.get("is_available")
- start_date = data.get("start_date")
-
- if start_date and not is_available:
- raise ValidationError(
- {
- "start_date": ValidationError(
- "Cannot set start date when isAvailable is false.",
- code=ProductErrorCode.INVALID,
- )
- }
- )
-
- if not is_available:
- product.available_for_purchase = None
- elif is_available and not start_date:
- product.available_for_purchase = datetime.date.today()
- else:
- product.available_for_purchase = start_date
-
- product.save(update_fields=["available_for_purchase", "updated_at"])
- info.context.plugins.product_updated(product)
- return ProductSetAvailabilityForPurchase(product=product)
diff --git a/saleor/graphql/product/resolvers.py b/saleor/graphql/product/resolvers.py
index 502015c099..c918b8982f 100644
--- a/saleor/graphql/product/resolvers.py
+++ b/saleor/graphql/product/resolvers.py
@@ -1,7 +1,21 @@
+from typing import Union
+
from django.db.models import Sum
+from promise import Promise
+from ...checkout.models import CheckoutLine
from ...order import OrderStatus
+from ...order.models import OrderLine
from ...product import models
+from ..channel import ChannelContext, ChannelQsContext
+from ..channel.dataloaders import (
+ ChannelByCheckoutLineIDLoader,
+ ChannelByOrderLineIdLoader,
+)
+from ..product.dataloaders import (
+ ProductChannelListingByProductIdAndChannelSlugLoader,
+ ProductVariantByIdLoader,
+)
from ..utils import get_database_id, get_user_or_app_from_context
from ..utils.filters import filter_by_period
from .filters import filter_products_by_stock_availability
@@ -24,49 +38,83 @@ def resolve_categories(info, level=None, **_kwargs):
return qs.distinct()
-def resolve_collection_by_slug(info, slug):
- requestor = get_user_or_app_from_context(info.context)
+def resolve_collection_by_id(info, id, channel_slug, requestor):
return (
- models.Collection.objects.visible_to_user(requestor).filter(slug=slug).first()
+ models.Collection.objects.visible_to_user(requestor, channel_slug=channel_slug)
+ .filter(id=id)
+ .first()
)
-def resolve_collections(info, **_kwargs):
+def resolve_collection_by_slug(info, slug, channel_slug, requestor):
+ return (
+ models.Collection.objects.visible_to_user(requestor, channel_slug)
+ .filter(slug=slug)
+ .first()
+ )
+
+
+def resolve_collections(info, channel_slug):
user = info.context.user
- return models.Collection.objects.visible_to_user(user)
+ qs = models.Collection.objects.visible_to_user(user, channel_slug)
+
+ return ChannelQsContext(qs=qs, channel_slug=channel_slug)
-def resolve_digital_contents(info):
+def resolve_digital_contents(_info):
return models.DigitalContent.objects.all()
-def resolve_product_by_slug(info, slug):
- requestor = get_user_or_app_from_context(info.context)
- return models.Product.objects.visible_to_user(requestor).filter(slug=slug).first()
+def resolve_product_by_id(info, id, channel_slug, requestor):
+ return (
+ models.Product.objects.visible_to_user(requestor, channel_slug=channel_slug)
+ .filter(id=id)
+ .first()
+ )
-def resolve_products(info, stock_availability=None, **_kwargs):
- user = get_user_or_app_from_context(info.context)
- qs = models.Product.objects.visible_to_user(user)
+def resolve_product_by_slug(info, product_slug, channel_slug, requestor):
+ return (
+ models.Product.objects.visible_to_user(requestor, channel_slug=channel_slug)
+ .filter(slug=product_slug)
+ .first()
+ )
+
+def resolve_products(
+ info, requestor, stock_availability=None, channel_slug=None, **_kwargs
+) -> ChannelQsContext:
+ qs = models.Product.objects.visible_to_user(requestor, channel_slug)
if stock_availability:
qs = filter_products_by_stock_availability(qs, stock_availability)
+ if not qs.user_has_access_to_all(requestor):
+ qs = qs.annotate_visible_in_listings(channel_slug).exclude(
+ visible_in_listings=False
+ )
+ return ChannelQsContext(qs=qs.distinct(), channel_slug=channel_slug)
- if not qs.user_has_access_to_all(user):
- qs = qs.exclude(visible_in_listings=False)
- return qs.distinct()
+def resolve_variant_by_id(info, id, channel_slug, requestor):
+ visible_products = models.Product.objects.visible_to_user(
+ requestor, channel_slug
+ ).values_list("pk", flat=True)
+ qs = models.ProductVariant.objects.filter(product__id__in=visible_products)
+ return qs.filter(pk=id).first()
def resolve_product_types(info, **_kwargs):
return models.ProductType.objects.all()
-def resolve_product_variant_by_sku(info, sku):
- requestor = get_user_or_app_from_context(info.context)
- visible_products = models.Product.objects.visible_to_user(requestor).values_list(
- "pk", flat=True
- )
+def resolve_product_variant_by_sku(
+ info, sku, channel_slug, requestor, requestor_has_access_to_all
+):
+ visible_products = models.Product.objects.visible_to_user(requestor, channel_slug)
+ if not requestor_has_access_to_all:
+ visible_products = visible_products.annotate_visible_in_listings(
+ channel_slug
+ ).exclude(visible_in_listings=False)
+
return (
models.ProductVariant.objects.filter(product__id__in=visible_products)
.filter(sku=sku)
@@ -74,24 +122,23 @@ def resolve_product_variant_by_sku(info, sku):
)
-def resolve_product_variants(info, ids=None):
- user = get_user_or_app_from_context(info.context)
-
- visible_products = models.Product.objects.visible_to_user(user).values_list(
- "pk", flat=True
- )
- if not visible_products.user_has_access_to_all(user):
- visible_products = visible_products.exclude(visible_in_listings=False)
+def resolve_product_variants(
+ info, requestor_has_access_to_all, requestor, ids=None, channel_slug=None
+) -> ChannelQsContext:
+ visible_products = models.Product.objects.visible_to_user(requestor, channel_slug)
+ if not requestor_has_access_to_all:
+ visible_products = visible_products.annotate_visible_in_listings(
+ channel_slug
+ ).exclude(visible_in_listings=False)
qs = models.ProductVariant.objects.filter(product__id__in=visible_products)
if ids:
db_ids = [get_database_id(info, node_id, "ProductVariant") for node_id in ids]
qs = qs.filter(pk__in=db_ids)
-
- return qs
+ return ChannelQsContext(qs=qs, channel_slug=channel_slug)
-def resolve_report_product_sales(period):
+def resolve_report_product_sales(period, channel_slug) -> ChannelQsContext:
qs = models.ProductVariant.objects.all()
# exclude draft and canceled orders
@@ -102,5 +149,46 @@ def resolve_report_product_sales(period):
qs = filter_by_period(qs, period, "order_lines__order__created")
qs = qs.annotate(quantity_ordered=Sum("order_lines__quantity"))
- qs = qs.filter(quantity_ordered__isnull=False)
- return qs.order_by("-quantity_ordered")
+ qs = qs.filter(
+ quantity_ordered__isnull=False, order_lines__order__channel__slug=channel_slug
+ )
+ qs = qs.order_by("-quantity_ordered")
+ return ChannelQsContext(qs=qs, channel_slug=channel_slug)
+
+
+def resolve_variant(
+ info,
+ root: Union[CheckoutLine, OrderLine],
+ channel_dataloader: Union[
+ ChannelByCheckoutLineIDLoader, ChannelByOrderLineIdLoader
+ ],
+):
+ context = info.context
+ if not root.variant_id:
+ return None
+
+ def requestor_has_access_to_variant(data):
+ variant, channel = data
+
+ def product_is_available(product_channel_listing):
+ if not product_channel_listing:
+ return None
+ requester = get_user_or_app_from_context(context)
+ visible_in_listings = product_channel_listing.visible_in_listings
+ requestor_has_access_to_all = models.Product.objects.user_has_access_to_all(
+ requester
+ )
+ if visible_in_listings or requestor_has_access_to_all:
+ return ChannelContext(node=variant, channel_slug=channel.slug)
+ return None
+
+ return (
+ ProductChannelListingByProductIdAndChannelSlugLoader(context)
+ .load((variant.product_id, channel.slug))
+ .then(product_is_available)
+ )
+
+ variant = ProductVariantByIdLoader(context).load(root.variant_id)
+ channel = channel_dataloader.load(root.id)
+
+ return Promise.all([variant, channel]).then(requestor_has_access_to_variant)
diff --git a/saleor/graphql/product/schema.py b/saleor/graphql/product/schema.py
index e83a3b777f..b6a7d7c4cb 100644
--- a/saleor/graphql/product/schema.py
+++ b/saleor/graphql/product/schema.py
@@ -1,8 +1,15 @@
import graphene
from ...core.permissions import ProductPermissions
+from ...product import models
+from ..channel import ChannelContext
+from ..channel.utils import get_default_channel_slug_or_graphql_error
from ..core.enums import ReportingPeriod
-from ..core.fields import FilterInputConnectionField, PrefetchingConnectionField
+from ..core.fields import (
+ ChannelContextFilterConnectionField,
+ FilterInputConnectionField,
+ PrefetchingConnectionField,
+)
from ..core.validators import validate_one_of_args_is_in_query
from ..decorators import permission_required
from ..translations.mutations import (
@@ -13,13 +20,12 @@ from ..translations.mutations import (
ProductTranslate,
ProductVariantTranslate,
)
+from ..utils import get_user_or_app_from_context
from .bulk_mutations.attributes import AttributeBulkDelete, AttributeValueBulkDelete
from .bulk_mutations.products import (
CategoryBulkDelete,
CollectionBulkDelete,
- CollectionBulkPublish,
ProductBulkDelete,
- ProductBulkPublish,
ProductImageBulkDelete,
ProductTypeBulkDelete,
ProductVariantBulkCreate,
@@ -49,6 +55,11 @@ from .mutations.attributes import (
AttributeValueUpdate,
ProductTypeReorderAttributes,
)
+from .mutations.channels import (
+ CollectionChannelListingUpdate,
+ ProductChannelListingUpdate,
+ ProductVariantChannelListingUpdate,
+)
from .mutations.digital_contents import (
DigitalContentCreate,
DigitalContentDelete,
@@ -71,7 +82,6 @@ from .mutations.products import (
ProductImageDelete,
ProductImageReorder,
ProductImageUpdate,
- ProductSetAvailabilityForPurchase,
ProductTypeCreate,
ProductTypeDelete,
ProductTypeUpdate,
@@ -88,15 +98,18 @@ from .resolvers import (
resolve_attributes,
resolve_categories,
resolve_category_by_slug,
+ resolve_collection_by_id,
resolve_collection_by_slug,
resolve_collections,
resolve_digital_contents,
+ resolve_product_by_id,
resolve_product_by_slug,
resolve_product_types,
resolve_product_variant_by_sku,
resolve_product_variants,
resolve_products,
resolve_report_product_sales,
+ resolve_variant_by_id,
)
from .sorters import (
AttributeSortingInput,
@@ -160,21 +173,30 @@ class ProductQueries(graphene.ObjectType):
Collection,
id=graphene.Argument(graphene.ID, description="ID of the collection.",),
slug=graphene.Argument(graphene.String, description="Slug of the category"),
+ channel=graphene.String(
+ description="Slug of a channel for which the data should be returned."
+ ),
description="Look up a collection by ID.",
)
- collections = FilterInputConnectionField(
+ collections = ChannelContextFilterConnectionField(
Collection,
filter=CollectionFilterInput(description="Filtering options for collections."),
sort_by=CollectionSortingInput(description="Sort collections."),
description="List of the shop's collections.",
+ channel=graphene.String(
+ description="Slug of a channel for which the data should be returned."
+ ),
)
product = graphene.Field(
Product,
id=graphene.Argument(graphene.ID, description="ID of the product.",),
- slug=graphene.Argument(graphene.String, description="Slug of the category"),
+ slug=graphene.Argument(graphene.String, description="Slug of the product."),
+ channel=graphene.String(
+ description="Slug of a channel for which the data should be returned."
+ ),
description="Look up a product by ID.",
)
- products = FilterInputConnectionField(
+ products = ChannelContextFilterConnectionField(
Product,
filter=ProductFilterInput(description="Filtering options for products."),
sort_by=ProductOrder(description="Sort products."),
@@ -185,6 +207,9 @@ class ProductQueries(graphene.ObjectType):
"field instead. This field will be removed after 2020-07-31."
),
),
+ channel=graphene.String(
+ description="Slug of a channel for which the data should be returned."
+ ),
description="List of the shop's products.",
)
product_type = graphene.Field(
@@ -208,23 +233,33 @@ class ProductQueries(graphene.ObjectType):
sku=graphene.Argument(
graphene.String, description="Sku of the product variant."
),
+ channel=graphene.String(
+ description="Slug of a channel for which the data should be returned."
+ ),
description="Look up a product variant by ID or SKU.",
)
- product_variants = FilterInputConnectionField(
+ product_variants = ChannelContextFilterConnectionField(
ProductVariant,
ids=graphene.List(
graphene.ID, description="Filter product variants by given IDs."
),
+ channel=graphene.String(
+ description="Slug of a channel for which the data should be returned."
+ ),
filter=ProductVariantFilterInput(
description="Filtering options for product variant."
),
description="List of product variants.",
)
- report_product_sales = PrefetchingConnectionField(
+ report_product_sales = ChannelContextFilterConnectionField(
ProductVariant,
period=graphene.Argument(
ReportingPeriod, required=True, description="Span of time."
),
+ channel=graphene.String(
+ description="Slug of a channel for which the data should be returned.",
+ required=True,
+ ),
description="List of top selling products.",
)
@@ -237,22 +272,43 @@ class ProductQueries(graphene.ObjectType):
def resolve_categories(self, info, level=None, **kwargs):
return resolve_categories(info, level=level, **kwargs)
- def resolve_category(self, info, id=None, slug=None):
+ def resolve_category(self, info, id=None, slug=None, **kwargs):
validate_one_of_args_is_in_query("id", id, "slug", slug)
if id:
return graphene.Node.get_node_from_global_id(info, id, Category)
if slug:
return resolve_category_by_slug(slug=slug)
- def resolve_collection(self, info, id=None, slug=None):
+ def resolve_collection(self, info, id=None, slug=None, channel=None, **_kwargs):
validate_one_of_args_is_in_query("id", id, "slug", slug)
+ requestor = get_user_or_app_from_context(info.context)
+
+ requestor_has_access_to_all = models.Collection.objects.user_has_access_to_all(
+ requestor
+ )
+ if channel is None and not requestor_has_access_to_all:
+ channel = get_default_channel_slug_or_graphql_error()
if id:
- return graphene.Node.get_node_from_global_id(info, id, Collection)
- if slug:
- return resolve_collection_by_slug(info, slug=slug)
+ _, id = graphene.Node.from_global_id(id)
+ collection = resolve_collection_by_id(info, id, channel, requestor)
+ else:
+ collection = resolve_collection_by_slug(
+ info, slug=slug, channel_slug=channel, requestor=requestor
+ )
+ return (
+ ChannelContext(node=collection, channel_slug=channel)
+ if collection
+ else None
+ )
- def resolve_collections(self, info, **kwargs):
- return resolve_collections(info, **kwargs)
+ def resolve_collections(self, info, channel=None, *_args, **_kwargs):
+ requestor = get_user_or_app_from_context(info.context)
+ requestor_has_access_to_all = models.Collection.objects.user_has_access_to_all(
+ requestor
+ )
+ if channel is None and not requestor_has_access_to_all:
+ channel = get_default_channel_slug_or_graphql_error()
+ return resolve_collections(info, channel)
@permission_required(ProductPermissions.MANAGE_PRODUCTS)
def resolve_digital_content(self, info, id):
@@ -262,34 +318,84 @@ class ProductQueries(graphene.ObjectType):
def resolve_digital_contents(self, info, **_kwargs):
return resolve_digital_contents(info)
- def resolve_product(self, info, id=None, slug=None):
+ def resolve_product(self, info, id=None, slug=None, channel=None, **_kwargs):
validate_one_of_args_is_in_query("id", id, "slug", slug)
+ requestor = get_user_or_app_from_context(info.context)
+ requestor_has_access_to_all = models.Collection.objects.user_has_access_to_all(
+ requestor
+ )
+
+ if channel is None and not requestor_has_access_to_all:
+ channel = get_default_channel_slug_or_graphql_error()
if id:
- return graphene.Node.get_node_from_global_id(info, id, Product)
- if slug:
- return resolve_product_by_slug(info, slug=slug)
+ _, id = graphene.Node.from_global_id(id)
+ product = resolve_product_by_id(
+ info, id, channel_slug=channel, requestor=requestor
+ )
+ else:
+ product = resolve_product_by_slug(
+ info, product_slug=slug, channel_slug=channel, requestor=requestor
+ )
+ return ChannelContext(node=product, channel_slug=channel) if product else None
- def resolve_products(self, info, **kwargs):
- return resolve_products(info, **kwargs)
+ def resolve_products(self, info, channel=None, **kwargs):
+ requestor = get_user_or_app_from_context(info.context)
+ requestor_has_access_to_all = models.Product.objects.user_has_access_to_all(
+ requestor
+ )
+ if channel is None and not requestor_has_access_to_all:
+ channel = get_default_channel_slug_or_graphql_error()
+ return resolve_products(info, requestor, channel_slug=channel, **kwargs)
- def resolve_product_type(self, info, id):
+ def resolve_product_type(self, info, id, **_kwargs):
return graphene.Node.get_node_from_global_id(info, id, ProductType)
def resolve_product_types(self, info, **kwargs):
return resolve_product_types(info, **kwargs)
- def resolve_product_variant(self, info, id=None, sku=None):
+ def resolve_product_variant(
+ self, info, id=None, sku=None, channel=None,
+ ):
validate_one_of_args_is_in_query("id", id, "sku", sku)
+ requestor = get_user_or_app_from_context(info.context)
+ requestor_has_access_to_all = models.Product.objects.user_has_access_to_all(
+ requestor
+ )
+ if channel is None and not requestor_has_access_to_all:
+ channel = get_default_channel_slug_or_graphql_error()
if id:
- return graphene.Node.get_node_from_global_id(info, id, ProductVariant)
- return resolve_product_variant_by_sku(info, sku=sku)
+ _, id = graphene.Node.from_global_id(id)
+ variant = resolve_variant_by_id(
+ info, id, channel_slug=channel, requestor=requestor
+ )
+ else:
+ variant = resolve_product_variant_by_sku(
+ info,
+ sku=sku,
+ channel_slug=channel,
+ requestor=requestor,
+ requestor_has_access_to_all=requestor_has_access_to_all,
+ )
+ return ChannelContext(node=variant, channel_slug=channel) if variant else None
- def resolve_product_variants(self, info, ids=None, **_kwargs):
- return resolve_product_variants(info, ids)
+ def resolve_product_variants(self, info, ids=None, channel=None, **_kwargs):
+ requestor = get_user_or_app_from_context(info.context)
+ requestor_has_access_to_all = models.Product.objects.user_has_access_to_all(
+ requestor
+ )
+ if channel is None and not requestor_has_access_to_all:
+ channel = get_default_channel_slug_or_graphql_error()
+ return resolve_product_variants(
+ info,
+ ids=ids,
+ channel_slug=channel,
+ requestor_has_access_to_all=requestor_has_access_to_all,
+ requestor=requestor,
+ )
@permission_required(ProductPermissions.MANAGE_PRODUCTS)
- def resolve_report_product_sales(self, *_args, period, **_kwargs):
- return resolve_report_product_sales(period)
+ def resolve_report_product_sales(self, *_args, period, channel, **_kwargs):
+ return resolve_report_product_sales(period, channel_slug=channel)
class ProductMutations(graphene.ObjectType):
@@ -319,19 +425,18 @@ class ProductMutations(graphene.ObjectType):
collection_delete = CollectionDelete.Field()
collection_reorder_products = CollectionReorderProducts.Field()
collection_bulk_delete = CollectionBulkDelete.Field()
- collection_bulk_publish = CollectionBulkPublish.Field()
collection_remove_products = CollectionRemoveProducts.Field()
collection_update = CollectionUpdate.Field()
collection_translate = CollectionTranslate.Field()
+ collection_channel_listing_update = CollectionChannelListingUpdate.Field()
product_create = ProductCreate.Field()
product_delete = ProductDelete.Field()
product_bulk_delete = ProductBulkDelete.Field()
- product_bulk_publish = ProductBulkPublish.Field()
product_update = ProductUpdate.Field()
product_translate = ProductTranslate.Field()
- product_set_availability_for_purchase = ProductSetAvailabilityForPurchase.Field()
+ product_channel_listing_update = ProductChannelListingUpdate.Field()
product_image_create = ProductImageCreate.Field()
product_variant_reorder = ProductVariantReorder.Field()
@@ -362,6 +467,7 @@ class ProductMutations(graphene.ObjectType):
product_variant_update = ProductVariantUpdate.Field()
product_variant_set_default = ProductVariantSetDefault.Field()
product_variant_translate = ProductVariantTranslate.Field()
+ product_variant_channel_listing_update = ProductVariantChannelListingUpdate.Field()
variant_image_assign = VariantImageAssign.Field()
variant_image_unassign = VariantImageUnassign.Field()
diff --git a/saleor/graphql/product/sorters.py b/saleor/graphql/product/sorters.py
index c94f7ece7a..7c1099127b 100644
--- a/saleor/graphql/product/sorters.py
+++ b/saleor/graphql/product/sorters.py
@@ -1,10 +1,28 @@
import graphene
-from django.db.models import Count, F, IntegerField, Min, OuterRef, QuerySet, Subquery
+from django.db.models import (
+ BooleanField,
+ Count,
+ DateField,
+ ExpressionWrapper,
+ F,
+ IntegerField,
+ Min,
+ OuterRef,
+ Q,
+ QuerySet,
+ Subquery,
+)
from django.db.models.expressions import Window
from django.db.models.functions import Coalesce, RowNumber
-from ...product.models import Category, Product
-from ..core.types import SortInputObjectType
+from ...product.models import (
+ Category,
+ CollectionChannelListing,
+ Product,
+ ProductChannelListing,
+)
+from ..channel.sorters import validate_channel_slug
+from ..core.types import ChannelSortInputObjectType, SortInputObjectType
class AttributeSortField(graphene.Enum):
@@ -76,7 +94,7 @@ class CategorySortField(graphene.Enum):
raise ValueError("Unsupported enum value: %s" % self.value)
@staticmethod
- def qs_with_product_count(queryset: QuerySet) -> QuerySet:
+ def qs_with_product_count(queryset: QuerySet, **_kwargs) -> QuerySet:
return queryset.annotate(
product_count=Coalesce(
Subquery(
@@ -92,11 +110,11 @@ class CategorySortField(graphene.Enum):
)
@staticmethod
- def qs_with_subcategory_count(queryset: QuerySet) -> QuerySet:
+ def qs_with_subcategory_count(queryset: QuerySet, **_kwargs) -> QuerySet:
return queryset.annotate(subcategory_count=Count("children__id"))
-class CategorySortingInput(SortInputObjectType):
+class CategorySortingInput(ChannelSortInputObjectType):
class Meta:
sort_enum = CategorySortField
type_name = "categories"
@@ -122,11 +140,35 @@ class CollectionSortField(graphene.Enum):
raise ValueError("Unsupported enum value: %s" % self.value)
@staticmethod
- def qs_with_product_count(queryset: QuerySet) -> QuerySet:
+ def qs_with_product_count(queryset: QuerySet, **_kwargs) -> QuerySet:
return queryset.annotate(product_count=Count("collectionproduct__id"))
+ @staticmethod
+ def qs_with_availability(queryset: QuerySet, channel_slug: str) -> QuerySet:
+ validate_channel_slug(channel_slug)
+ subquery = Subquery(
+ CollectionChannelListing.objects.filter(
+ collection_id=OuterRef("pk"), channel__slug=channel_slug
+ ).values_list("is_published")[:1]
+ )
+ return queryset.annotate(
+ is_published=ExpressionWrapper(subquery, output_field=BooleanField())
+ )
-class CollectionSortingInput(SortInputObjectType):
+ @staticmethod
+ def qs_with_publication_date(queryset: QuerySet, channel_slug: str) -> QuerySet:
+ validate_channel_slug(channel_slug)
+ subquery = Subquery(
+ CollectionChannelListing.objects.filter(
+ collection_id=OuterRef("pk"), channel__slug=channel_slug
+ ).values_list("publication_date")[:1]
+ )
+ return queryset.annotate(
+ publication_date=ExpressionWrapper(subquery, output_field=DateField())
+ )
+
+
+class CollectionSortingInput(ChannelSortInputObjectType):
class Meta:
sort_enum = CollectionSortField
type_name = "collections"
@@ -135,7 +177,7 @@ class CollectionSortingInput(SortInputObjectType):
class ProductOrderField(graphene.Enum):
NAME = ["name", "slug"]
PRICE = ["min_variants_price_amount", "name", "slug"]
- MINIMAL_PRICE = ["minimal_variant_price_amount", "name", "slug"]
+ MINIMAL_PRICE = ["discounted_price_amount", "name", "slug"]
DATE = ["updated_at", "name", "slug"]
TYPE = ["product_type__name", "name", "slug"]
PUBLISHED = ["is_published", "name", "slug"]
@@ -167,13 +209,51 @@ class ProductOrderField(graphene.Enum):
raise ValueError("Unsupported enum value: %s" % self.value)
@staticmethod
- def qs_with_price(queryset: QuerySet) -> QuerySet:
+ def qs_with_price(queryset: QuerySet, channel_slug: str) -> QuerySet:
+ validate_channel_slug(channel_slug)
+ return queryset.annotate(
+ min_variants_price_amount=Min(
+ "variants__channel_listings__price_amount",
+ filter=Q(variants__channel_listings__channel__slug=channel_slug),
+ )
+ )
+
+ @staticmethod
+ def qs_with_minimal_price(queryset: QuerySet, channel_slug: str) -> QuerySet:
+ validate_channel_slug(channel_slug)
+ return queryset.annotate(
+ discounted_price_amount=Min(
+ "channel_listings__discounted_price_amount",
+ filter=Q(channel_listings__channel__slug=channel_slug),
+ )
+ )
+
+ @staticmethod
+ def qs_with_published(queryset: QuerySet, channel_slug: str) -> QuerySet:
+ validate_channel_slug(channel_slug)
+ subquery = Subquery(
+ ProductChannelListing.objects.filter(
+ product_id=OuterRef("pk"), channel__slug=channel_slug
+ ).values_list("is_published")[:1]
+ )
+ return queryset.annotate(
+ is_published=ExpressionWrapper(subquery, output_field=BooleanField())
+ )
+
+ @staticmethod
+ def qs_with_publication_date(queryset: QuerySet, channel_slug: str) -> QuerySet:
+ validate_channel_slug(channel_slug)
+ subquery = Subquery(
+ ProductChannelListing.objects.filter(
+ product_id=OuterRef("pk"), channel__slug=channel_slug
+ ).values_list("publication_date")[:1]
+ )
return queryset.annotate(
- min_variants_price_amount=Min("variants__price_amount")
+ publication_date=ExpressionWrapper(subquery, output_field=DateField())
)
@staticmethod
- def qs_with_collection(queryset: QuerySet) -> QuerySet:
+ def qs_with_collection(queryset: QuerySet, **_kwargs) -> QuerySet:
return queryset.annotate(
row_number=Window(
expression=RowNumber(),
@@ -185,7 +265,7 @@ class ProductOrderField(graphene.Enum):
)
-class ProductOrder(SortInputObjectType):
+class ProductOrder(ChannelSortInputObjectType):
attribute_id = graphene.Argument(
graphene.ID,
description=(
diff --git a/saleor/graphql/product/tests/benchmark/conftest.py b/saleor/graphql/product/tests/benchmark/conftest.py
index 46b5ef540e..b7c7d5d3c5 100644
--- a/saleor/graphql/product/tests/benchmark/conftest.py
+++ b/saleor/graphql/product/tests/benchmark/conftest.py
@@ -1,43 +1,25 @@
import pytest
-from .....discount.models import Sale
+from .....discount.models import Sale, SaleChannelListing
from .....product.models import Category
@pytest.fixture
-def sales_list():
- return list(
- Sale.objects.bulk_create(
- [Sale(name="Sale1", value=15), Sale(name="Sale2", value=5)]
- )
+def sales_list(channel_USD):
+ sales = Sale.objects.bulk_create([Sale(name="Sale1"), Sale(name="Sale2")])
+ values = [15, 5]
+ SaleChannelListing.objects.bulk_create(
+ [
+ SaleChannelListing(
+ sale=sale,
+ channel=channel_USD,
+ discount_value=values[i],
+ currency=channel_USD.currency_code,
+ )
+ for i, sale in enumerate(sales)
+ ]
)
-
-
-def homepage_collection(
- site_settings,
- collection,
- product_list_published,
- product_with_image,
- product_with_variant_with_two_attributes,
- product_with_multiple_values_attributes,
- product_without_shipping,
- non_default_category,
- sales_list,
-):
- product_with_image.category = non_default_category
- product_with_image.save()
-
- collection.products.set(product_list_published)
-
- collection.products.add(product_with_image)
- collection.products.add(product_with_variant_with_two_attributes)
- collection.products.add(product_with_multiple_values_attributes)
- collection.products.add(product_without_shipping)
-
- site_settings.homepage_collection = collection
- site_settings.save(update_fields=["homepage_collection"])
- return collection
+ return list(sales)
@pytest.fixture
diff --git a/saleor/graphql/product/tests/benchmark/test_category.py b/saleor/graphql/product/tests/benchmark/test_category.py
index 073302b796..f463e005d2 100644
--- a/saleor/graphql/product/tests/benchmark/test_category.py
+++ b/saleor/graphql/product/tests/benchmark/test_category.py
@@ -6,7 +6,7 @@ from ....tests.utils import get_graphql_content
@pytest.mark.django_db
@pytest.mark.count_queries(autouse=False)
-def test_category_view(api_client, category_with_products, count_queries):
+def test_category_view(api_client, category_with_products, count_queries, channel_USD):
query = """
fragment BasicProductFields on Product {
id
@@ -53,8 +53,12 @@ def test_category_view(api_client, category_with_products, count_queries):
}
}
- query Category($id: ID!, $pageSize: Int) {
- products(first: $pageSize, filter: {categories: [$id]}) {
+ query Category($id: ID!, $pageSize: Int, $channel: String) {
+ products (
+ first: $pageSize,
+ filter: {categories: [$id]},
+ channel: $channel
+ ) {
totalCount
edges {
node {
@@ -90,7 +94,7 @@ def test_category_view(api_client, category_with_products, count_queries):
}
}
}
- attributes(filter: {inCategory: $id}, first: 100) {
+ attributes(filter: {inCategory: $id, channel: $channel}, first: 100) {
edges {
node {
id
@@ -109,5 +113,6 @@ def test_category_view(api_client, category_with_products, count_queries):
variables = {
"pageSize": 100,
"id": graphene.Node.to_global_id("Category", category_with_products.pk),
+ "channel": channel_USD.slug,
}
get_graphql_content(api_client.post_graphql(query, variables))
diff --git a/saleor/graphql/product/tests/benchmark/test_collection.py b/saleor/graphql/product/tests/benchmark/test_collection.py
index 8bc5431ee3..5e86b4dd3c 100644
--- a/saleor/graphql/product/tests/benchmark/test_collection.py
+++ b/saleor/graphql/product/tests/benchmark/test_collection.py
@@ -6,7 +6,7 @@ from ....tests.utils import get_graphql_content
@pytest.mark.django_db
@pytest.mark.count_queries(autouse=False)
-def test_collection_view(api_client, homepage_collection, count_queries):
+def test_collection_view(api_client, published_collection, count_queries, channel_USD):
query = """
fragment BasicProductFields on Product {
id
@@ -53,8 +53,8 @@ def test_collection_view(api_client, homepage_collection, count_queries):
}
}
- query Collection($id: ID!, $pageSize: Int) {
- collection(id: $id) {
+ query Collection($id: ID!, $pageSize: Int, $channel: String) {
+ collection(id: $id, channel: $channel) {
id
slug
name
@@ -64,7 +64,11 @@ def test_collection_view(api_client, homepage_collection, count_queries):
url
}
}
- products(first: $pageSize, filter: {collections: [$id]}) {
+ products (
+ first: $pageSize,
+ filter: {collections: [$id]},
+ channel: $channel
+ ) {
totalCount
edges {
node {
@@ -83,7 +87,7 @@ def test_collection_view(api_client, homepage_collection, count_queries):
startCursor
}
}
- attributes(filter: {inCollection: $id}, first: 100) {
+ attributes(filter: {inCollection: $id, channel: $channel}, first: 100) {
edges {
node {
id
@@ -101,6 +105,49 @@ def test_collection_view(api_client, homepage_collection, count_queries):
"""
variables = {
"pageSize": 100,
- "id": graphene.Node.to_global_id("Collection", homepage_collection.pk),
+ "id": graphene.Node.to_global_id("Collection", published_collection.pk),
+ "channel": channel_USD.slug,
}
get_graphql_content(api_client.post_graphql(query, variables))
+
+
[email protected]_queries(autouse=False)
+def test_retrieve_collection_channel_listings(
+ product_list_with_many_channels,
+ staff_api_client,
+ count_queries,
+ permission_manage_products,
+ channel_USD,
+):
+ query = """
+ query($channel: String) {
+ collections(first: 10, channel: $channel) {
+ edges {
+ node {
+ id
+ channelListings {
+ publicationDate
+ isPublished
+ channel{
+ slug
+ currencyCode
+ name
+ isActive
+ }
+ }
+ }
+ }
+ }
+ }
+ """
+
+ variables = {"channel": channel_USD.slug}
+ get_graphql_content(
+ staff_api_client.post_graphql(
+ query,
+ variables,
+ permissions=(permission_manage_products,),
+ check_no_permissions=False,
+ )
+ )
diff --git a/saleor/graphql/product/tests/benchmark/test_homepage.py b/saleor/graphql/product/tests/benchmark/test_homepage.py
index fc05730dc9..ae7ca1ec47 100644
--- a/saleor/graphql/product/tests/benchmark/test_homepage.py
+++ b/saleor/graphql/product/tests/benchmark/test_homepage.py
@@ -1,25 +1,19 @@
import pytest
+from ....core.enums import ReportingPeriod
from ....tests.utils import get_graphql_content
@pytest.mark.django_db
@pytest.mark.count_queries(autouse=False)
def test_retrieve_product_list(
- api_client, homepage_collection, category, categories_tree, count_queries,
+ api_client, category, categories_tree, count_queries,
):
query = """
query ProductsList {
shop {
description
name
- homepageCollection {
- id
- backgroundImage {
- url
- }
- name
- }
}
categories(level: 0, first: 4) {
edges {
@@ -39,71 +33,33 @@ def test_retrieve_product_list(
@pytest.mark.django_db
@pytest.mark.count_queries(autouse=False)
-def test_featured_products_list(api_client, homepage_collection, count_queries):
+def test_report_product_sales(
+ staff_api_client,
+ order_with_lines,
+ order_with_lines_channel_PLN,
+ permission_manage_products,
+ permission_manage_orders,
+ channel_USD,
+ count_queries,
+):
query = """
- fragment BasicProductFields on Product {
- id
- name
- thumbnail {
- url
- alt
- }
- thumbnail2x: thumbnail(size: 510) {
- url
- }
- }
-
- fragment Price on TaxedMoney {
- gross {
- amount
- currency
- }
- net {
- amount
- currency
- }
- }
-
- fragment ProductPricingField on Product {
- pricing {
- onSale
- priceRangeUndiscounted {
- start {
- ...Price
- }
- stop {
- ...Price
- }
- }
- priceRange {
- start {
- ...Price
- }
- stop {
- ...Price
- }
- }
- }
- }
-
- query FeaturedProducts {
- shop {
- homepageCollection {
- id
- products(first: 20) {
- edges {
- node {
- ...BasicProductFields
- ...ProductPricingField
- category {
- id
- name
- }
+ query TopProducts($period: ReportingPeriod!, $channel: String!) {
+ reportProductSales(period: $period, first: 20, channel: $channel) {
+ edges {
+ node {
+ revenue(period: $period) {
+ gross {
+ amount
}
}
+ quantityOrdered
+ sku
}
}
}
}
"""
- get_graphql_content(api_client.post_graphql(query))
+ variables = {"period": ReportingPeriod.TODAY.name, "channel": channel_USD.slug}
+ permissions = [permission_manage_orders, permission_manage_products]
+ response = staff_api_client.post_graphql(query, variables, permissions)
+ get_graphql_content(response)
diff --git a/saleor/graphql/product/tests/benchmark/test_product.py b/saleor/graphql/product/tests/benchmark/test_product.py
index c6cb17313a..7cd2783ed5 100644
--- a/saleor/graphql/product/tests/benchmark/test_product.py
+++ b/saleor/graphql/product/tests/benchmark/test_product.py
@@ -6,7 +6,7 @@ from ....tests.utils import get_graphql_content
@pytest.mark.django_db
@pytest.mark.count_queries(autouse=False)
-def test_product_details(product, api_client, count_queries):
+def test_product_details(product, api_client, count_queries, channel_USD):
query = """
fragment BasicProductFields on Product {
id
@@ -69,14 +69,14 @@ def test_product_details(product, api_client, count_queries):
}
}
- query ProductDetails($id: ID!) {
- product(id: $id) {
+ query ProductDetails($id: ID!, $channel: String) {
+ product(id: $id, channel: $channel) {
...BasicProductFields
description
category {
id
name
- products(first: 4) {
+ products(first: 4, channel: $channel) {
edges {
node {
...BasicProductFields
@@ -152,16 +152,21 @@ def test_product_details(product, api_client, count_queries):
}
"""
- variables = {"id": Node.to_global_id("Product", product.pk)}
+ variables = {
+ "id": Node.to_global_id("Product", product.pk),
+ "channel": channel_USD.slug,
+ }
get_graphql_content(api_client.post_graphql(query, variables))
@pytest.mark.django_db
@pytest.mark.count_queries(autouse=False)
-def test_retrieve_product_attributes(product_list, api_client, count_queries):
+def test_retrieve_product_attributes(
+ product_list, api_client, count_queries, channel_USD
+):
query = """
- query($sortBy: ProductOrder) {
- products(first: 10, sortBy: $sortBy) {
+ query($sortBy: ProductOrder, $channel: String) {
+ products(first: 10, sortBy: $sortBy, channel: $channel) {
edges {
node {
id
@@ -176,18 +181,79 @@ def test_retrieve_product_attributes(product_list, api_client, count_queries):
}
"""
- variables = {}
+ variables = {"channel": channel_USD.slug}
get_graphql_content(api_client.post_graphql(query, variables))
[email protected]_queries(autouse=False)
+def test_retrieve_channel_listings(
+ product_list_with_many_channels,
+ staff_api_client,
+ count_queries,
+ permission_manage_products,
+ channel_USD,
+):
+ query = """
+ query($channel: String) {
+ products(first: 10, channel: $channel) {
+ edges {
+ node {
+ id
+ channelListings {
+ publicationDate
+ isPublished
+ channel{
+ slug
+ currencyCode
+ name
+ isActive
+ }
+ visibleInListings
+ discountedPrice{
+ amount
+ currency
+ }
+ purchaseCost{
+ start{
+ amount
+ }
+ stop{
+ amount
+ }
+ }
+ margin{
+ start
+ stop
+ }
+ isAvailableForPurchase
+ availableForPurchase
+ }
+ }
+ }
+ }
+ }
+ """
+
+ variables = {"channel": channel_USD.slug}
+ get_graphql_content(
+ staff_api_client.post_graphql(
+ query,
+ variables,
+ permissions=(permission_manage_products,),
+ check_no_permissions=False,
+ )
+ )
+
+
@pytest.mark.django_db
@pytest.mark.count_queries(autouse=False)
def test_retrive_products_with_product_types_and_attributes(
- product_list, api_client, count_queries
+ product_list, api_client, count_queries, channel_USD,
):
query = """
- {
- products(first: 10) {
+ query($channel: String) {
+ products(first: 10, channel: $channel) {
edges {
node {
id
@@ -205,5 +271,5 @@ def test_retrive_products_with_product_types_and_attributes(
}
}
"""
- variables = {}
+ variables = {"channel": channel_USD.slug}
get_graphql_content(api_client.post_graphql(query, variables))
diff --git a/saleor/graphql/product/tests/benchmark/test_variant.py b/saleor/graphql/product/tests/benchmark/test_variant.py
index 30943bce37..d9167f9491 100644
--- a/saleor/graphql/product/tests/benchmark/test_variant.py
+++ b/saleor/graphql/product/tests/benchmark/test_variant.py
@@ -17,6 +17,7 @@ def test_retrieve_variant_list(
warehouse,
warehouse_no_shipping_zone,
shipping_zone_without_countries,
+ channel_USD,
):
query = """
fragment BasicProductFields on Product {
@@ -80,8 +81,8 @@ def test_retrieve_variant_list(
}
}
- query VariantList($ids: [ID!]) {
- productVariants(ids: $ids, first: 100) {
+ query VariantList($ids: [ID!], $channel: String) {
+ productVariants(ids: $ids, first: 100, channel: $channel) {
edges {
node {
...ProductVariantFields
@@ -115,7 +116,8 @@ def test_retrieve_variant_list(
"ids": [
graphene.Node.to_global_id("ProductVariant", variant.pk)
for variant in product_variant_list
- ]
+ ],
+ "channel": channel_USD.slug,
}
get_graphql_content(api_client.post_graphql(query, variables))
@@ -161,7 +163,6 @@ def test_product_variant_bulk_create(
{"id": color_attribute_id, "values": ["red"]},
{"id": size_attribute_id, "values": ["big"]},
],
- "price": 10,
}
]
variables = {"productId": product_id, "variants": variants}
diff --git a/saleor/graphql/product/tests/deprecated/__init__.py b/saleor/graphql/product/tests/deprecated/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/graphql/product/tests/deprecated/test_collection.py b/saleor/graphql/product/tests/deprecated/test_collection.py
new file mode 100644
index 0000000000..d15f072a17
--- /dev/null
+++ b/saleor/graphql/product/tests/deprecated/test_collection.py
@@ -0,0 +1,47 @@
+import warnings
+
+from .....channel.utils import DEPRECATION_WARNING_MESSAGE
+from ....tests.utils import get_graphql_content
+
+
+def test_collections_query_with_default_channel_slug(
+ user_api_client,
+ published_collection,
+ unpublished_collection,
+ permission_manage_products,
+ channel_USD,
+):
+ query = """
+ query Collections {
+ collections(first:2) {
+ edges {
+ node {
+ name
+ slug
+ description
+ products {
+ totalCount
+ }
+ }
+ }
+ }
+ }
+ """
+
+ # query public collections only as regular user
+ with warnings.catch_warnings(record=True) as warns:
+ response = user_api_client.post_graphql(query)
+ content = get_graphql_content(response)
+ edges = content["data"]["collections"]["edges"]
+ assert len(edges) == 1
+ collection_data = edges[0]["node"]
+ assert collection_data["name"] == published_collection.name
+ assert collection_data["slug"] == published_collection.slug
+ assert collection_data["description"] == published_collection.description
+ assert (
+ collection_data["products"]["totalCount"]
+ == published_collection.products.count()
+ )
+ assert any(
+ [str(warning.message) == DEPRECATION_WARNING_MESSAGE for warning in warns]
+ )
diff --git a/saleor/graphql/product/tests/deprecated/test_product.py b/saleor/graphql/product/tests/deprecated/test_product.py
new file mode 100644
index 0000000000..d92454b8ec
--- /dev/null
+++ b/saleor/graphql/product/tests/deprecated/test_product.py
@@ -0,0 +1,71 @@
+import warnings
+
+import graphene
+
+from .....channel.utils import DEPRECATION_WARNING_MESSAGE
+from .....product.models import Product
+from ....tests.utils import get_graphql_content
+
+QUERY_PRODUCT = """
+ query ($id: ID, $slug: String){
+ product(
+ id: $id,
+ slug: $slug,
+ ) {
+ id
+ name
+ }
+ }
+ """
+
+QUERY_FETCH_ALL_PRODUCTS = """
+ query {
+ products(first: 1) {
+ totalCount
+ edges {
+ node {
+ name
+ }
+ }
+ }
+ }
+"""
+
+
+def test_product_query_by_id_with_default_channel(user_api_client, product):
+ variables = {"id": graphene.Node.to_global_id("Product", product.pk)}
+
+ with warnings.catch_warnings(record=True) as warns:
+ response = user_api_client.post_graphql(QUERY_PRODUCT, variables=variables)
+ content = get_graphql_content(response)
+ collection_data = content["data"]["product"]
+ assert collection_data is not None
+ assert collection_data["name"] == product.name
+ assert any(
+ [str(warning.message) == DEPRECATION_WARNING_MESSAGE for warning in warns]
+ )
+
+
+def test_product_query_by_slug_with_default_channel(user_api_client, product):
+ variables = {"slug": product.slug}
+ with warnings.catch_warnings(record=True) as warns:
+ response = user_api_client.post_graphql(QUERY_PRODUCT, variables=variables)
+ content = get_graphql_content(response)
+ collection_data = content["data"]["product"]
+ assert collection_data is not None
+ assert collection_data["name"] == product.name
+ assert any(
+ [str(warning.message) == DEPRECATION_WARNING_MESSAGE for warning in warns]
+ )
+
+
+def test_fetch_all_products(user_api_client, product):
+ with warnings.catch_warnings(record=True) as warns:
+ response = user_api_client.post_graphql(QUERY_FETCH_ALL_PRODUCTS)
+ content = get_graphql_content(response)
+ num_products = Product.objects.count()
+ assert content["data"]["products"]["totalCount"] == num_products
+ assert len(content["data"]["products"]["edges"]) == num_products
+ assert any(
+ [str(warning.message) == DEPRECATION_WARNING_MESSAGE for warning in warns]
+ )
diff --git a/saleor/graphql/product/tests/deprecated/test_variant_availability.py b/saleor/graphql/product/tests/deprecated/test_variant_availability.py
new file mode 100644
index 0000000000..0001061cc7
--- /dev/null
+++ b/saleor/graphql/product/tests/deprecated/test_variant_availability.py
@@ -0,0 +1,88 @@
+import warnings
+
+import graphene
+
+from .....channel.utils import DEPRECATION_WARNING_MESSAGE
+from ....tests.utils import get_graphql_content
+
+QUERY_DEPRECATED_VARIANT_AVAILABILITY = """
+ query variantAvailability($id: ID!) {
+ productVariant(id: $id) {
+ isAvailable
+ stockQuantity
+ quantityAvailable
+ }
+ }
+"""
+
+
+def test_variant_availability_without_inventory_tracking(
+ api_client, variant_without_inventory_tracking, settings
+):
+ variant = variant_without_inventory_tracking
+ variables = {"id": graphene.Node.to_global_id("ProductVariant", variant.pk)}
+ with warnings.catch_warnings(record=True) as warns:
+ response = api_client.post_graphql(
+ QUERY_DEPRECATED_VARIANT_AVAILABILITY, variables
+ )
+ content = get_graphql_content(response)
+ variant_data = content["data"]["productVariant"]
+ assert variant_data["isAvailable"] is True
+ assert variant_data["stockQuantity"] == settings.MAX_CHECKOUT_LINE_QUANTITY
+ assert variant_data["quantityAvailable"] == settings.MAX_CHECKOUT_LINE_QUANTITY
+ assert any(
+ [str(warning.message) == DEPRECATION_WARNING_MESSAGE for warning in warns]
+ )
+
+
+def test_variant_availability(api_client, variant_with_many_stocks, settings):
+ variant = variant_with_many_stocks
+ variables = {"id": graphene.Node.to_global_id("ProductVariant", variant.pk)}
+ with warnings.catch_warnings(record=True) as warns:
+ response = api_client.post_graphql(
+ QUERY_DEPRECATED_VARIANT_AVAILABILITY, variables
+ )
+ content = get_graphql_content(response)
+ variant_data = content["data"]["productVariant"]
+ assert variant_data["isAvailable"] is True
+ assert variant_data["stockQuantity"] == 7
+ assert variant_data["quantityAvailable"] == 7
+ assert any(
+ [str(warning.message) == DEPRECATION_WARNING_MESSAGE for warning in warns]
+ )
+
+
+def test_variant_availability_without_inventory_tracking_without_stocks(
+ api_client, variant_without_inventory_tracking, settings
+):
+ variant = variant_without_inventory_tracking
+ variant.stocks.all().delete()
+ variables = {"id": graphene.Node.to_global_id("ProductVariant", variant.pk)}
+ with warnings.catch_warnings(record=True) as warns:
+ response = api_client.post_graphql(
+ QUERY_DEPRECATED_VARIANT_AVAILABILITY, variables
+ )
+ content = get_graphql_content(response)
+ variant_data = content["data"]["productVariant"]
+ assert variant_data["isAvailable"] is True
+ assert variant_data["stockQuantity"] == settings.MAX_CHECKOUT_LINE_QUANTITY
+ assert variant_data["quantityAvailable"] == settings.MAX_CHECKOUT_LINE_QUANTITY
+ assert any(
+ [str(warning.message) == DEPRECATION_WARNING_MESSAGE for warning in warns]
+ )
+
+
+def test_variant_availability_without_stocks(api_client, variant, settings):
+ variables = {"id": graphene.Node.to_global_id("ProductVariant", variant.pk)}
+ with warnings.catch_warnings(record=True) as warns:
+ response = api_client.post_graphql(
+ QUERY_DEPRECATED_VARIANT_AVAILABILITY, variables
+ )
+ content = get_graphql_content(response)
+ variant_data = content["data"]["productVariant"]
+ assert variant_data["isAvailable"] is False
+ assert variant_data["stockQuantity"] == 0
+ assert variant_data["quantityAvailable"] == 0
+ assert any(
+ [str(warning.message) == DEPRECATION_WARNING_MESSAGE for warning in warns]
+ )
diff --git a/saleor/graphql/product/tests/test_attribute_filtering_with_channels.py b/saleor/graphql/product/tests/test_attribute_filtering_with_channels.py
new file mode 100644
index 0000000000..5327b66ef8
--- /dev/null
+++ b/saleor/graphql/product/tests/test_attribute_filtering_with_channels.py
@@ -0,0 +1,429 @@
+from decimal import Decimal
+
+import graphene
+import pytest
+
+from ....product.models import (
+ Attribute,
+ AttributeProduct,
+ AttributeVariant,
+ Product,
+ ProductChannelListing,
+ ProductType,
+ ProductVariant,
+ ProductVariantChannelListing,
+)
+from ...channel.filters import LACK_OF_CHANNEL_IN_FILTERING_MSG
+from ...tests.utils import assert_graphql_error_with_message, get_graphql_content
+
+
+def attributes_for_filtering_with_channels(
+ collection, category, channel_USD, channel_PLN, other_channel_USD
+):
+ attributes = Attribute.objects.bulk_create(
+ [
+ Attribute(
+ name="Attr1",
+ slug="attr1",
+ value_required=True,
+ storefront_search_position=4,
+ ),
+ Attribute(
+ name="AttrAttr1",
+ slug="attr_attr1",
+ value_required=True,
+ storefront_search_position=3,
+ ),
+ Attribute(
+ name="AttrAttr2",
+ slug="attr_attr2",
+ value_required=True,
+ storefront_search_position=2,
+ ),
+ Attribute(
+ name="Attr2",
+ slug="attr2",
+ value_required=False,
+ storefront_search_position=5,
+ ),
+ Attribute(
+ name="Attr3",
+ slug="attr3",
+ value_required=False,
+ storefront_search_position=1,
+ ),
+ ]
+ )
+
+ product_type = ProductType.objects.create(name="My Product Type")
+ product = Product.objects.create(
+ name="Test product", product_type=product_type, category=category,
+ )
+ ProductChannelListing.objects.bulk_create(
+ [
+ ProductChannelListing(
+ channel=channel_USD,
+ product=product,
+ visible_in_listings=True,
+ currency=channel_USD.currency_code,
+ is_published=True,
+ ),
+ ProductChannelListing(
+ channel=channel_PLN,
+ product=product,
+ visible_in_listings=False,
+ currency=channel_PLN.currency_code,
+ is_published=True,
+ ),
+ ProductChannelListing(
+ channel=other_channel_USD,
+ product=product,
+ visible_in_listings=True,
+ currency=other_channel_USD.currency_code,
+ is_published=False,
+ ),
+ ]
+ )
+ variant = ProductVariant.objects.create(product=product)
+ ProductVariantChannelListing.objects.create(
+ variant=variant,
+ channel=channel_USD,
+ cost_price_amount=Decimal(1),
+ price_amount=Decimal(10),
+ currency=channel_USD.currency_code,
+ )
+ ProductVariantChannelListing.objects.create(
+ variant=variant,
+ channel=channel_PLN,
+ cost_price_amount=Decimal(1),
+ price_amount=Decimal(10),
+ currency=channel_PLN.currency_code,
+ )
+ ProductVariantChannelListing.objects.create(
+ variant=variant,
+ channel=other_channel_USD,
+ cost_price_amount=Decimal(1),
+ price_amount=Decimal(10),
+ currency=other_channel_USD.currency_code,
+ )
+
+ collection.products.add(product)
+ AttributeVariant.objects.bulk_create(
+ [
+ AttributeVariant(
+ product_type=product_type, attribute=attributes[1], sort_order=1
+ ),
+ AttributeVariant(
+ product_type=product_type, attribute=attributes[3], sort_order=2
+ ),
+ AttributeVariant(
+ product_type=product_type, attribute=attributes[4], sort_order=3
+ ),
+ ]
+ )
+ AttributeProduct.objects.bulk_create(
+ [
+ AttributeProduct(
+ product_type=product_type, attribute=attributes[2], sort_order=1
+ ),
+ AttributeProduct(
+ product_type=product_type, attribute=attributes[0], sort_order=2
+ ),
+ AttributeProduct(
+ product_type=product_type, attribute=attributes[1], sort_order=3
+ ),
+ ]
+ )
+
+ return attributes
+
+
+QUERY_ATTRIBUTES_FILTERING = """
+ query (
+ $filter: AttributeFilterInput
+ ){
+ attributes (
+ first: 10, filter: $filter
+ ) {
+ edges {
+ node {
+ name
+ }
+ }
+ }
+ }
+"""
+
+
+ "tested_field", ["inCategory", "inCollection"],
+)
+def test_attributes_with_filtering_without_channel(
+ tested_field, staff_api_client, permission_manage_products, category, collection,
+):
+ # given
+ if "Collection" in tested_field:
+ filtered_by_node_id = graphene.Node.to_global_id("Collection", collection.pk)
+ elif "Category" in tested_field:
+ filtered_by_node_id = graphene.Node.to_global_id("Category", category.pk)
+ else:
+ raise AssertionError(tested_field)
+ filter_by = {tested_field: filtered_by_node_id}
+ variables = {"filter": filter_by}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_ATTRIBUTES_FILTERING,
+ variables,
+ permissions=[permission_manage_products],
+ check_no_permissions=False,
+ )
+
+ # then
+ assert_graphql_error_with_message(response, LACK_OF_CHANNEL_IN_FILTERING_MSG)
+
+
+ "tested_field, attribute_count", [("inCategory", 5), ("inCollection", 5)],
+)
+def test_products_with_filtering_with_as_staff_user(
+ tested_field,
+ attribute_count,
+ staff_api_client,
+ permission_manage_products,
+ attributes_for_filtering_with_channels,
+ category,
+ collection,
+ channel_USD,
+):
+ # given
+ if "Collection" in tested_field:
+ filtered_by_node_id = graphene.Node.to_global_id("Collection", collection.pk)
+ elif "Category" in tested_field:
+ filtered_by_node_id = graphene.Node.to_global_id("Category", category.pk)
+ else:
+ raise AssertionError(tested_field)
+ filter_by = {tested_field: filtered_by_node_id, "channel": channel_USD.slug}
+
+ variables = {"filter": filter_by}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_ATTRIBUTES_FILTERING,
+ variables,
+ permissions=[permission_manage_products],
+ check_no_permissions=False,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ attribute_nodes = content["data"]["attributes"]["edges"]
+ assert len(attribute_nodes) == attribute_count
+
+
+ "tested_field, attribute_count", [("inCategory", 5), ("inCollection", 5)],
+)
+def test_products_with_filtering_as_anonymous_client(
+ tested_field,
+ attribute_count,
+ api_client,
+ attributes_for_filtering_with_channels,
+ category,
+ collection,
+ channel_USD,
+):
+ # given
+ if "Collection" in tested_field:
+ filtered_by_node_id = graphene.Node.to_global_id("Collection", collection.pk)
+ elif "Category" in tested_field:
+ filtered_by_node_id = graphene.Node.to_global_id("Category", category.pk)
+ else:
+ raise AssertionError(tested_field)
+ filter_by = {tested_field: filtered_by_node_id, "channel": channel_USD.slug}
+
+ variables = {"filter": filter_by}
+
+ # when
+ response = api_client.post_graphql(QUERY_ATTRIBUTES_FILTERING, variables)
+
+ # then
+ content = get_graphql_content(response)
+ attribute_nodes = content["data"]["attributes"]["edges"]
+ assert len(attribute_nodes) == attribute_count
+
+
+ "tested_field, attribute_count", [("inCategory", 5), ("inCollection", 5)],
+)
+def test_products_with_filtering_with_not_visible_in_listings_as_staff_user(
+ tested_field,
+ attribute_count,
+ staff_api_client,
+ permission_manage_products,
+ attributes_for_filtering_with_channels,
+ category,
+ collection,
+ channel_PLN,
+):
+ # given
+ if "Collection" in tested_field:
+ filtered_by_node_id = graphene.Node.to_global_id("Collection", collection.pk)
+ elif "Category" in tested_field:
+ filtered_by_node_id = graphene.Node.to_global_id("Category", category.pk)
+ else:
+ raise AssertionError(tested_field)
+ filter_by = {tested_field: filtered_by_node_id, "channel": channel_PLN.slug}
+
+ variables = {"filter": filter_by}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_ATTRIBUTES_FILTERING,
+ variables,
+ permissions=[permission_manage_products],
+ check_no_permissions=False,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ attribute_nodes = content["data"]["attributes"]["edges"]
+ assert len(attribute_nodes) == attribute_count
+
+
+ "tested_field, attribute_count",
+ [
+ ("inCategory", 0),
+ # Products not visible in listings should be visible in collections
+ ("inCollection", 5),
+ ],
+)
+def test_products_with_filtering_with_not_visible_in_listings_as_anonymous_client(
+ tested_field,
+ attribute_count,
+ api_client,
+ attributes_for_filtering_with_channels,
+ category,
+ collection,
+ channel_PLN,
+):
+ # given
+ if "Collection" in tested_field:
+ filtered_by_node_id = graphene.Node.to_global_id("Collection", collection.pk)
+ elif "Category" in tested_field:
+ filtered_by_node_id = graphene.Node.to_global_id("Category", category.pk)
+ else:
+ raise AssertionError(tested_field)
+ filter_by = {tested_field: filtered_by_node_id, "channel": channel_PLN.slug}
+
+ variables = {"filter": filter_by}
+
+ # when
+ response = api_client.post_graphql(QUERY_ATTRIBUTES_FILTERING, variables)
+
+ # then
+ content = get_graphql_content(response)
+ attribute_nodes = content["data"]["attributes"]["edges"]
+ assert len(attribute_nodes) == attribute_count
+
+
+ "tested_field, attribute_count", [("inCategory", 5), ("inCollection", 5)],
+)
+def test_products_with_filtering_with_not_published_as_staff_user(
+ tested_field,
+ attribute_count,
+ staff_api_client,
+ permission_manage_products,
+ attributes_for_filtering_with_channels,
+ category,
+ collection,
+ other_channel_USD,
+):
+ # given
+ if "Collection" in tested_field:
+ filtered_by_node_id = graphene.Node.to_global_id("Collection", collection.pk)
+ elif "Category" in tested_field:
+ filtered_by_node_id = graphene.Node.to_global_id("Category", category.pk)
+ else:
+ raise AssertionError(tested_field)
+ filter_by = {tested_field: filtered_by_node_id, "channel": other_channel_USD.slug}
+
+ variables = {"filter": filter_by}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_ATTRIBUTES_FILTERING,
+ variables,
+ permissions=[permission_manage_products],
+ check_no_permissions=False,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ attribute_nodes = content["data"]["attributes"]["edges"]
+ assert len(attribute_nodes) == attribute_count
+
+
+ "tested_field, attribute_count", [("inCategory", 0), ("inCollection", 0)],
+)
+def test_products_with_filtering_with_not_published_as_anonymous_client(
+ tested_field,
+ attribute_count,
+ api_client,
+ attributes_for_filtering_with_channels,
+ category,
+ collection,
+ other_channel_USD,
+):
+ # given
+ if "Collection" in tested_field:
+ filtered_by_node_id = graphene.Node.to_global_id("Collection", collection.pk)
+ elif "Category" in tested_field:
+ filtered_by_node_id = graphene.Node.to_global_id("Category", category.pk)
+ else:
+ raise AssertionError(tested_field)
+ filter_by = {tested_field: filtered_by_node_id, "channel": other_channel_USD.slug}
+
+ variables = {"filter": filter_by}
+
+ # when
+ response = api_client.post_graphql(QUERY_ATTRIBUTES_FILTERING, variables)
+
+ # then
+ content = get_graphql_content(response)
+ attribute_nodes = content["data"]["attributes"]["edges"]
+ assert len(attribute_nodes) == attribute_count
+
+
+ "tested_field", ["inCategory", "inCollection"],
+)
+def test_products_with_filtering_not_existing_channel(
+ tested_field,
+ api_client,
+ attributes_for_filtering_with_channels,
+ category,
+ collection,
+):
+ # given
+ if "Collection" in tested_field:
+ filtered_by_node_id = graphene.Node.to_global_id("Collection", collection.pk)
+ elif "Category" in tested_field:
+ filtered_by_node_id = graphene.Node.to_global_id("Category", category.pk)
+ else:
+ raise AssertionError(tested_field)
+ filter_by = {tested_field: filtered_by_node_id, "channel": "Not-existing"}
+
+ variables = {"filter": filter_by}
+
+ # when
+ response = api_client.post_graphql(QUERY_ATTRIBUTES_FILTERING, variables)
+
+ # then
+ content = get_graphql_content(response)
+ attribute_nodes = content["data"]["attributes"]["edges"]
+ assert len(attribute_nodes) == 0
diff --git a/saleor/graphql/product/tests/test_attribute_pagination.py b/saleor/graphql/product/tests/test_attribute_pagination.py
index 6605541c8d..4cafaadbb3 100644
--- a/saleor/graphql/product/tests/test_attribute_pagination.py
+++ b/saleor/graphql/product/tests/test_attribute_pagination.py
@@ -8,14 +8,16 @@ from ....product.models import (
AttributeProduct,
AttributeVariant,
Product,
+ ProductChannelListing,
ProductType,
ProductVariant,
+ ProductVariantChannelListing,
)
from ...tests.utils import get_graphql_content
@pytest.fixture
-def attributes_for_pagination(collection, category):
+def attributes_for_pagination(collection, category, channel_USD):
attributes = Attribute.objects.bulk_create(
[
Attribute(
@@ -53,15 +55,39 @@ def attributes_for_pagination(collection, category):
product_type = ProductType.objects.create(name="My Product Type")
product = Product.objects.create(
- name="Test product",
- product_type=product_type,
- category=category,
+ name="Test product", product_type=product_type, category=category,
+ )
+ ProductChannelListing.objects.create(
+ channel=channel_USD,
+ product=product,
is_published=True,
visible_in_listings=True,
)
- ProductVariant.objects.create(
- product=product, sku="testVariant", price_amount=Decimal(10)
+ variants = ProductVariant.objects.bulk_create(
+ [
+ ProductVariant(product=product),
+ ProductVariant(product=product, sku="testVariant"),
+ ]
)
+ ProductVariantChannelListing.objects.bulk_create(
+ [
+ ProductVariantChannelListing(
+ variant=variants[0],
+ channel=channel_USD,
+ cost_price_amount=Decimal(1),
+ price_amount=Decimal(10),
+ currency=channel_USD.currency_code,
+ ),
+ ProductVariantChannelListing(
+ variant=variants[1],
+ channel=channel_USD,
+ cost_price_amount=Decimal(1),
+ price_amount=Decimal(10),
+ currency=channel_USD.currency_code,
+ ),
+ ]
+ )
+
collection.products.add(product)
AttributeVariant.objects.bulk_create(
[
@@ -170,12 +196,12 @@ def test_attributes_pagination_with_filtering(
def test_attributes_pagination_with_filtering_in_collection(
- staff_api_client, attributes_for_pagination, collection
+ staff_api_client, attributes_for_pagination, collection, channel_USD
):
page_size = 2
attributes_order = ["Attr3", "AttrAttr2"]
collection_id = graphene.Node.to_global_id("Collection", collection.id)
- filter_by = {"inCollection": collection_id}
+ filter_by = {"inCollection": collection_id, "channel": channel_USD.slug}
variables = {"first": page_size, "after": None, "filter": filter_by}
response = staff_api_client.post_graphql(QUERY_ATTRIBUTES_PAGINATION, variables)
@@ -187,12 +213,12 @@ def test_attributes_pagination_with_filtering_in_collection(
def test_attributes_pagination_with_filtering_in_category(
- staff_api_client, attributes_for_pagination, category
+ staff_api_client, attributes_for_pagination, category, channel_USD
):
page_size = 2
attributes_order = ["Attr3", "AttrAttr2"]
category_id = graphene.Node.to_global_id("Category", category.id)
- filter_by = {"inCategory": category_id}
+ filter_by = {"inCategory": category_id, "channel": channel_USD.slug}
variables = {"first": page_size, "after": None, "filter": filter_by}
response = staff_api_client.post_graphql(QUERY_ATTRIBUTES_PAGINATION, variables)
diff --git a/saleor/graphql/product/tests/test_attributes.py b/saleor/graphql/product/tests/test_attributes.py
index a5c87380fd..7be4131af8 100644
--- a/saleor/graphql/product/tests/test_attributes.py
+++ b/saleor/graphql/product/tests/test_attributes.py
@@ -166,8 +166,8 @@ def test_attributes_query_hidden_attribute_as_staff_user(
QUERY_PRODUCT_AND_VARIANTS_ATTRIBUTES = """
- {
- products(first: 1) {
+ query ($channel: String){
+ products(first: 1, channel: $channel) {
edges {
node {
attributes {
@@ -204,10 +204,12 @@ def test_resolve_attributes_with_hidden(
size_attribute,
is_staff,
permission_manage_products,
+ channel_USD,
):
"""Ensure non-staff users don't see hidden attributes, and staff users having
the 'manage product' permission can.
"""
+ variables = {"channel": channel_USD.slug}
query = QUERY_PRODUCT_AND_VARIANTS_ATTRIBUTES
api_client = user_api_client
@@ -230,16 +232,17 @@ def test_resolve_attributes_with_hidden(
attribute.visible_in_storefront = False
attribute.save(update_fields=["visible_in_storefront"])
- product = get_graphql_content(api_client.post_graphql(query))["data"]["products"][
- "edges"
- ][0]["node"]
+ product = get_graphql_content(api_client.post_graphql(query, variables))["data"][
+ "products"
+ ]["edges"][0]["node"]
assert len(product["attributes"]) == expected_product_attribute_count
assert len(product["variants"][0]["attributes"]) == expected_variant_attribute_count
-def test_resolve_attribute_values(user_api_client, product, staff_user):
+def test_resolve_attribute_values(user_api_client, product, staff_user, channel_USD):
"""Ensure the attribute values are properly resolved."""
+ variables = {"channel": channel_USD.slug}
query = QUERY_PRODUCT_AND_VARIANTS_ATTRIBUTES
api_client = user_api_client
@@ -258,9 +261,9 @@ def test_resolve_attribute_values(user_api_client, product, staff_user):
assert len(product_attribute_values) == 1
assert len(variant_attribute_values) == 1
- product = get_graphql_content(api_client.post_graphql(query))["data"]["products"][
- "edges"
- ][0]["node"]
+ product = get_graphql_content(api_client.post_graphql(query, variables))["data"][
+ "products"
+ ]["edges"][0]["node"]
product_attributes = product["attributes"]
variant_attributes = product["variants"][0]["attributes"]
@@ -276,12 +279,13 @@ def test_resolve_attribute_values(user_api_client, product, staff_user):
def test_resolve_attribute_values_non_assigned_to_node(
- user_api_client, product, staff_user
+ user_api_client, product, staff_user, channel_USD
):
"""Ensure the attribute values are properly resolved when an attribute is part
of the product type but not of the node (product/variant), thus no values should be
resolved.
"""
+ variables = {"channel": channel_USD.slug}
query = QUERY_PRODUCT_AND_VARIANTS_ATTRIBUTES
api_client = user_api_client
@@ -313,9 +317,9 @@ def test_resolve_attribute_values_non_assigned_to_node(
assert product.attributes.count() == 1
assert variant.attributes.count() == 1
- product = get_graphql_content(api_client.post_graphql(query))["data"]["products"][
- "edges"
- ][0]["node"]
+ product = get_graphql_content(api_client.post_graphql(query, variables))["data"][
+ "products"
+ ]["edges"][0]["node"]
product_attributes = product["attributes"]
variant_attributes = product["variants"][0]["attributes"]
@@ -337,11 +341,13 @@ def test_attributes_filter_by_product_type_with_empty_value():
qs = Attribute.objects.all()
- assert filter_attributes_by_product_types(qs, "...", "", None) is qs
- assert filter_attributes_by_product_types(qs, "...", None, None) is qs
+ assert filter_attributes_by_product_types(qs, "...", "", None, None) is qs
+ assert filter_attributes_by_product_types(qs, "...", None, None, None) is qs
-def test_attributes_filter_by_product_type_with_unsupported_field(customer_user):
+def test_attributes_filter_by_product_type_with_unsupported_field(
+ customer_user, channel_USD
+):
"""Ensure using an unknown field to filter attributes by raises a NotImplemented
exception.
"""
@@ -349,18 +355,20 @@ def test_attributes_filter_by_product_type_with_unsupported_field(customer_user)
qs = Attribute.objects.all()
with pytest.raises(NotImplementedError) as exc:
- filter_attributes_by_product_types(qs, "in_space", "a-value", customer_user)
+ filter_attributes_by_product_types(
+ qs, "in_space", "a-value", customer_user, channel_USD.slug
+ )
assert exc.value.args == ("Filtering by in_space is unsupported",)
-def test_attributes_filter_by_non_existing_category_id(customer_user):
+def test_attributes_filter_by_non_existing_category_id(customer_user, channel_USD):
"""Ensure using a non-existing category ID returns an empty query set."""
category_id = graphene.Node.to_global_id("Category", -1)
mocked_qs = mock.MagicMock()
qs = filter_attributes_by_product_types(
- mocked_qs, "in_category", category_id, customer_user
+ mocked_qs, "in_category", category_id, customer_user, channel_USD.slug
)
assert qs == mocked_qs.none.return_value
@@ -370,12 +378,15 @@ def test_attributes_in_collection_query(
user_api_client,
product_type,
category,
- collection,
+ published_collection,
collection_with_products,
tested_field,
+ channel_USD,
):
if "Collection" in tested_field:
- filtered_by_node_id = graphene.Node.to_global_id("Collection", collection.pk)
+ filtered_by_node_id = graphene.Node.to_global_id(
+ "Collection", published_collection.pk
+ )
elif "Category" in tested_field:
filtered_by_node_id = graphene.Node.to_global_id("Category", category.pk)
else:
@@ -393,24 +404,18 @@ def test_attributes_in_collection_query(
)
other_product_type.product_attributes.add(other_attribute)
other_product = Product.objects.create(
- name="Another Product",
- product_type=other_product_type,
- category=other_category,
- is_published=True,
+ name="Another Product", product_type=other_product_type, category=other_category
)
# Create another collection with products but shouldn't get matched
# as we don't look for this other collection
other_collection = Collection.objects.create(
- name="Other Collection",
- slug="other-collection",
- is_published=True,
- description="Description",
+ name="Other Collection", slug="other-collection", description="Description",
)
other_collection.products.add(other_product)
query = """
- query($nodeID: ID!) {
+ query($nodeID: ID!, $channel: String) {
attributes(first: 20, %(filter_input)s) {
edges {
node {
@@ -423,9 +428,11 @@ def test_attributes_in_collection_query(
}
"""
- query = query % {"filter_input": "filter: { %s: $nodeID }" % tested_field}
+ query = query % {
+ "filter_input": "filter: { %s: $nodeID, channel: $channel }" % tested_field
+ }
- variables = {"nodeID": filtered_by_node_id}
+ variables = {"nodeID": filtered_by_node_id, "channel": channel_USD.slug}
content = get_graphql_content(user_api_client.post_graphql(query, variables))
attributes_data = content["data"]["attributes"]["edges"]
@@ -1187,7 +1194,9 @@ def test_resolve_attribute_value_type(raw_value, expected_type):
assert resolve_attribute_value_type(raw_value) == expected_type
-def test_resolve_assigned_attribute_without_values(api_client, product_type, product):
+def test_resolve_assigned_attribute_without_values(
+ api_client, product_type, product, channel_USD
+):
"""Ensure the attributes assigned to a product type are resolved even if
the product doesn't provide any value for it or is not directly associated to it.
"""
@@ -1202,8 +1211,8 @@ def test_resolve_assigned_attribute_without_values(api_client, product_type, pro
products = get_graphql_content(
api_client.post_graphql(
"""
- {
- products(first: 10) {
+ query ($channel: String) {
+ products(first: 10, channel: $channel) {
edges {
node {
attributes {
@@ -1228,7 +1237,8 @@ def test_resolve_assigned_attribute_without_values(api_client, product_type, pro
}
}
}
- """
+ """,
+ {"channel": channel_USD.slug},
)
)["data"]["products"]["edges"]
@@ -1582,11 +1592,11 @@ def test_unassign_attributes_not_in_product_type(
def test_retrieve_product_attributes_input_type(
- staff_api_client, product, permission_manage_products
+ staff_api_client, product, permission_manage_products, channel_USD
):
query = """
- {
- products(first: 10) {
+ query ($channel: String){
+ products(first: 10, channel: $channel) {
edges {
node {
attributes {
@@ -1601,8 +1611,11 @@ def test_retrieve_product_attributes_input_type(
}
"""
+ variables = {"channel": channel_USD.slug}
found_products = get_graphql_content(
- staff_api_client.post_graphql(query, permissions=[permission_manage_products])
+ staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
)["data"]["products"]["edges"]
assert len(found_products) == 1
@@ -2030,7 +2043,7 @@ def test_filter_attributes_by_global_id_list(api_client, attribute_list):
def test_filter_attributes_in_category_not_visible_in_listings_by_customer(
- user_api_client, product_list, weight_attribute
+ user_api_client, product_list, weight_attribute, channel_USD
):
# given
product_type = ProductType.objects.create(
@@ -2043,8 +2056,8 @@ def test_filter_attributes_in_category_not_visible_in_listings_by_customer(
last_product = product_list[-1]
last_product.product_type = product_type
- last_product.visible_in_listings = False
- last_product.save(update_fields=["visible_in_listings", "product_type"])
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(visible_in_listings=False)
associate_attribute_values_to_instance(
product_list[-1], weight_attribute, weight_attribute.values.first()
@@ -2054,7 +2067,10 @@ def test_filter_attributes_in_category_not_visible_in_listings_by_customer(
category = last_product.category
variables = {
- "filters": {"inCategory": graphene.Node.to_global_id("Category", category.pk)}
+ "filters": {
+ "inCategory": graphene.Node.to_global_id("Category", category.pk),
+ "channel": channel_USD.slug,
+ }
}
# when
@@ -2070,7 +2086,11 @@ def test_filter_attributes_in_category_not_visible_in_listings_by_customer(
def test_filter_attributes_in_category_not_visible_in_listings_by_staff_with_perm(
- staff_api_client, product_list, weight_attribute, permission_manage_products
+ staff_api_client,
+ product_list,
+ weight_attribute,
+ permission_manage_products,
+ channel_USD,
):
# given
staff_api_client.user.user_permissions.add(permission_manage_products)
@@ -2085,8 +2105,8 @@ def test_filter_attributes_in_category_not_visible_in_listings_by_staff_with_per
last_product = product_list[-1]
last_product.product_type = product_type
- last_product.visible_in_listings = False
- last_product.save(update_fields=["visible_in_listings", "product_type"])
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(visible_in_listings=False)
associate_attribute_values_to_instance(
product_list[-1], weight_attribute, weight_attribute.values.first()
@@ -2096,7 +2116,10 @@ def test_filter_attributes_in_category_not_visible_in_listings_by_staff_with_per
category = last_product.category
variables = {
- "filters": {"inCategory": graphene.Node.to_global_id("Category", category.pk)}
+ "filters": {
+ "inCategory": graphene.Node.to_global_id("Category", category.pk),
+ "channel": channel_USD.slug,
+ }
}
# when
@@ -2109,7 +2132,11 @@ def test_filter_attributes_in_category_not_visible_in_listings_by_staff_with_per
def test_filter_attributes_in_category_not_visible_in_listings_by_staff_without_perm(
- staff_api_client, product_list, weight_attribute, permission_manage_products
+ staff_api_client,
+ product_list,
+ weight_attribute,
+ permission_manage_products,
+ channel_USD,
):
# given
product_type = ProductType.objects.create(
@@ -2122,8 +2149,8 @@ def test_filter_attributes_in_category_not_visible_in_listings_by_staff_without_
last_product = product_list[-1]
last_product.product_type = product_type
- last_product.visible_in_listings = False
- last_product.save(update_fields=["visible_in_listings", "product_type"])
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(visible_in_listings=False)
associate_attribute_values_to_instance(
product_list[-1], weight_attribute, weight_attribute.values.first()
@@ -2133,7 +2160,10 @@ def test_filter_attributes_in_category_not_visible_in_listings_by_staff_without_
category = last_product.category
variables = {
- "filters": {"inCategory": graphene.Node.to_global_id("Category", category.pk)}
+ "filters": {
+ "inCategory": graphene.Node.to_global_id("Category", category.pk),
+ "channel": channel_USD.slug,
+ }
}
# when
@@ -2149,7 +2179,11 @@ def test_filter_attributes_in_category_not_visible_in_listings_by_staff_without_
def test_filter_attributes_in_category_not_visible_in_listings_by_app_with_perm(
- app_api_client, product_list, weight_attribute, permission_manage_products
+ app_api_client,
+ product_list,
+ weight_attribute,
+ permission_manage_products,
+ channel_USD,
):
# given
app_api_client.app.permissions.add(permission_manage_products)
@@ -2164,8 +2198,8 @@ def test_filter_attributes_in_category_not_visible_in_listings_by_app_with_perm(
last_product = product_list[-1]
last_product.product_type = product_type
- last_product.visible_in_listings = False
- last_product.save(update_fields=["visible_in_listings", "product_type"])
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(visible_in_listings=False)
associate_attribute_values_to_instance(
product_list[-1], weight_attribute, weight_attribute.values.first()
@@ -2175,7 +2209,10 @@ def test_filter_attributes_in_category_not_visible_in_listings_by_app_with_perm(
category = last_product.category
variables = {
- "filters": {"inCategory": graphene.Node.to_global_id("Category", category.pk)}
+ "filters": {
+ "inCategory": graphene.Node.to_global_id("Category", category.pk),
+ "channel": channel_USD.slug,
+ }
}
# when
@@ -2188,7 +2225,11 @@ def test_filter_attributes_in_category_not_visible_in_listings_by_app_with_perm(
def test_filter_attributes_in_category_not_visible_in_listings_by_app_without_perm(
- app_api_client, product_list, weight_attribute, permission_manage_products
+ app_api_client,
+ product_list,
+ weight_attribute,
+ permission_manage_products,
+ channel_USD,
):
# given
product_type = ProductType.objects.create(
@@ -2201,8 +2242,8 @@ def test_filter_attributes_in_category_not_visible_in_listings_by_app_without_pe
last_product = product_list[-1]
last_product.product_type = product_type
- last_product.visible_in_listings = False
- last_product.save(update_fields=["visible_in_listings", "product_type"])
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(visible_in_listings=False)
associate_attribute_values_to_instance(
product_list[-1], weight_attribute, weight_attribute.values.first()
@@ -2212,7 +2253,10 @@ def test_filter_attributes_in_category_not_visible_in_listings_by_app_without_pe
category = last_product.category
variables = {
- "filters": {"inCategory": graphene.Node.to_global_id("Category", category.pk)}
+ "filters": {
+ "inCategory": graphene.Node.to_global_id("Category", category.pk),
+ "channel": channel_USD.slug,
+ }
}
# when
@@ -2228,7 +2272,7 @@ def test_filter_attributes_in_category_not_visible_in_listings_by_app_without_pe
def test_filter_attributes_in_category_not_published_by_customer(
- user_api_client, product_list, weight_attribute
+ user_api_client, product_list, weight_attribute, channel_USD
):
# given
product_type = ProductType.objects.create(
@@ -2241,8 +2285,8 @@ def test_filter_attributes_in_category_not_published_by_customer(
last_product = product_list[-1]
last_product.product_type = product_type
- last_product.is_published = False
- last_product.save(update_fields=["is_published", "product_type"])
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(is_published=False)
associate_attribute_values_to_instance(
product_list[-1], weight_attribute, weight_attribute.values.first()
@@ -2252,7 +2296,10 @@ def test_filter_attributes_in_category_not_published_by_customer(
category = last_product.category
variables = {
- "filters": {"inCategory": graphene.Node.to_global_id("Category", category.pk)}
+ "filters": {
+ "inCategory": graphene.Node.to_global_id("Category", category.pk),
+ "channel": channel_USD.slug,
+ },
}
# when
@@ -2268,7 +2315,11 @@ def test_filter_attributes_in_category_not_published_by_customer(
def test_filter_attributes_in_category_not_published_by_staff_with_perm(
- staff_api_client, product_list, weight_attribute, permission_manage_products
+ staff_api_client,
+ product_list,
+ weight_attribute,
+ permission_manage_products,
+ channel_USD,
):
# given
staff_api_client.user.user_permissions.add(permission_manage_products)
@@ -2283,8 +2334,8 @@ def test_filter_attributes_in_category_not_published_by_staff_with_perm(
last_product = product_list[-1]
last_product.product_type = product_type
- last_product.is_published = False
- last_product.save(update_fields=["is_published", "product_type"])
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(is_published=False)
associate_attribute_values_to_instance(
product_list[-1], weight_attribute, weight_attribute.values.first()
@@ -2294,7 +2345,10 @@ def test_filter_attributes_in_category_not_published_by_staff_with_perm(
category = last_product.category
variables = {
- "filters": {"inCategory": graphene.Node.to_global_id("Category", category.pk)}
+ "filters": {
+ "inCategory": graphene.Node.to_global_id("Category", category.pk),
+ "channel": channel_USD.slug,
+ }
}
# when
@@ -2307,7 +2361,11 @@ def test_filter_attributes_in_category_not_published_by_staff_with_perm(
def test_filter_attributes_in_category_not_published_by_staff_without_perm(
- staff_api_client, product_list, weight_attribute, permission_manage_products
+ staff_api_client,
+ product_list,
+ weight_attribute,
+ permission_manage_products,
+ channel_USD,
):
# given
product_type = ProductType.objects.create(
@@ -2320,8 +2378,8 @@ def test_filter_attributes_in_category_not_published_by_staff_without_perm(
last_product = product_list[-1]
last_product.product_type = product_type
- last_product.is_published = False
- last_product.save(update_fields=["is_published", "product_type"])
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(is_published=False)
associate_attribute_values_to_instance(
product_list[-1], weight_attribute, weight_attribute.values.first()
@@ -2331,7 +2389,10 @@ def test_filter_attributes_in_category_not_published_by_staff_without_perm(
category = last_product.category
variables = {
- "filters": {"inCategory": graphene.Node.to_global_id("Category", category.pk)}
+ "filters": {
+ "inCategory": graphene.Node.to_global_id("Category", category.pk),
+ "channel": channel_USD.slug,
+ }
}
# when
@@ -2347,7 +2408,11 @@ def test_filter_attributes_in_category_not_published_by_staff_without_perm(
def test_filter_attributes_in_category_not_published_by_app_with_perm(
- app_api_client, product_list, weight_attribute, permission_manage_products
+ app_api_client,
+ product_list,
+ weight_attribute,
+ permission_manage_products,
+ channel_USD,
):
# given
app_api_client.app.permissions.add(permission_manage_products)
@@ -2362,8 +2427,8 @@ def test_filter_attributes_in_category_not_published_by_app_with_perm(
last_product = product_list[-1]
last_product.product_type = product_type
- last_product.is_published = False
- last_product.save(update_fields=["is_published", "product_type"])
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(is_published=False)
associate_attribute_values_to_instance(
product_list[-1], weight_attribute, weight_attribute.values.first()
@@ -2373,7 +2438,10 @@ def test_filter_attributes_in_category_not_published_by_app_with_perm(
category = last_product.category
variables = {
- "filters": {"inCategory": graphene.Node.to_global_id("Category", category.pk)}
+ "filters": {
+ "inCategory": graphene.Node.to_global_id("Category", category.pk),
+ "channel": channel_USD.slug,
+ }
}
# when
@@ -2386,7 +2454,11 @@ def test_filter_attributes_in_category_not_published_by_app_with_perm(
def test_filter_attributes_in_category_not_published_by_app_without_perm(
- app_api_client, product_list, weight_attribute, permission_manage_products
+ app_api_client,
+ product_list,
+ weight_attribute,
+ permission_manage_products,
+ channel_USD,
):
# given
product_type = ProductType.objects.create(
@@ -2399,8 +2471,8 @@ def test_filter_attributes_in_category_not_published_by_app_without_perm(
last_product = product_list[-1]
last_product.product_type = product_type
- last_product.is_published = False
- last_product.save(update_fields=["is_published", "product_type"])
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(is_published=False)
associate_attribute_values_to_instance(
product_list[-1], weight_attribute, weight_attribute.values.first()
@@ -2410,7 +2482,10 @@ def test_filter_attributes_in_category_not_published_by_app_without_perm(
category = last_product.category
variables = {
- "filters": {"inCategory": graphene.Node.to_global_id("Category", category.pk)}
+ "filters": {
+ "inCategory": graphene.Node.to_global_id("Category", category.pk),
+ "channel": channel_USD.slug,
+ }
}
# when
@@ -2426,7 +2501,7 @@ def test_filter_attributes_in_category_not_published_by_app_without_perm(
def test_filter_attributes_in_collection_not_visible_in_listings_by_customer(
- user_api_client, product_list, weight_attribute, collection
+ user_api_client, product_list, weight_attribute, collection, channel_USD
):
# given
product_type = ProductType.objects.create(
@@ -2439,8 +2514,8 @@ def test_filter_attributes_in_collection_not_visible_in_listings_by_customer(
last_product = product_list[-1]
last_product.product_type = product_type
- last_product.visible_in_listings = False
- last_product.save(update_fields=["visible_in_listings", "product_type"])
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(visible_in_listings=False)
for product in product_list:
collection.products.add(product)
@@ -2453,7 +2528,8 @@ def test_filter_attributes_in_collection_not_visible_in_listings_by_customer(
variables = {
"filters": {
- "inCollection": graphene.Node.to_global_id("Collection", collection.pk)
+ "inCollection": graphene.Node.to_global_id("Collection", collection.pk),
+ "channel": channel_USD.slug,
}
}
@@ -2467,7 +2543,7 @@ def test_filter_attributes_in_collection_not_visible_in_listings_by_customer(
def test_filter_in_collection_not_published_by_customer(
- user_api_client, product_list, weight_attribute, collection
+ user_api_client, product_list, weight_attribute, collection, channel_USD
):
# given
product_type = ProductType.objects.create(
@@ -2480,8 +2556,8 @@ def test_filter_in_collection_not_published_by_customer(
last_product = product_list[-1]
last_product.product_type = product_type
- last_product.is_published = False
- last_product.save(update_fields=["is_published", "product_type"])
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(is_published=False)
for product in product_list:
collection.products.add(product)
@@ -2494,7 +2570,8 @@ def test_filter_in_collection_not_published_by_customer(
variables = {
"filters": {
- "inCollection": graphene.Node.to_global_id("Collection", collection.pk)
+ "inCollection": graphene.Node.to_global_id("Collection", collection.pk),
+ "channel": channel_USD.slug,
}
}
@@ -2516,6 +2593,7 @@ def test_filter_in_collection_not_published_by_staff_with_perm(
weight_attribute,
permission_manage_products,
collection,
+ channel_USD,
):
# given
staff_api_client.user.user_permissions.add(permission_manage_products)
@@ -2530,8 +2608,8 @@ def test_filter_in_collection_not_published_by_staff_with_perm(
last_product = product_list[-1]
last_product.product_type = product_type
- last_product.is_published = False
- last_product.save(update_fields=["is_published", "product_type"])
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(is_published=False)
for product in product_list:
collection.products.add(product)
@@ -2544,7 +2622,8 @@ def test_filter_in_collection_not_published_by_staff_with_perm(
variables = {
"filters": {
- "inCollection": graphene.Node.to_global_id("Collection", collection.pk)
+ "inCollection": graphene.Node.to_global_id("Collection", collection.pk),
+ "channel": channel_USD.slug,
}
}
@@ -2563,6 +2642,7 @@ def test_filter_in_collection_not_published_by_staff_without_perm(
weight_attribute,
permission_manage_products,
collection,
+ channel_USD,
):
# given
product_type = ProductType.objects.create(
@@ -2575,8 +2655,8 @@ def test_filter_in_collection_not_published_by_staff_without_perm(
last_product = product_list[-1]
last_product.product_type = product_type
- last_product.is_published = False
- last_product.save(update_fields=["is_published", "product_type"])
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(is_published=False)
for product in product_list:
collection.products.add(product)
@@ -2589,7 +2669,8 @@ def test_filter_in_collection_not_published_by_staff_without_perm(
variables = {
"filters": {
- "inCollection": graphene.Node.to_global_id("Collection", collection.pk)
+ "inCollection": graphene.Node.to_global_id("Collection", collection.pk),
+ "channel": channel_USD.slug,
}
}
@@ -2611,6 +2692,7 @@ def test_filter_in_collection_not_published_by_app_with_perm(
weight_attribute,
permission_manage_products,
collection,
+ channel_USD,
):
# given
app_api_client.app.permissions.add(permission_manage_products)
@@ -2625,8 +2707,8 @@ def test_filter_in_collection_not_published_by_app_with_perm(
last_product = product_list[-1]
last_product.product_type = product_type
- last_product.is_published = False
- last_product.save(update_fields=["is_published", "product_type"])
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(is_published=False)
for product in product_list:
collection.products.add(product)
@@ -2639,7 +2721,8 @@ def test_filter_in_collection_not_published_by_app_with_perm(
variables = {
"filters": {
- "inCollection": graphene.Node.to_global_id("Collection", collection.pk)
+ "inCollection": graphene.Node.to_global_id("Collection", collection.pk),
+ "channel": channel_USD.slug,
}
}
@@ -2658,6 +2741,7 @@ def test_filter_in_collection_not_published_by_app_without_perm(
weight_attribute,
permission_manage_products,
collection,
+ channel_USD,
):
# given
product_type = ProductType.objects.create(
@@ -2670,8 +2754,8 @@ def test_filter_in_collection_not_published_by_app_without_perm(
last_product = product_list[-1]
last_product.product_type = product_type
- last_product.is_published = False
- last_product.save(update_fields=["is_published", "product_type"])
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(is_published=False)
for product in product_list:
collection.products.add(product)
@@ -2684,7 +2768,8 @@ def test_filter_in_collection_not_published_by_app_without_perm(
variables = {
"filters": {
- "inCollection": graphene.Node.to_global_id("Collection", collection.pk)
+ "inCollection": graphene.Node.to_global_id("Collection", collection.pk),
+ "channel": channel_USD.slug,
}
}
@@ -2749,7 +2834,7 @@ def test_sort_attributes_by_default_sorting(api_client):
@pytest.mark.parametrize("is_variant", (True, False))
def test_attributes_of_products_are_sorted(
- staff_api_client, product, color_attribute, is_variant
+ user_api_client, product, color_attribute, is_variant, channel_USD
):
"""Ensures the attributes of products and variants are sorted."""
@@ -2757,8 +2842,8 @@ def test_attributes_of_products_are_sorted(
if is_variant:
query = """
- query($id: ID!) {
- productVariant(id: $id) {
+ query($id: ID!, $channel: String) {
+ productVariant(id: $id, channel: $channel) {
attributes {
attribute {
id
@@ -2769,8 +2854,8 @@ def test_attributes_of_products_are_sorted(
"""
else:
query = """
- query($id: ID!) {
- product(id: $id) {
+ query($id: ID!, $channel: String) {
+ product(id: $id, channel: $channel) {
attributes {
attribute {
id
@@ -2818,9 +2903,11 @@ def test_attributes_of_products_are_sorted(
node_id = graphene.Node.to_global_id("Product", product.pk)
# Retrieve the attributes
- data = get_graphql_content(staff_api_client.post_graphql(query, {"id": node_id}))[
- "data"
- ]
+ data = get_graphql_content(
+ user_api_client.post_graphql(
+ query, {"id": node_id, "channel": channel_USD.slug}
+ )
+ )["data"]
attributes = data["productVariant" if is_variant else "product"]["attributes"]
actual_order = [
int(graphene.Node.from_global_id(attr["attribute"]["id"])[1])
diff --git a/saleor/graphql/product/tests/test_bulk_delete.py b/saleor/graphql/product/tests/test_bulk_delete.py
index 3aaa9c7473..763e3bc9aa 100644
--- a/saleor/graphql/product/tests/test_bulk_delete.py
+++ b/saleor/graphql/product/tests/test_bulk_delete.py
@@ -1,8 +1,8 @@
-from decimal import Decimal
from unittest.mock import patch
import graphene
import pytest
+from django.utils import timezone
from prices import Money, TaxedMoney
from ....order import OrderStatus
@@ -13,9 +13,11 @@ from ....product.models import (
Category,
Collection,
Product,
+ ProductChannelListing,
ProductImage,
ProductType,
ProductVariant,
+ ProductVariantChannelListing,
)
from ...tests.utils import get_graphql_content
@@ -134,18 +136,19 @@ def test_delete_categories(staff_api_client, category_list, permission_manage_pr
).exists()
-@patch("saleor.product.utils.update_products_minimal_variant_prices_task")
+@patch("saleor.product.utils.update_products_discounted_prices_task")
def test_delete_categories_with_subcategories_and_products(
- mock_update_products_minimal_variant_prices_task,
+ mock_update_products_discounted_prices_task,
staff_api_client,
category_list,
permission_manage_products,
product,
category,
+ channel_USD,
+ channel_PLN,
):
product.category = category
category.parent = category_list[0]
- product.save()
category.save()
parent_product = Product.objects.get(pk=product.pk)
@@ -154,6 +157,20 @@ def test_delete_categories_with_subcategories_and_products(
parent_product.category = category_list[0]
parent_product.save()
+ ProductChannelListing.objects.bulk_create(
+ [
+ ProductChannelListing(
+ product=parent_product, channel=channel_USD, is_published=True
+ ),
+ ProductChannelListing(
+ product=parent_product,
+ channel=channel_PLN,
+ is_published=True,
+ publication_date=timezone.now(),
+ ),
+ ]
+ )
+
product_list = [product, parent_product]
variables = {
@@ -174,19 +191,25 @@ def test_delete_categories_with_subcategories_and_products(
id__in=[category.id for category in category_list]
).exists()
- mock_update_products_minimal_variant_prices_task.delay.assert_called_once()
+ mock_update_products_discounted_prices_task.delay.assert_called_once()
(
_call_args,
call_kwargs,
- ) = mock_update_products_minimal_variant_prices_task.delay.call_args
+ ) = mock_update_products_discounted_prices_task.delay.call_args
assert set(call_kwargs["product_ids"]) == set([p.pk for p in product_list])
for product in product_list:
product.refresh_from_db()
assert not product.category
- assert not product.is_published
- assert not product.publication_date
+
+ product_channel_listings = ProductChannelListing.objects.filter(
+ product__in=product_list
+ )
+ for product_channel_listing in product_channel_listings:
+ assert product_channel_listing.is_published is False
+ assert not product_channel_listing.publication_date
+ assert product_channel_listings.count() == 3
def test_delete_collections(
@@ -227,7 +250,7 @@ mutation productBulkDelete($ids: [ID]!) {
def test_delete_products(
- staff_api_client, product_list, permission_manage_products, order_list
+ staff_api_client, product_list, permission_manage_products, order_list, channel_USD
):
# given
query = DELETE_PRODUCTS_MUTATION
@@ -240,7 +263,7 @@ def test_delete_products(
draft_order_lines_pks = []
not_draft_order_lines_pks = []
for variant in [product_list[0].variants.first(), product_list[1].variants.first()]:
- net = variant.get_price()
+ net = variant.get_price(channel_USD.slug)
gross = Money(amount=net.amount, currency=net.currency)
order_line = OrderLine.objects.create(
@@ -297,6 +320,10 @@ def test_delete_products_variants_in_draft_order(
):
query = DELETE_PRODUCTS_MUTATION
+ assert ProductChannelListing.objects.filter(
+ product_id__in=[product.id for product in product_list]
+ ).exists()
+
variables = {
"ids": [
graphene.Node.to_global_id("Product", product.id)
@@ -312,6 +339,9 @@ def test_delete_products_variants_in_draft_order(
assert not Product.objects.filter(
id__in=[product.id for product in product_list]
).exists()
+ assert not ProductChannelListing.objects.filter(
+ product_id__in=[product.id for product in product_list]
+ ).exists()
def test_delete_product_images(
@@ -385,6 +415,10 @@ def test_delete_product_variants(
):
query = PRODUCT_VARIANT_BULK_DELETE_MUTATION
+ assert ProductVariantChannelListing.objects.filter(
+ variant_id__in=[variant.id for variant in product_variant_list]
+ ).exists()
+
variables = {
"ids": [
graphene.Node.to_global_id("ProductVariant", variant.id)
@@ -408,6 +442,7 @@ def test_delete_product_variants_in_draft_orders(
permission_manage_products,
order_line,
order_list,
+ channel_USD,
):
# given
query = PRODUCT_VARIANT_BULK_DELETE_MUTATION
@@ -418,7 +453,7 @@ def test_delete_product_variants_in_draft_orders(
draft_order.save(update_fields=["status"])
second_variant_in_draft = variants[1]
- net = second_variant_in_draft.get_price()
+ net = second_variant_in_draft.get_price(channel_USD.slug)
gross = Money(amount=net.amount, currency=net.currency)
second_draft_order = OrderLine.objects.create(
variant=second_variant_in_draft,
@@ -432,7 +467,7 @@ def test_delete_product_variants_in_draft_orders(
)
variant = variants[0]
- net = variant.get_price()
+ net = variant.get_price(channel_USD.slug)
gross = Money(amount=net.amount, currency=net.currency)
order_not_draft = order_list[-1]
order_line_not_in_draft = OrderLine.objects.create(
@@ -488,9 +523,9 @@ def test_delete_product_variants_delete_default_variant(
variants = ProductVariant.objects.bulk_create(
[
- ProductVariant(product=product, sku="1", price_amount=Decimal(10)),
- ProductVariant(product=product, sku="2", price_amount=Decimal(10)),
- ProductVariant(product=product, sku="3", price_amount=Decimal(10)),
+ ProductVariant(product=product, sku="1"),
+ ProductVariant(product=product, sku="2"),
+ ProductVariant(product=product, sku="3"),
]
)
@@ -534,8 +569,8 @@ def test_delete_product_variants_delete_all_product_variants(
variants = ProductVariant.objects.bulk_create(
[
- ProductVariant(product=product, sku="1", price_amount=Decimal(10)),
- ProductVariant(product=product, sku="2", price_amount=Decimal(10)),
+ ProductVariant(product=product, sku="1"),
+ ProductVariant(product=product, sku="2"),
]
)
diff --git a/saleor/graphql/product/tests/test_category.py b/saleor/graphql/product/tests/test_category.py
index 001a292675..b73fa6ccdd 100644
--- a/saleor/graphql/product/tests/test_category.py
+++ b/saleor/graphql/product/tests/test_category.py
@@ -7,12 +7,12 @@ from django.utils.text import slugify
from graphql_relay import to_global_id
from ....product.error_codes import ProductErrorCode
-from ....product.models import Category, Product
+from ....product.models import Category, Product, ProductChannelListing
from ....product.tests.utils import create_image, create_pdf_file_with_image_ext
from ...tests.utils import get_graphql_content, get_multipart_request_body
QUERY_CATEGORY = """
- query ($id: ID, $slug: String){
+ query ($id: ID, $slug: String, $channel: String){
category(
id: $id,
slug: $slug,
@@ -33,7 +33,7 @@ QUERY_CATEGORY = """
}
}
}
- products(first: 10) {
+ products(first: 10, channel: $channel) {
edges {
node {
id
@@ -45,11 +45,12 @@ QUERY_CATEGORY = """
"""
-def test_category_query_by_id(
- user_api_client, product,
-):
+def test_category_query_by_id(user_api_client, product, channel_USD):
category = Category.objects.first()
- variables = {"id": graphene.Node.to_global_id("Category", category.pk)}
+ variables = {
+ "id": graphene.Node.to_global_id("Category", category.pk),
+ "channel": channel_USD.slug,
+ }
response = user_api_client.post_graphql(QUERY_CATEGORY, variables=variables)
content = get_graphql_content(response)
@@ -60,11 +61,9 @@ def test_category_query_by_id(
assert len(category_data["children"]["edges"]) == category.get_children().count()
-def test_category_query_by_slug(
- user_api_client, product,
-):
+def test_category_query_by_slug(user_api_client, product, channel_USD):
category = Category.objects.first()
- variables = {"slug": category.slug}
+ variables = {"slug": category.slug, "channel": channel_USD.slug}
response = user_api_client.post_graphql(QUERY_CATEGORY, variables=variables)
content = get_graphql_content(response)
category_data = content["data"]["category"]
@@ -75,12 +74,13 @@ def test_category_query_by_slug(
def test_category_query_error_when_id_and_slug_provided(
- user_api_client, product, graphql_log_handler,
+ user_api_client, product, graphql_log_handler, channel_USD
):
category = Category.objects.first()
variables = {
"id": graphene.Node.to_global_id("Category", category.pk),
"slug": category.slug,
+ "channel": channel_USD.slug,
}
response = user_api_client.post_graphql(QUERY_CATEGORY, variables=variables)
assert graphql_log_handler.messages == [
@@ -91,7 +91,7 @@ def test_category_query_error_when_id_and_slug_provided(
def test_category_query_error_when_no_param(
- user_api_client, product, graphql_log_handler,
+ user_api_client, product, graphql_log_handler
):
variables = {}
response = user_api_client.post_graphql(QUERY_CATEGORY, variables=variables)
@@ -103,18 +103,18 @@ def test_category_query_error_when_no_param(
def test_query_category_product_only_visible_in_listings_as_customer(
- user_api_client, product_list
+ user_api_client, product_list, channel_USD
):
# given
category = Category.objects.first()
- product_list[0].visible_in_listings = False
- product_list[0].save(update_fields=["visible_in_listings"])
+ product_list[0].channel_listings.all().update(visible_in_listings=False)
product_count = Product.objects.count()
variables = {
"id": graphene.Node.to_global_id("Category", category.pk),
+ "channel": channel_USD.slug,
}
# when
@@ -126,18 +126,18 @@ def test_query_category_product_only_visible_in_listings_as_customer(
def test_query_category_product_only_visible_in_listings_as_staff_without_perm(
- staff_api_client, product_list
+ staff_api_client, product_list, channel_USD
):
# given
category = Category.objects.first()
- product_list[0].visible_in_listings = False
- product_list[0].save(update_fields=["visible_in_listings"])
+ product_list[0].channel_listings.all().update(visible_in_listings=False)
product_count = Product.objects.count()
variables = {
"id": graphene.Node.to_global_id("Category", category.pk),
+ "channel": channel_USD.slug,
}
# when
@@ -156,14 +156,11 @@ def test_query_category_product_only_visible_in_listings_as_staff_with_perm(
category = Category.objects.first()
- product_list[0].visible_in_listings = False
- product_list[0].save(update_fields=["visible_in_listings"])
+ product_list[0].channel_listings.all().update(visible_in_listings=False)
product_count = Product.objects.count()
- variables = {
- "id": graphene.Node.to_global_id("Category", category.pk),
- }
+ variables = {"id": graphene.Node.to_global_id("Category", category.pk)}
# when
response = staff_api_client.post_graphql(QUERY_CATEGORY, variables=variables)
@@ -174,18 +171,18 @@ def test_query_category_product_only_visible_in_listings_as_staff_with_perm(
def test_query_category_product_only_visible_in_listings_as_app_without_perm(
- app_api_client, product_list
+ app_api_client, product_list, channel_USD
):
# given
category = Category.objects.first()
- product_list[0].visible_in_listings = False
- product_list[0].save(update_fields=["visible_in_listings"])
+ product_list[0].channel_listings.all().update(visible_in_listings=False)
product_count = Product.objects.count()
variables = {
"id": graphene.Node.to_global_id("Category", category.pk),
+ "channel": channel_USD.slug,
}
# when
@@ -204,14 +201,11 @@ def test_query_category_product_only_visible_in_listings_as_app_with_perm(
category = Category.objects.first()
- product_list[0].visible_in_listings = False
- product_list[0].save(update_fields=["visible_in_listings"])
+ product_list[0].channel_listings.all().update(visible_in_listings=False)
product_count = Product.objects.count()
- variables = {
- "id": graphene.Node.to_global_id("Category", category.pk),
- }
+ variables = {"id": graphene.Node.to_global_id("Category", category.pk)}
# when
response = app_api_client.post_graphql(QUERY_CATEGORY, variables=variables)
@@ -735,9 +729,9 @@ def test_category_delete_mutation(
category.refresh_from_db()
-@patch("saleor.product.utils.update_products_minimal_variant_prices_task")
+@patch("saleor.product.utils.update_products_discounted_prices_task")
def test_category_delete_mutation_for_categories_tree(
- mock_update_products_minimal_variant_prices_task,
+ mock_update_products_discounted_prices_task,
staff_api_client,
categories_tree_with_published_products,
permission_manage_products,
@@ -758,22 +752,25 @@ def test_category_delete_mutation_for_categories_tree(
with pytest.raises(parent._meta.model.DoesNotExist):
parent.refresh_from_db()
- mock_update_products_minimal_variant_prices_task.delay.assert_called_once()
+ mock_update_products_discounted_prices_task.delay.assert_called_once()
(
_call_args,
call_kwargs,
- ) = mock_update_products_minimal_variant_prices_task.delay.call_args
+ ) = mock_update_products_discounted_prices_task.delay.call_args
assert set(call_kwargs["product_ids"]) == set(p.pk for p in product_list)
- for product in product_list:
- product.refresh_from_db()
- assert not product.is_published
- assert not product.publication_date
+ product_channel_listings = ProductChannelListing.objects.filter(
+ product__in=product_list
+ )
+ for product_channel_listing in product_channel_listings:
+ assert product_channel_listing.is_published is False
+ assert not product_channel_listing.publication_date
+ assert product_channel_listings.count() == 4
-@patch("saleor.product.utils.update_products_minimal_variant_prices_task")
+@patch("saleor.product.utils.update_products_discounted_prices_task")
def test_category_delete_mutation_for_children_from_categories_tree(
- mock_update_products_minimal_variant_prices_task,
+ mock_update_products_discounted_prices_task,
staff_api_client,
categories_tree_with_published_products,
permission_manage_products,
@@ -793,19 +790,27 @@ def test_category_delete_mutation_for_children_from_categories_tree(
with pytest.raises(child._meta.model.DoesNotExist):
child.refresh_from_db()
- mock_update_products_minimal_variant_prices_task.delay.assert_called_once_with(
+ mock_update_products_discounted_prices_task.delay.assert_called_once_with(
product_ids=[child_product.pk]
)
parent_product.refresh_from_db()
assert parent_product.category
- assert parent_product.is_published
- assert parent_product.publication_date
+ product_channel_listings = ProductChannelListing.objects.filter(
+ product=parent_product
+ )
+ for product_channel_listing in product_channel_listings:
+ assert product_channel_listing.is_published is True
+ assert product_channel_listing.publication_date
child_product.refresh_from_db()
assert not child_product.category
- assert not child_product.is_published
- assert not child_product.publication_date
+ product_channel_listings = ProductChannelListing.objects.filter(
+ product=child_product
+ )
+ for product_channel_listing in product_channel_listings:
+ assert product_channel_listing.is_published is False
+ assert not product_channel_listing.publication_date
LEVELED_CATEGORIES_QUERY = """
diff --git a/saleor/graphql/product/tests/test_collection.py b/saleor/graphql/product/tests/test_collection.py
index 167f2d4e2b..dad34f10e7 100644
--- a/saleor/graphql/product/tests/test_collection.py
+++ b/saleor/graphql/product/tests/test_collection.py
@@ -1,22 +1,21 @@
import json
-from datetime import date, timedelta
from unittest.mock import Mock
import graphene
import pytest
-from freezegun import freeze_time
from graphql_relay import to_global_id
-from ....product.error_codes import ProductErrorCode
+from ....product.error_codes import CollectionErrorCode, ProductErrorCode
from ....product.models import Collection, Product
from ....product.tests.utils import create_image, create_pdf_file_with_image_ext
from ...tests.utils import get_graphql_content, get_multipart_request_body
QUERY_COLLECTION = """
- query ($id: ID, $slug: String){
+ query ($id: ID, $slug: String, $channel: String){
collection(
id: $id,
slug: $slug,
+ channel: $channel,
) {
id
name
@@ -25,25 +24,27 @@ QUERY_COLLECTION = """
"""
-def test_collection_query_by_id(
- user_api_client, collection,
-):
- variables = {"id": graphene.Node.to_global_id("Collection", collection.pk)}
+def test_collection_query_by_id(user_api_client, published_collection, channel_USD):
+ variables = {
+ "id": graphene.Node.to_global_id("Collection", published_collection.pk),
+ "channel": channel_USD.slug,
+ }
response = user_api_client.post_graphql(QUERY_COLLECTION, variables=variables)
content = get_graphql_content(response)
collection_data = content["data"]["collection"]
assert collection_data is not None
- assert collection_data["name"] == collection.name
+ assert collection_data["name"] == published_collection.name
def test_collection_query_unpublished_collection_by_id_as_app(
- app_api_client, collection, permission_manage_products
+ app_api_client, unpublished_collection, permission_manage_products, channel_USD
):
# given
- collection.is_published = False
- collection.save(update_fields=["is_published"])
- variables = {"id": graphene.Node.to_global_id("Collection", collection.pk)}
+ variables = {
+ "id": graphene.Node.to_global_id("Collection", unpublished_collection.pk),
+ "channel": channel_USD.slug,
+ }
# when
response = app_api_client.post_graphql(
@@ -57,30 +58,29 @@ def test_collection_query_unpublished_collection_by_id_as_app(
content = get_graphql_content(response)
collection_data = content["data"]["collection"]
assert collection_data is not None
- assert collection_data["name"] == collection.name
+ assert collection_data["name"] == unpublished_collection.name
-def test_collection_query_by_slug(
- user_api_client, collection,
-):
- variables = {"slug": collection.slug}
+def test_collection_query_by_slug(user_api_client, published_collection, channel_USD):
+ variables = {
+ "slug": published_collection.slug,
+ "channel": channel_USD.slug,
+ }
response = user_api_client.post_graphql(QUERY_COLLECTION, variables=variables)
content = get_graphql_content(response)
collection_data = content["data"]["collection"]
assert collection_data is not None
- assert collection_data["name"] == collection.name
+ assert collection_data["name"] == published_collection.name
def test_collection_query_unpublished_collection_by_slug_as_staff(
- staff_api_client, collection, permission_manage_products
+ staff_api_client, unpublished_collection, permission_manage_products, channel_USD
):
# given
user = staff_api_client.user
user.user_permissions.add(permission_manage_products)
- collection.is_published = False
- collection.save(update_fields=["is_published"])
- variables = {"slug": collection.slug}
+ variables = {"slug": unpublished_collection.slug, "channel": channel_USD.slug}
# when
response = staff_api_client.post_graphql(QUERY_COLLECTION, variables=variables)
@@ -89,16 +89,14 @@ def test_collection_query_unpublished_collection_by_slug_as_staff(
content = get_graphql_content(response)
collection_data = content["data"]["collection"]
assert collection_data is not None
- assert collection_data["name"] == collection.name
+ assert collection_data["name"] == unpublished_collection.name
-def test_collection_query_unpublished_collection_by_slug_and_anonympus_user(
- api_client, collection,
+def test_collection_query_unpublished_collection_by_slug_and_anonymous_user(
+ api_client, unpublished_collection, channel_USD
):
# given
- collection.is_published = False
- collection.save(update_fields=["is_published"])
- variables = {"slug": collection.slug}
+ variables = {"slug": unpublished_collection.slug, "channel": channel_USD.slug}
# when
response = api_client.post_graphql(QUERY_COLLECTION, variables=variables)
@@ -138,17 +136,16 @@ def test_collection_query_error_when_no_param(
def test_collections_query(
user_api_client,
- staff_api_client,
- collection,
- draft_collection,
+ published_collection,
+ unpublished_collection,
permission_manage_products,
+ channel_USD,
):
query = """
- query Collections {
- collections(first: 2) {
+ query Collections ($channel: String) {
+ collections(first:2, channel: $channel) {
edges {
node {
- isPublished
name
slug
description
@@ -162,17 +159,76 @@ def test_collections_query(
"""
# query public collections only as regular user
- response = user_api_client.post_graphql(query)
+ variables = {"channel": channel_USD.slug}
+ response = user_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
edges = content["data"]["collections"]["edges"]
assert len(edges) == 1
collection_data = edges[0]["node"]
- assert collection_data["isPublished"]
- assert collection_data["name"] == collection.name
- assert collection_data["slug"] == collection.slug
- assert collection_data["description"] == collection.description
- assert collection_data["products"]["totalCount"] == collection.products.count()
+ assert collection_data["name"] == published_collection.name
+ assert collection_data["slug"] == published_collection.slug
+ assert collection_data["description"] == published_collection.description
+ assert (
+ collection_data["products"]["totalCount"]
+ == published_collection.products.count()
+ )
+
+def test_collections_query_as_staff(
+ staff_api_client,
+ published_collection,
+ unpublished_collection_PLN,
+ permission_manage_products,
+ channel_USD,
+):
+ query = """
+ query Collections($channel: String) {
+ collections(first: 2, channel: $channel) {
+ edges {
+ node {
+ name
+ slug
+ description
+ products {
+ totalCount
+ }
+ }
+ }
+ }
+ }
+ """
+ # query all collections only as a staff user with proper permissions
+ variables = {"channel": channel_USD.slug}
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ response = staff_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ edges = content["data"]["collections"]["edges"]
+ assert len(edges) == 1
+
+
+def test_collections_query_as_staff_without_channel(
+ staff_api_client,
+ published_collection,
+ unpublished_collection_PLN,
+ permission_manage_products,
+ channel_USD,
+):
+ query = """
+ query Collections($channel: String) {
+ collections(first: 2, channel: $channel) {
+ edges {
+ node {
+ name
+ slug
+ description
+ products {
+ totalCount
+ }
+ }
+ }
+ }
+ }
+ """
# query all collections only as a staff user with proper permissions
staff_api_client.user.user_permissions.add(permission_manage_products)
response = staff_api_client.post_graphql(query)
@@ -182,8 +238,8 @@ def test_collections_query(
GET_FILTERED_PRODUCTS_COLLECTION_QUERY = """
-query CollectionProducts($id: ID!, $filters: ProductFilterInput) {
- collection(id: $id) {
+query CollectionProducts($id: ID!,$channel: String, $filters: ProductFilterInput) {
+ collection(id: $id, channel: $channel) {
products(first: 10, filter: $filters) {
edges {
node {
@@ -203,20 +259,21 @@ query CollectionProducts($id: ID!, $filters: ProductFilterInput) {
"""
-def test_filter_collection_products(user_api_client, product_list, collection):
+def test_filter_collection_products(
+ user_api_client, product_list, published_collection, channel_USD
+):
# given
query = GET_FILTERED_PRODUCTS_COLLECTION_QUERY
for product in product_list:
- collection.products.add(product)
+ published_collection.products.add(product)
- p1 = product_list[0]
- p1.is_published = False
- p1.save(update_fields=["is_published"])
+ product = product_list[0]
variables = {
- "id": graphene.Node.to_global_id("Collection", collection.pk),
- "filters": {"isPublished": True},
+ "id": graphene.Node.to_global_id("Collection", published_collection.pk),
+ "filters": {"search": product.name},
+ "channel": channel_USD.slug,
}
# when
@@ -224,32 +281,31 @@ def test_filter_collection_products(user_api_client, product_list, collection):
# then
content = get_graphql_content(response)
- products_data = content["data"]["collection"]["products"]["edges"]
+ product_data = content["data"]["collection"]["products"]["edges"][0]["node"]
- assert {node["node"]["id"] for node in products_data} == {
- graphene.Node.to_global_id("Product", product.pk)
- for product in product_list[1:]
- }
+ assert product_data["id"] == graphene.Node.to_global_id("Product", product.pk)
def test_filter_collection_products_by_multiple_attributes(
user_api_client,
- collection,
+ published_collection,
product_with_two_variants,
product_with_multiple_values_attributes,
+ channel_USD,
):
# given
- collection.products.set(
+ published_collection.products.set(
[product_with_two_variants, product_with_multiple_values_attributes]
)
- assert collection.products.count() == 2
+ assert published_collection.products.count() == 2
filters = {
"attributes": [{"slug": "modes", "values": ["eco"]}],
}
variables = {
- "id": graphene.Node.to_global_id("Collection", collection.pk),
+ "id": graphene.Node.to_global_id("Collection", published_collection.pk),
"filters": filters,
+ "channel": channel_USD.slug,
}
# when
@@ -277,8 +333,7 @@ CREATE_COLLECTION_MUTATION = """
mutation createCollection(
$name: String!, $slug: String, $description: String,
$descriptionJson: JSONString, $products: [ID],
- $backgroundImage: Upload, $backgroundImageAlt: String,
- $isPublished: Boolean, $publicationDate: Date) {
+ $backgroundImage: Upload, $backgroundImageAlt: String) {
collectionCreate(
input: {
name: $name,
@@ -287,9 +342,7 @@ CREATE_COLLECTION_MUTATION = """
descriptionJson: $descriptionJson,
products: $products,
backgroundImage: $backgroundImage,
- backgroundImageAlt: $backgroundImageAlt,
- isPublished: $isPublished,
- publicationDate: $publicationDate}) {
+ backgroundImageAlt: $backgroundImageAlt}) {
collection {
name
slug
@@ -298,13 +351,11 @@ CREATE_COLLECTION_MUTATION = """
products {
totalCount
}
- publicationDate
- isPublished
backgroundImage{
alt
}
}
- productErrors {
+ collectionErrors {
field
message
code
@@ -335,7 +386,6 @@ def test_create_collection(
slug = "test-slug"
description = "test-description"
description_json = json.dumps({"content": "description"})
- publication_date = date.today()
variables = {
"name": name,
"slug": slug,
@@ -344,8 +394,6 @@ def test_create_collection(
"products": product_ids,
"backgroundImage": image_name,
"backgroundImageAlt": image_alt,
- "isPublished": True,
- "publicationDate": publication_date,
}
body = get_multipart_request_body(query, variables, image_file, image_name)
response = staff_api_client.post_multipart(
@@ -357,7 +405,6 @@ def test_create_collection(
assert data["slug"] == slug
assert data["description"] == description
assert data["descriptionJson"] == description_json
- assert data["publicationDate"] == publication_date.isoformat()
assert data["products"]["totalCount"] == len(product_ids)
collection = Collection.objects.get(slug=slug)
assert collection.background_image.file
@@ -365,34 +412,6 @@ def test_create_collection(
assert data["backgroundImage"]["alt"] == image_alt
-@freeze_time("2020-03-18 12:00:00")
-def test_create_collection_updates_publication_Date(
- monkeypatch, staff_api_client, permission_manage_products
-):
- query = CREATE_COLLECTION_MUTATION
-
- mock_create_thumbnails = Mock(return_value=None)
- monkeypatch.setattr(
- (
- "saleor.product.thumbnails."
- "create_collection_background_image_thumbnails.delay"
- ),
- mock_create_thumbnails,
- )
- variables = {
- "name": "test-name",
- "slug": "test-slug",
- "isPublished": True,
- }
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_products]
- )
- content = get_graphql_content(response)
- data = content["data"]["collectionCreate"]["collection"]
- assert data["publicationDate"] == "2020-03-18"
- assert data["isPublished"] is True
-
-
def test_create_collection_without_background_image(
monkeypatch, staff_api_client, product_list, permission_manage_products
):
@@ -407,7 +426,7 @@ def test_create_collection_without_background_image(
mock_create_thumbnails,
)
- variables = {"name": "test-name", "slug": "test-slug", "isPublished": True}
+ variables = {"name": "test-name", "slug": "test-slug"}
response = staff_api_client.post_graphql(
query, variables, permissions=[permission_manage_products]
)
@@ -425,7 +444,7 @@ def test_create_collection_without_background_image(
),
)
def test_create_collection_with_given_slug(
- staff_api_client, permission_manage_products, input_slug, expected_slug
+ staff_api_client, permission_manage_products, input_slug, expected_slug, channel_USD
):
query = CREATE_COLLECTION_MUTATION
name = "Test collection"
@@ -435,12 +454,12 @@ def test_create_collection_with_given_slug(
)
content = get_graphql_content(response)
data = content["data"]["collectionCreate"]
- assert not data["productErrors"]
+ assert not data["collectionErrors"]
assert data["collection"]["slug"] == expected_slug
def test_create_collection_name_with_unicode(
- staff_api_client, permission_manage_products
+ staff_api_client, permission_manage_products, channel_USD
):
query = CREATE_COLLECTION_MUTATION
name = "わたし わ にっぽん です"
@@ -450,7 +469,7 @@ def test_create_collection_name_with_unicode(
)
content = get_graphql_content(response)
data = content["data"]["collectionCreate"]
- assert not data["productErrors"]
+ assert not data["collectionErrors"]
assert data["collection"]["name"] == name
assert data["collection"]["slug"] == "わたし-わ-にっぽん-です"
@@ -460,18 +479,15 @@ def test_update_collection(
):
query = """
mutation updateCollection(
- $name: String!, $slug: String!, $description: String, $id: ID!,
- $isPublished: Boolean!, $publicationDate: Date) {
+ $name: String!, $slug: String!, $description: String, $id: ID!) {
collectionUpdate(
- id: $id, input: {name: $name, slug: $slug, description: $description,
- isPublished: $isPublished, publicationDate: $publicationDate}) {
+ id: $id, input: {name: $name, slug: $slug, description: $description}) {
collection {
name
slug
description
- publicationDate
}
}
}
@@ -489,14 +505,11 @@ def test_update_collection(
name = "new-name"
slug = "new-slug"
description = "new-description"
- publication_date = date.today() + timedelta(days=5)
variables = {
"name": name,
"slug": slug,
"description": description,
"id": to_global_id("Collection", collection.id),
- "isPublished": True,
- "publicationDate": publication_date,
}
response = staff_api_client.post_graphql(
query, variables, permissions=[permission_manage_products]
@@ -505,53 +518,18 @@ def test_update_collection(
data = content["data"]["collectionUpdate"]["collection"]
assert data["name"] == name
assert data["slug"] == slug
- assert data["publicationDate"] == publication_date.isoformat()
assert mock_create_thumbnails.call_count == 0
-@freeze_time("2020-03-18 12:00:00")
-def test_update_collection_sets_publication_date(
- collection, staff_api_client, permission_manage_products
-):
- query = """
- mutation updateCollection(
- $name: String!, $slug: String!, $id: ID!,$isPublished: Boolean!) {
- collectionUpdate(
- id: $id, input: {name: $name, slug: $slug, isPublished: $isPublished}) {
- collection {
- publicationDate
- isPublished
- }
- }
- }
- """
- variables = {
- "name": "name",
- "slug": "slug",
- "id": to_global_id("Collection", collection.id),
- "isPublished": True,
- }
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_products]
- )
- content = get_graphql_content(response)
- data = content["data"]["collectionUpdate"]["collection"]
- assert data["publicationDate"] == "2020-03-18"
- assert data["isPublished"] is True
-
-
MUTATION_UPDATE_COLLECTION_WITH_BACKGROUND_IMAGE = """
mutation updateCollection($name: String!, $slug: String!, $id: ID!,
- $backgroundImage: Upload, $backgroundImageAlt: String,
- $isPublished: Boolean!) {
-
+ $backgroundImage: Upload, $backgroundImageAlt: String) {
collectionUpdate(
id: $id, input: {
name: $name,
slug: $slug,
backgroundImage: $backgroundImage,
backgroundImageAlt: $backgroundImageAlt,
- isPublished: $isPublished
}
) {
collection {
@@ -588,7 +566,6 @@ def test_update_collection_with_background_image(
"id": to_global_id("Collection", collection.id),
"backgroundImage": image_name,
"backgroundImageAlt": image_alt,
- "isPublished": True,
}
body = get_multipart_request_body(
MUTATION_UPDATE_COLLECTION_WITH_BACKGROUND_IMAGE,
@@ -620,7 +597,6 @@ def test_update_collection_invalid_background_image(
"id": to_global_id("Collection", collection.id),
"backgroundImage": image_name,
"backgroundImageAlt": image_alt,
- "isPublished": True,
}
body = get_multipart_request_body(
MUTATION_UPDATE_COLLECTION_WITH_BACKGROUND_IMAGE,
@@ -649,7 +625,7 @@ UPDATE_COLLECTION_SLUG_MUTATION = """
name
slug
}
- productErrors {
+ collectionErrors {
field
message
code
@@ -687,7 +663,7 @@ def test_update_collection_slug(
)
content = get_graphql_content(response)
data = content["data"]["collectionUpdate"]
- errors = data["productErrors"]
+ errors = data["collectionErrors"]
if not error_message:
assert not errors
assert data["collection"]["slug"] == expected_slug
@@ -718,7 +694,7 @@ def test_update_collection_slug_exists(
)
content = get_graphql_content(response)
data = content["data"]["collectionUpdate"]
- errors = data["productErrors"]
+ errors = data["collectionErrors"]
assert errors
assert errors[0]["field"] == "slug"
assert errors[0]["code"] == ProductErrorCode.UNIQUE.name
@@ -758,7 +734,7 @@ def test_update_collection_slug_and_name(
name
slug
}
- productErrors {
+ collectionErrors {
field
message
code
@@ -781,7 +757,7 @@ def test_update_collection_slug_and_name(
content = get_graphql_content(response)
collection.refresh_from_db()
data = content["data"]["collectionUpdate"]
- errors = data["productErrors"]
+ errors = data["collectionErrors"]
if not error_message:
assert data["collection"]["name"] == input_name == collection.name
assert data["collection"]["slug"] == input_slug == collection.slug
@@ -840,6 +816,42 @@ def test_add_products_to_collection(
assert data["products"]["totalCount"] == no_products_before + len(product_ids)
+def test_add_products_to_collection_with_product_without_variants(
+ staff_api_client, collection, product_list, permission_manage_products
+):
+ query = """
+ mutation collectionAddProducts(
+ $id: ID!, $products: [ID]!) {
+ collectionAddProducts(collectionId: $id, products: $products) {
+ collection {
+ products {
+ totalCount
+ }
+ }
+ collectionErrors {
+ field
+ message
+ code
+ }
+ }
+ }
+ """
+ product_list[0].variants.all().delete()
+ collection_id = to_global_id("Collection", collection.id)
+ product_ids = [to_global_id("Product", product.pk) for product in product_list]
+ variables = {"id": collection_id, "products": product_ids}
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+ content = get_graphql_content(response)
+ error = content["data"]["collectionAddProducts"]["collectionErrors"][0]
+
+ assert (
+ error["code"] == CollectionErrorCode.CANNOT_MANAGE_PRODUCT_WITHOUT_VARIANT.name
+ )
+ assert error["message"] == "Cannot manage products without variants."
+
+
def test_remove_products_from_collection(
staff_api_client, collection, product_list, permission_manage_products
):
@@ -869,8 +881,8 @@ def test_remove_products_from_collection(
NOT_EXISTS_IDS_COLLECTIONS_QUERY = """
- query ($filter: CollectionFilterInput!) {
- collections(first: 5, filter: $filter) {
+ query ($filter: CollectionFilterInput!, $channel: String) {
+ collections(first: 5, filter: $filter, channel: $channel) {
edges {
node {
id
@@ -882,9 +894,14 @@ NOT_EXISTS_IDS_COLLECTIONS_QUERY = """
"""
-def test_collections_query_ids_not_exists(user_api_client, category):
+def test_collections_query_ids_not_exists(
+ user_api_client, published_collection, channel_USD
+):
query = NOT_EXISTS_IDS_COLLECTIONS_QUERY
- variables = {"filter": {"ids": ["ncXc5tP7kmV6pxE=", "yMyDVE5S2LWWTqK="]}}
+ variables = {
+ "filter": {"ids": ["ncXc5tP7kmV6pxE=", "yMyDVE5S2LWWTqK="]},
+ "channel": channel_USD.slug,
+ }
response = user_api_client.post_graphql(query, variables)
content = get_graphql_content(response, ignore_errors=True)
message_error = '{"ids": [{"message": "Invalid ID specified.", "code": ""}]}'
@@ -895,8 +912,8 @@ def test_collections_query_ids_not_exists(user_api_client, category):
FETCH_COLLECTION_QUERY = """
- query fetchCollection($id: ID!){
- collection(id: $id) {
+ query fetchCollection($id: ID!, $channel: String){
+ collection(id: $id, channel: $channel) {
name
backgroundImage(size: 120) {
url
@@ -907,29 +924,39 @@ FETCH_COLLECTION_QUERY = """
"""
-def test_collection_image_query(user_api_client, collection, media_root):
+def test_collection_image_query(
+ user_api_client, published_collection, media_root, channel_USD
+):
alt_text = "Alt text for an image."
image_file, image_name = create_image()
- collection.background_image = image_file
- collection.background_image_alt = alt_text
- collection.save()
- collection_id = graphene.Node.to_global_id("Collection", collection.pk)
- variables = {"id": collection_id}
+ published_collection.background_image = image_file
+ published_collection.background_image_alt = alt_text
+ published_collection.save()
+ collection_id = graphene.Node.to_global_id("Collection", published_collection.pk)
+ variables = {
+ "id": collection_id,
+ "channel": channel_USD.slug,
+ }
response = user_api_client.post_graphql(FETCH_COLLECTION_QUERY, variables)
content = get_graphql_content(response)
data = content["data"]["collection"]
- thumbnail_url = collection.background_image.thumbnail["120x120"].url
+ thumbnail_url = published_collection.background_image.thumbnail["120x120"].url
assert thumbnail_url in data["backgroundImage"]["url"]
assert data["backgroundImage"]["alt"] == alt_text
-def test_collection_image_query_without_associated_file(user_api_client, collection):
- collection_id = graphene.Node.to_global_id("Collection", collection.pk)
- variables = {"id": collection_id}
+def test_collection_image_query_without_associated_file(
+ user_api_client, published_collection, channel_USD
+):
+ collection_id = graphene.Node.to_global_id("Collection", published_collection.pk)
+ variables = {
+ "id": collection_id,
+ "channel": channel_USD.slug,
+ }
response = user_api_client.post_graphql(FETCH_COLLECTION_QUERY, variables)
content = get_graphql_content(response)
data = content["data"]["collection"]
- assert data["name"] == collection.name
+ assert data["name"] == published_collection.name
assert data["backgroundImage"] is None
@@ -970,17 +997,20 @@ def test_update_collection_mutation_remove_background_image(
assert not collection_with_image.background_image
-def _fetch_collection(client, collection, permissions=None):
+def _fetch_collection(client, collection, channel_slug, permissions=None):
query = """
- query fetchCollection($collectionId: ID!){
- collection(id: $collectionId) {
+ query fetchCollection($id: ID!, $channel: String){
+ collection(id: $id, channel: $channel) {
name,
- isPublished
+ channelListings {
+ isPublished
+ }
}
}
"""
variables = {
- "collectionId": graphene.Node.to_global_id("Collection", collection.id)
+ "id": graphene.Node.to_global_id("Collection", collection.id),
+ "channel": channel_slug,
}
response = client.post_graphql(
query, variables, permissions=permissions, check_no_permissions=False
@@ -990,94 +1020,39 @@ def _fetch_collection(client, collection, permissions=None):
def test_fetch_unpublished_collection_staff_user(
- staff_api_client, unpublished_collection, permission_manage_products
+ staff_api_client, unpublished_collection, permission_manage_products, channel_USD
):
collection_data = _fetch_collection(
staff_api_client,
unpublished_collection,
+ channel_USD.slug,
permissions=[permission_manage_products],
)
assert collection_data["name"] == unpublished_collection.name
- assert collection_data["isPublished"] == unpublished_collection.is_published
-
-
-def test_fetch_unpublished_collection_customer(user_api_client, unpublished_collection):
- collection_data = _fetch_collection(user_api_client, unpublished_collection)
- assert collection_data is None
-
-
-def test_fetch_unpublished_collection_anonymous_user(
- api_client, unpublished_collection
-):
- collection_data = _fetch_collection(api_client, unpublished_collection)
- assert collection_data is None
-
+ assert collection_data["channelListings"][0]["isPublished"] is False
-MUTATION_BULK_PUBLISH_COLLECTIONS = """
- mutation publishManyCollections($ids: [ID]!, $is_published: Boolean!) {
- collectionBulkPublish(ids: $ids, isPublished: $is_published) {
- count
- }
- }
- """
-
-def test_bulk_publish_collection(
- staff_api_client, collection_list_unpublished, permission_manage_products
+def test_fetch_unpublished_collection_customer(
+ user_api_client, unpublished_collection, channel_USD
):
- collection_list = collection_list_unpublished
- assert not any(collection.is_published for collection in collection_list)
-
- variables = {
- "ids": [
- graphene.Node.to_global_id("Collection", collection.id)
- for collection in collection_list
- ],
- "is_published": True,
- }
- response = staff_api_client.post_graphql(
- MUTATION_BULK_PUBLISH_COLLECTIONS,
- variables,
- permissions=[permission_manage_products],
- )
- content = get_graphql_content(response)
- collection_list = Collection.objects.filter(
- id__in=[collection.pk for collection in collection_list]
+ collection_data = _fetch_collection(
+ user_api_client, unpublished_collection, channel_USD.slug
)
-
- assert content["data"]["collectionBulkPublish"]["count"] == len(collection_list)
- assert all(collection.is_published for collection in collection_list)
+ assert collection_data is None
-def test_bulk_unpublish_collection(
- staff_api_client, collection_list, permission_manage_products
+def test_fetch_unpublished_collection_anonymous_user(
+ api_client, unpublished_collection, channel_USD
):
- assert all(collection.is_published for collection in collection_list)
-
- variables = {
- "ids": [
- graphene.Node.to_global_id("Collection", collection.id)
- for collection in collection_list
- ],
- "is_published": False,
- }
- response = staff_api_client.post_graphql(
- MUTATION_BULK_PUBLISH_COLLECTIONS,
- variables,
- permissions=[permission_manage_products],
- )
- content = get_graphql_content(response)
- collection_list = Collection.objects.filter(
- id__in=[collection.pk for collection in collection_list]
+ collection_data = _fetch_collection(
+ api_client, unpublished_collection, channel_USD.slug
)
-
- assert content["data"]["collectionBulkPublish"]["count"] == len(collection_list)
- assert not any(collection.is_published for collection in collection_list)
+ assert collection_data is None
GET_SORTED_PRODUCTS_COLLECTION_QUERY = """
-query CollectionProducts($id: ID!, $sortBy: ProductOrder) {
- collection(id: $id) {
+query CollectionProducts($id: ID!, $channel: String, $sortBy: ProductOrder) {
+ collection(id: $id, channel: $channel) {
products(first: 10, sortBy: $sortBy) {
edges {
node {
@@ -1090,14 +1065,17 @@ query CollectionProducts($id: ID!, $sortBy: ProductOrder) {
"""
-def test_sort_collection_products_by_name(staff_api_client, collection, product_list):
+def test_sort_collection_products_by_name(
+ staff_api_client, published_collection, product_list, channel_USD
+):
# given
for product in product_list:
- collection.products.add(product)
+ published_collection.products.add(product)
variables = {
- "id": graphene.Node.to_global_id("Collection", collection.pk),
+ "id": graphene.Node.to_global_id("Collection", published_collection.pk),
"sortBy": {"direction": "DESC", "field": "NAME"},
+ "channel": channel_USD.slug,
}
# when
@@ -1127,33 +1105,3 @@ query Collections($sortBy: CollectionSortingInput) {
}
}
"""
-
-
-@freeze_time("2020-03-18 12:00:00")
- "direction, order_direction",
- (("ASC", "publication_date"), ("DESC", "-publication_date")),
-)
-def test_sort_collections_by_publication_date(
- direction, order_direction, staff_api_client, collection_list
-):
-
- for iter_value, product in enumerate(collection_list):
- product.publication_date = date.today() - timedelta(days=iter_value)
- Collection.objects.bulk_update(collection_list, ["publication_date"])
-
- variables = {
- "sortBy": {"direction": direction, "field": "PUBLICATION_DATE"},
- }
-
- # when
- response = staff_api_client.post_graphql(GET_SORTED_COLLECTION_QUERY, variables)
-
- # then
- content = get_graphql_content(response)
- data = content["data"]["collections"]["edges"]
-
- assert [node["node"]["id"] for node in data] == [
- graphene.Node.to_global_id("Collection", collection.pk)
- for collection in Collection.objects.order_by(order_direction)
- ]
diff --git a/saleor/graphql/product/tests/test_collection_channel_listing_update.py b/saleor/graphql/product/tests/test_collection_channel_listing_update.py
new file mode 100644
index 0000000000..dd61c33185
--- /dev/null
+++ b/saleor/graphql/product/tests/test_collection_channel_listing_update.py
@@ -0,0 +1,560 @@
+import datetime
+
+import graphene
+from freezegun import freeze_time
+
+from ....product.error_codes import CollectionErrorCode
+from ...tests.utils import assert_no_permission, get_graphql_content
+
+COLLECTION_CHANNEL_LISTING_UPDATE_MUTATION = """
+mutation UpdateCollectionChannelListing(
+ $id: ID!
+ $input: CollectionChannelListingUpdateInput!
+) {
+ collectionChannelListingUpdate(id: $id, input: $input) {
+ collectionChannelListingErrors {
+ field
+ message
+ code
+ channels
+ }
+ collection {
+ slug
+ channelListings {
+ isPublished
+ publicationDate
+ channel {
+ slug
+ }
+ }
+ }
+ }
+}
+"""
+
+
+def test_collection_channel_listing_update_duplicated_ids_in_add_and_remove(
+ staff_api_client, collection, permission_manage_products, channel_USD
+):
+ # given
+ collection_id = graphene.Node.to_global_id("Collection", collection.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": collection_id,
+ "input": {
+ "addChannels": [{"channelId": channel_id, "isPublished": True}],
+ "removeChannels": [channel_id],
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ COLLECTION_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ errors = content["data"]["collectionChannelListingUpdate"][
+ "collectionChannelListingErrors"
+ ]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "input"
+ assert errors[0]["code"] == CollectionErrorCode.DUPLICATED_INPUT_ITEM.name
+ assert errors[0]["channels"] == [channel_id]
+
+
+def test_collection_channel_listing_update_duplicated_channel_in_add(
+ staff_api_client, collection, permission_manage_products, channel_USD
+):
+ # given
+ collection_id = graphene.Node.to_global_id("Collection", collection.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": collection_id,
+ "input": {
+ "addChannels": [
+ {"channelId": channel_id, "isPublished": True},
+ {"channelId": channel_id, "isPublished": False},
+ ],
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ COLLECTION_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ errors = content["data"]["collectionChannelListingUpdate"][
+ "collectionChannelListingErrors"
+ ]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "addChannels"
+ assert errors[0]["code"] == CollectionErrorCode.DUPLICATED_INPUT_ITEM.name
+ assert errors[0]["channels"] == [channel_id]
+
+
+def test_collection_channel_listing_update_duplicated_channel_in_remove(
+ staff_api_client, collection, permission_manage_products, channel_USD
+):
+ # given
+ collection_id = graphene.Node.to_global_id("Collection", collection.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": collection_id,
+ "input": {"removeChannels": [channel_id, channel_id]},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ COLLECTION_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ errors = content["data"]["collectionChannelListingUpdate"][
+ "collectionChannelListingErrors"
+ ]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "removeChannels"
+ assert errors[0]["code"] == CollectionErrorCode.DUPLICATED_INPUT_ITEM.name
+ assert errors[0]["channels"] == [channel_id]
+
+
+def test_collection_channel_listing_update_with_empty_input(
+ staff_api_client, collection, permission_manage_products
+):
+ # given
+ collection_id = graphene.Node.to_global_id("Collection", collection.pk)
+ variables = {
+ "id": collection_id,
+ "input": {},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ COLLECTION_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ errors = content["data"]["collectionChannelListingUpdate"][
+ "collectionChannelListingErrors"
+ ]
+ assert not errors
+
+
+def test_collection_channel_listing_update_with_empty_lists_in_input(
+ staff_api_client, collection, permission_manage_products
+):
+ # given
+ collection_id = graphene.Node.to_global_id("Collection", collection.pk)
+ variables = {
+ "id": collection_id,
+ "input": {"addChannels": [], "removeChannels": []},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ COLLECTION_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ errors = content["data"]["collectionChannelListingUpdate"][
+ "collectionChannelListingErrors"
+ ]
+ assert not errors
+
+
+def test_collection_channel_listing_update_as_staff_user(
+ staff_api_client,
+ published_collection,
+ permission_manage_products,
+ channel_USD,
+ channel_PLN,
+):
+ # given
+ publication_date = datetime.date.today()
+ collection_id = graphene.Node.to_global_id("Collection", published_collection.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ variables = {
+ "id": collection_id,
+ "input": {
+ "addChannels": [
+ {
+ "channelId": channel_id,
+ "isPublished": False,
+ "publicationDate": publication_date,
+ }
+ ]
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ COLLECTION_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["collectionChannelListingUpdate"]
+ collection_data = data["collection"]
+ collection_channel_listing = published_collection.channel_listings.get(
+ channel=channel_USD
+ )
+ publication_date_usd = collection_channel_listing.publication_date.isoformat()
+ assert not data["collectionChannelListingErrors"]
+ assert collection_data["slug"] == published_collection.slug
+ assert collection_data["channelListings"][0]["isPublished"] is True
+ assert (
+ collection_data["channelListings"][0]["publicationDate"] == publication_date_usd
+ )
+ assert collection_data["channelListings"][0]["channel"]["slug"] == channel_USD.slug
+
+ assert collection_data["channelListings"][1]["isPublished"] is False
+ assert (
+ collection_data["channelListings"][1]["publicationDate"]
+ == publication_date.isoformat()
+ )
+ assert collection_data["channelListings"][1]["channel"]["slug"] == channel_PLN.slug
+
+
+def test_collection_channel_listing_update_as_app(
+ app_api_client,
+ published_collection,
+ permission_manage_products,
+ channel_USD,
+ channel_PLN,
+):
+ # given
+ publication_date = datetime.date.today()
+ collection_id = graphene.Node.to_global_id("Collection", published_collection.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ variables = {
+ "id": collection_id,
+ "input": {
+ "addChannels": [
+ {
+ "channelId": channel_id,
+ "isPublished": False,
+ "publicationDate": publication_date,
+ }
+ ]
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ COLLECTION_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ collection_channel_listing = published_collection.channel_listings.get(
+ channel=channel_USD
+ )
+ publication_date_usd = collection_channel_listing.publication_date.isoformat()
+ data = content["data"]["collectionChannelListingUpdate"]
+ collection_data = data["collection"]
+ assert not data["collectionChannelListingErrors"]
+ assert collection_data["slug"] == published_collection.slug
+ assert collection_data["channelListings"][0]["isPublished"] is True
+ assert (
+ collection_data["channelListings"][0]["publicationDate"] == publication_date_usd
+ )
+ assert collection_data["channelListings"][0]["channel"]["slug"] == channel_USD.slug
+ assert collection_data["channelListings"][1]["isPublished"] is False
+ assert (
+ collection_data["channelListings"][1]["publicationDate"]
+ == publication_date.isoformat()
+ )
+ assert collection_data["channelListings"][1]["channel"]["slug"] == channel_PLN.slug
+
+
+def test_collection_channel_listing_update_as_customer(
+ user_api_client, collection, channel_PLN
+):
+ # given
+ collection_id = graphene.Node.to_global_id("Collection", collection.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ variables = {
+ "id": collection_id,
+ "input": {"addChannels": [{"channelId": channel_id, "isPublished": False}]},
+ }
+
+ # when
+ response = user_api_client.post_graphql(
+ COLLECTION_CHANNEL_LISTING_UPDATE_MUTATION, variables=variables
+ )
+
+ # then
+ assert_no_permission(response)
+
+
+def test_collection_channel_listing_update_as_anonymous(
+ api_client, collection, channel_PLN
+):
+ # given
+ collection_id = graphene.Node.to_global_id("Collection", collection.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ variables = {
+ "id": collection_id,
+ "input": {"addChannels": [{"channelId": channel_id, "isPublished": False}]},
+ }
+
+ # when
+ response = api_client.post_graphql(
+ COLLECTION_CHANNEL_LISTING_UPDATE_MUTATION, variables=variables
+ )
+
+ # then
+ assert_no_permission(response)
+
+
+def test_collection_channel_listing_update_add_channel(
+ staff_api_client,
+ published_collection,
+ permission_manage_products,
+ channel_USD,
+ channel_PLN,
+):
+ # given
+ publication_date = datetime.date.today()
+ collection_id = graphene.Node.to_global_id("Collection", published_collection.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ variables = {
+ "id": collection_id,
+ "input": {
+ "addChannels": [
+ {
+ "channelId": channel_id,
+ "isPublished": False,
+ "publicationDate": publication_date,
+ }
+ ]
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ COLLECTION_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ collection_channel_listing = published_collection.channel_listings.get(
+ channel=channel_USD
+ )
+ publication_date_usd = collection_channel_listing.publication_date.isoformat()
+ data = content["data"]["collectionChannelListingUpdate"]
+ collection_data = data["collection"]
+ assert not data["collectionChannelListingErrors"]
+ assert collection_data["slug"] == published_collection.slug
+ assert collection_data["channelListings"][0]["isPublished"] is True
+ assert (
+ collection_data["channelListings"][0]["publicationDate"] == publication_date_usd
+ )
+ assert collection_data["channelListings"][0]["channel"]["slug"] == channel_USD.slug
+ assert collection_data["channelListings"][1]["isPublished"] is False
+ assert (
+ collection_data["channelListings"][1]["publicationDate"]
+ == publication_date.isoformat()
+ )
+ assert collection_data["channelListings"][1]["channel"]["slug"] == channel_PLN.slug
+
+
+def test_collection_channel_listing_update_unpublished(
+ staff_api_client, published_collection, permission_manage_products, channel_USD
+):
+ # given
+ collection_id = graphene.Node.to_global_id("Collection", published_collection.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": collection_id,
+ "input": {"addChannels": [{"channelId": channel_id, "isPublished": False}]},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ COLLECTION_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+ collection_channel_listing = published_collection.channel_listings.get()
+ publication_date_usd = collection_channel_listing.publication_date.isoformat()
+
+ # then
+ data = content["data"]["collectionChannelListingUpdate"]
+ collection_data = data["collection"]
+ assert not data["collectionChannelListingErrors"]
+ assert collection_data["slug"] == published_collection.slug
+ assert collection_data["channelListings"][0]["isPublished"] is False
+ assert (
+ collection_data["channelListings"][0]["publicationDate"] == publication_date_usd
+ )
+ assert collection_data["channelListings"][0]["channel"]["slug"] == channel_USD.slug
+
+
+def test_collection_channel_listing_update_update_publication_date(
+ staff_api_client, collection, permission_manage_products, channel_USD
+):
+ # given
+ publication_date = datetime.date.today()
+ collection_id = graphene.Node.to_global_id("Collection", collection.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": collection_id,
+ "input": {
+ "addChannels": [
+ {"channelId": channel_id, "publicationDate": publication_date}
+ ]
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ COLLECTION_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["collectionChannelListingUpdate"]
+ collection_data = data["collection"]
+ assert not data["collectionChannelListingErrors"]
+ assert collection_data["slug"] == collection.slug
+ assert (
+ collection_data["channelListings"][0]["publicationDate"]
+ == publication_date.isoformat()
+ )
+ assert collection_data["channelListings"][0]["channel"]["slug"] == channel_USD.slug
+
+
+def test_collection_channel_listing_update_remove_not_assigned_channel(
+ staff_api_client,
+ published_collection,
+ permission_manage_products,
+ channel_USD,
+ channel_PLN,
+):
+ # given
+ collection_id = graphene.Node.to_global_id("Collection", published_collection.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ variables = {
+ "id": collection_id,
+ "input": {"removeChannels": [channel_id]},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ COLLECTION_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ collection_channel_listing = published_collection.channel_listings.get(
+ channel=channel_USD
+ )
+ publication_date = collection_channel_listing.publication_date.isoformat()
+ data = content["data"]["collectionChannelListingUpdate"]
+ collection_data = data["collection"]
+ assert not data["collectionChannelListingErrors"]
+ assert collection_data["slug"] == published_collection.slug
+ assert collection_data["channelListings"][0]["isPublished"] is True
+ assert collection_data["channelListings"][0]["publicationDate"] == publication_date
+ assert collection_data["channelListings"][0]["channel"]["slug"] == channel_USD.slug
+
+
+@freeze_time("2020-03-18 12:00:00")
+def test_collection_channel_listing_update_add_channel_without_publication_date(
+ staff_api_client,
+ published_collection,
+ permission_manage_products,
+ channel_USD,
+ channel_PLN,
+):
+ # given
+ collection_id = graphene.Node.to_global_id("Collection", published_collection.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ variables = {
+ "id": collection_id,
+ "input": {"addChannels": [{"channelId": channel_id, "isPublished": True}]},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ COLLECTION_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["collectionChannelListingUpdate"]
+ collection_data = data["collection"]
+ assert not data["collectionChannelListingErrors"]
+ assert collection_data["slug"] == published_collection.slug
+ assert collection_data["channelListings"][0]["isPublished"] is True
+ assert collection_data["channelListings"][0]["channel"]["slug"] == channel_USD.slug
+ assert collection_data["channelListings"][1]["isPublished"] is True
+ assert (
+ collection_data["channelListings"][1]["publicationDate"]
+ == datetime.date(2020, 3, 18).isoformat()
+ )
+ assert collection_data["channelListings"][1]["channel"]["slug"] == channel_PLN.slug
+
+
+@freeze_time("2020-03-18 12:00:00")
+def test_collection_channel_listing_update_publish_without_publication_date(
+ staff_api_client, published_collection, permission_manage_products, channel_USD
+):
+ # given
+ published_collection.channel_listings.update(is_published=False)
+ collection_id = graphene.Node.to_global_id("Collection", published_collection.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": collection_id,
+ "input": {"addChannels": [{"channelId": channel_id, "isPublished": True}]},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ COLLECTION_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["collectionChannelListingUpdate"]
+ collection_data = data["collection"]
+ assert not data["collectionChannelListingErrors"]
+ assert collection_data["slug"] == published_collection.slug
+ assert collection_data["channelListings"][0]["isPublished"] is True
+ assert (
+ collection_data["channelListings"][0]["publicationDate"]
+ == datetime.date(2020, 3, 18).isoformat()
+ )
+ assert collection_data["channelListings"][0]["channel"]["slug"] == channel_USD.slug
diff --git a/saleor/graphql/product/tests/test_collection_filtering_and_sorting_with_channels.py b/saleor/graphql/product/tests/test_collection_filtering_and_sorting_with_channels.py
new file mode 100644
index 0000000000..a7255f0068
--- /dev/null
+++ b/saleor/graphql/product/tests/test_collection_filtering_and_sorting_with_channels.py
@@ -0,0 +1,398 @@
+import datetime
+
+import pytest
+
+from ....product.models import Collection, CollectionChannelListing
+from ...channel.filters import LACK_OF_CHANNEL_IN_FILTERING_MSG
+from ...channel.sorters import LACK_OF_CHANNEL_IN_SORTING_MSG
+from ...tests.utils import assert_graphql_error_with_message, get_graphql_content
+
+
+def collections_for_sorting_with_channels(channel_USD, channel_PLN):
+ collections = Collection.objects.bulk_create(
+ [
+ Collection(name="Collection1", slug="collection1"),
+ Collection(name="Collection2", slug="collection2"),
+ Collection(name="Collection3", slug="collection3"),
+ Collection(name="Collection4", slug="collection4"),
+ Collection(name="Collection5", slug="collection5"),
+ ]
+ )
+ CollectionChannelListing.objects.bulk_create(
+ [
+ CollectionChannelListing(
+ collection=collections[0],
+ publication_date=None,
+ is_published=True,
+ channel=channel_USD,
+ ),
+ CollectionChannelListing(
+ collection=collections[1],
+ publication_date=None,
+ is_published=False,
+ channel=channel_USD,
+ ),
+ CollectionChannelListing(
+ collection=collections[2],
+ publication_date=datetime.date(2004, 1, 1),
+ is_published=False,
+ channel=channel_USD,
+ ),
+ CollectionChannelListing(
+ collection=collections[3],
+ publication_date=datetime.date(2003, 1, 1),
+ is_published=False,
+ channel=channel_USD,
+ ),
+ # second channel
+ CollectionChannelListing(
+ collection=collections[0],
+ publication_date=None,
+ is_published=False,
+ channel=channel_PLN,
+ ),
+ CollectionChannelListing(
+ collection=collections[1],
+ publication_date=None,
+ is_published=True,
+ channel=channel_PLN,
+ ),
+ CollectionChannelListing(
+ collection=collections[2],
+ publication_date=datetime.date(2002, 1, 1),
+ is_published=False,
+ channel=channel_PLN,
+ ),
+ CollectionChannelListing(
+ collection=collections[4],
+ publication_date=datetime.date(2001, 1, 1),
+ is_published=False,
+ channel=channel_PLN,
+ ),
+ ]
+ )
+
+
+QUERY_COLLECTIONS_WITH_SORTING_AND_FILTERING = """
+ query ($sortBy: CollectionSortingInput, $filter: CollectionFilterInput){
+ collections (
+ first: 10, sortBy: $sortBy, filter: $filter
+ ) {
+ edges {
+ node {
+ name
+ slug
+ }
+ }
+ }
+ }
+"""
+
+
+ "sort_by",
+ [
+ {"field": "AVAILABILITY", "direction": "ASC"},
+ {"field": "PUBLICATION_DATE", "direction": "DESC"},
+ ],
+)
+def test_collections_with_sorting_and_without_channel(
+ sort_by, staff_api_client, permission_manage_products,
+):
+ # given
+ variables = {"sortBy": sort_by}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_COLLECTIONS_WITH_SORTING_AND_FILTERING,
+ variables,
+ permissions=[permission_manage_products],
+ check_no_permissions=False,
+ )
+
+ # then
+ assert_graphql_error_with_message(response, LACK_OF_CHANNEL_IN_SORTING_MSG)
+
+
+ "sort_by, collections_order",
+ [
+ (
+ {"field": "AVAILABILITY", "direction": "ASC"},
+ ["Collection2", "Collection3", "Collection4", "Collection1", "Collection5"],
+ ),
+ (
+ {"field": "AVAILABILITY", "direction": "DESC"},
+ ["Collection5", "Collection1", "Collection4", "Collection3", "Collection2"],
+ ),
+ (
+ {"field": "PUBLICATION_DATE", "direction": "ASC"},
+ ["Collection4", "Collection3", "Collection1", "Collection2", "Collection5"],
+ ),
+ (
+ {"field": "PUBLICATION_DATE", "direction": "DESC"},
+ ["Collection5", "Collection2", "Collection1", "Collection3", "Collection4"],
+ ),
+ ],
+)
+def test_collections_with_sorting_and_channel_USD(
+ sort_by,
+ collections_order,
+ staff_api_client,
+ permission_manage_products,
+ collections_for_sorting_with_channels,
+ channel_USD,
+):
+ # given
+ sort_by["channel"] = channel_USD.slug
+ variables = {"sortBy": sort_by}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_COLLECTIONS_WITH_SORTING_AND_FILTERING,
+ variables,
+ permissions=[permission_manage_products],
+ check_no_permissions=False,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ collections_nodes = content["data"]["collections"]["edges"]
+ for index, collection_name in enumerate(collections_order):
+ assert collection_name == collections_nodes[index]["node"]["name"]
+
+
+ "sort_by, collections_order",
+ [
+ (
+ {"field": "AVAILABILITY", "direction": "ASC"},
+ ["Collection1", "Collection3", "Collection5", "Collection2", "Collection4"],
+ ),
+ (
+ {"field": "AVAILABILITY", "direction": "DESC"},
+ ["Collection4", "Collection2", "Collection5", "Collection3", "Collection1"],
+ ),
+ (
+ {"field": "PUBLICATION_DATE", "direction": "ASC"},
+ ["Collection5", "Collection3", "Collection1", "Collection2", "Collection4"],
+ ),
+ (
+ {"field": "PUBLICATION_DATE", "direction": "DESC"},
+ ["Collection4", "Collection2", "Collection1", "Collection3", "Collection5"],
+ ),
+ ],
+)
+def test_collections_with_sorting_and_channel_PLN(
+ sort_by,
+ collections_order,
+ staff_api_client,
+ permission_manage_products,
+ collections_for_sorting_with_channels,
+ channel_PLN,
+):
+ # given
+ sort_by["channel"] = channel_PLN.slug
+ variables = {"sortBy": sort_by}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_COLLECTIONS_WITH_SORTING_AND_FILTERING,
+ variables,
+ permissions=[permission_manage_products],
+ check_no_permissions=False,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ collections_nodes = content["data"]["collections"]["edges"]
+
+ for index, collection_name in enumerate(collections_order):
+ assert collection_name == collections_nodes[index]["node"]["name"]
+
+
+ "sort_by",
+ [
+ {"field": "AVAILABILITY", "direction": "ASC"},
+ {"field": "PUBLICATION_DATE", "direction": "ASC"},
+ ],
+)
+def test_collections_with_sorting_and_not_existing_channel_asc(
+ sort_by,
+ staff_api_client,
+ permission_manage_products,
+ collections_for_sorting_with_channels,
+ channel_USD,
+):
+ # given
+ collections_order = [
+ "Collection1",
+ "Collection2",
+ "Collection3",
+ "Collection4",
+ "Collection5",
+ ]
+ sort_by["channel"] = "Not-existing"
+ variables = {"sortBy": sort_by}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_COLLECTIONS_WITH_SORTING_AND_FILTERING,
+ variables,
+ permissions=[permission_manage_products],
+ check_no_permissions=False,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ collections_nodes = content["data"]["collections"]["edges"]
+ for index, collection_name in enumerate(collections_order):
+ assert collection_name == collections_nodes[index]["node"]["name"]
+
+
+ "sort_by",
+ [
+ {"field": "AVAILABILITY", "direction": "DESC"},
+ {"field": "PUBLICATION_DATE", "direction": "DESC"},
+ ],
+)
+def test_collections_with_sorting_and_not_existing_channel_desc(
+ sort_by,
+ staff_api_client,
+ permission_manage_products,
+ collections_for_sorting_with_channels,
+ channel_USD,
+):
+ collections_order = [
+ "Collection5",
+ "Collection4",
+ "Collection3",
+ "Collection2",
+ "Collection1",
+ ]
+ # given
+ sort_by["channel"] = "Not-existing"
+ variables = {"sortBy": sort_by}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_COLLECTIONS_WITH_SORTING_AND_FILTERING,
+ variables,
+ permissions=[permission_manage_products],
+ check_no_permissions=False,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ collections_nodes = content["data"]["collections"]["edges"]
+ for index, collection_name in enumerate(collections_order):
+ assert collection_name == collections_nodes[index]["node"]["name"]
+
+
+def test_collections_with_filtering_without_channel(
+ staff_api_client, permission_manage_products
+):
+ # given
+ variables = {"filter": {"published": "PUBLISHED"}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_COLLECTIONS_WITH_SORTING_AND_FILTERING,
+ variables,
+ permissions=[permission_manage_products],
+ check_no_permissions=False,
+ )
+
+ # then
+ assert_graphql_error_with_message(response, LACK_OF_CHANNEL_IN_FILTERING_MSG)
+
+
+ "filter_by, collections_count",
+ [({"published": "PUBLISHED"}, 1), ({"published": "HIDDEN"}, 3)],
+)
+def test_collections_with_filtering_with_channel_USD(
+ filter_by,
+ collections_count,
+ staff_api_client,
+ permission_manage_products,
+ collections_for_sorting_with_channels,
+ channel_USD,
+):
+ # given
+ filter_by["channel"] = channel_USD.slug
+ variables = {"filter": filter_by}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_COLLECTIONS_WITH_SORTING_AND_FILTERING,
+ variables,
+ permissions=[permission_manage_products],
+ check_no_permissions=False,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ collections_nodes = content["data"]["collections"]["edges"]
+ assert len(collections_nodes) == collections_count
+
+
+ "filter_by, collections_count",
+ [({"published": "PUBLISHED"}, 1), ({"published": "HIDDEN"}, 3)],
+)
+def test_collections_with_filtering_with_channel_PLN(
+ filter_by,
+ collections_count,
+ staff_api_client,
+ permission_manage_products,
+ collections_for_sorting_with_channels,
+ channel_PLN,
+):
+ # given
+ filter_by["channel"] = channel_PLN.slug
+ variables = {"filter": filter_by}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_COLLECTIONS_WITH_SORTING_AND_FILTERING,
+ variables,
+ permissions=[permission_manage_products],
+ check_no_permissions=False,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ collections_nodes = content["data"]["collections"]["edges"]
+ assert len(collections_nodes) == collections_count
+
+
+ "filter_by", [{"published": "PUBLISHED"}, {"published": "HIDDEN"}],
+)
+def test_collections_with_filtering_and_not_existing_channel(
+ filter_by,
+ staff_api_client,
+ permission_manage_products,
+ collections_for_sorting_with_channels,
+ channel_USD,
+):
+ # given
+ filter_by["channel"] = "Not-existing"
+ variables = {"filter": filter_by}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_COLLECTIONS_WITH_SORTING_AND_FILTERING,
+ variables,
+ permissions=[permission_manage_products],
+ check_no_permissions=False,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ collections_nodes = content["data"]["collections"]["edges"]
+ assert len(collections_nodes) == 0
diff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.py
index 157bb6461f..771e0c7035 100644
--- a/saleor/graphql/product/tests/test_product.py
+++ b/saleor/graphql/product/tests/test_product.py
@@ -25,18 +25,21 @@ from ....product.models import (
AttributeValue,
Category,
Collection,
+ CollectionChannelListing,
Product,
+ ProductChannelListing,
ProductImage,
ProductType,
ProductVariant,
+ ProductVariantChannelListing,
)
from ....product.tasks import update_variants_names
from ....product.tests.utils import create_image, create_pdf_file_with_image_ext
from ....product.utils.attributes import associate_attribute_values_to_instance
+from ....product.utils.costs import get_product_costs_data
from ....warehouse.models import Allocation, Stock, Warehouse
from ...core.enums import ReportingPeriod
from ...tests.utils import (
- assert_negative_positive_decimal_value,
assert_no_permission,
get_graphql_content,
get_graphql_content_from_response,
@@ -49,8 +52,8 @@ from ..utils import create_stocks
@pytest.fixture
def query_products_with_filter():
query = """
- query ($filter: ProductFilterInput!, ) {
- products(first:5, filter: $filter) {
+ query ($filter: ProductFilterInput!, $channel: String) {
+ products(first:5, filter: $filter, channel: $channel) {
edges{
node{
id
@@ -88,8 +91,8 @@ def query_products_with_attributes():
@pytest.fixture
def query_collections_with_filter():
query = """
- query ($filter: CollectionFilterInput!, ) {
- collections(first:5, filter: $filter) {
+ query ($filter: CollectionFilterInput!, $channel: String) {
+ collections(first:5, filter: $filter, channel: $channel) {
edges{
node{
id
@@ -121,14 +124,13 @@ def query_categories_with_filter():
QUERY_FETCH_ALL_PRODUCTS = """
- query {
- products(first: 10) {
+ query ($channel:String){
+ products(first: 10, channel: $channel) {
totalCount
edges {
node {
id
name
- isPublished
}
}
}
@@ -137,10 +139,11 @@ QUERY_FETCH_ALL_PRODUCTS = """
QUERY_PRODUCT = """
- query ($id: ID, $slug: String){
+ query ($id: ID, $slug: String, $channel:String){
product(
id: $id,
slug: $slug,
+ channel: $channel
) {
id
name
@@ -150,20 +153,184 @@ QUERY_PRODUCT = """
}
availableForPurchase
isAvailableForPurchase
- visibleInListings
}
}
"""
-def test_product_query_by_id(
- user_api_client, product,
+def test_product_query_by_id_available_as_staff_user(
+ staff_api_client, permission_manage_products, product, channel_USD
):
- # given
- product.visible_in_listings = True
- product.save(update_fields=["visible_in_listings"])
+ variables = {
+ "id": graphene.Node.to_global_id("Product", product.pk),
+ "channel": channel_USD.slug,
+ }
- variables = {"id": graphene.Node.to_global_id("Product", product.pk)}
+ response = staff_api_client.post_graphql(
+ QUERY_PRODUCT,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ check_no_permissions=False,
+ )
+ content = get_graphql_content(response)
+ product_data = content["data"]["product"]
+ assert product_data is not None
+ assert product_data["name"] == product.name
+
+
+def test_product_query_by_id_not_available_as_staff_user(
+ staff_api_client, permission_manage_products, product, channel_USD
+):
+ variables = {
+ "id": graphene.Node.to_global_id("Product", product.pk),
+ "channel": channel_USD.slug,
+ }
+ ProductChannelListing.objects.filter(product=product, channel=channel_USD).update(
+ is_published=False
+ )
+
+ response = staff_api_client.post_graphql(
+ QUERY_PRODUCT,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ check_no_permissions=False,
+ )
+ content = get_graphql_content(response)
+ product_data = content["data"]["product"]
+ assert product_data is not None
+ assert product_data["name"] == product.name
+
+
+def test_product_query_by_id_not_existing_in_channel_as_staff_user(
+ staff_api_client, permission_manage_products, product, channel_USD
+):
+ variables = {
+ "id": graphene.Node.to_global_id("Product", product.pk),
+ "channel": channel_USD.slug,
+ }
+ ProductChannelListing.objects.filter(product=product, channel=channel_USD).delete()
+
+ response = staff_api_client.post_graphql(
+ QUERY_PRODUCT,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ check_no_permissions=False,
+ )
+ content = get_graphql_content(response)
+ product_data = content["data"]["product"]
+ assert product_data is None
+
+
+def test_product_query_by_id_as_staff_user_without_channel_slug(
+ staff_api_client, permission_manage_products, product, channel_USD
+):
+ variables = {
+ "id": graphene.Node.to_global_id("Product", product.pk),
+ }
+ ProductChannelListing.objects.filter(product=product, channel=channel_USD).delete()
+
+ response = staff_api_client.post_graphql(
+ QUERY_PRODUCT,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ check_no_permissions=False,
+ )
+ content = get_graphql_content(response)
+ product_data = content["data"]["product"]
+ assert product_data is not None
+ assert product_data["name"] == product.name
+
+
+def test_product_query_by_id_available_as_app(
+ app_api_client, permission_manage_products, product, channel_USD
+):
+ variables = {
+ "id": graphene.Node.to_global_id("Product", product.pk),
+ "channel": channel_USD.slug,
+ }
+
+ response = app_api_client.post_graphql(
+ QUERY_PRODUCT,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ check_no_permissions=False,
+ )
+ content = get_graphql_content(response)
+ product_data = content["data"]["product"]
+ assert product_data is not None
+ assert product_data["name"] == product.name
+
+
+def test_product_query_by_id_not_available_as_app(
+ app_api_client, permission_manage_products, product, channel_USD
+):
+ variables = {
+ "id": graphene.Node.to_global_id("Product", product.pk),
+ "channel": channel_USD.slug,
+ }
+ ProductChannelListing.objects.filter(product=product, channel=channel_USD).update(
+ is_published=False
+ )
+
+ response = app_api_client.post_graphql(
+ QUERY_PRODUCT,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ check_no_permissions=False,
+ )
+ content = get_graphql_content(response)
+ product_data = content["data"]["product"]
+ assert product_data is not None
+ assert product_data["name"] == product.name
+
+
+def test_product_query_by_id_not_existing_in_channel_as_app(
+ app_api_client, permission_manage_products, product, channel_USD
+):
+ variables = {
+ "id": graphene.Node.to_global_id("Product", product.pk),
+ "channel": channel_USD.slug,
+ }
+ ProductChannelListing.objects.filter(product=product, channel=channel_USD).delete()
+
+ response = app_api_client.post_graphql(
+ QUERY_PRODUCT,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ check_no_permissions=False,
+ )
+ content = get_graphql_content(response)
+ product_data = content["data"]["product"]
+ assert product_data is None
+
+
+def test_product_query_by_id_as_app_without_channel_slug(
+ app_api_client, permission_manage_products, product, channel_USD
+):
+ variables = {
+ "id": graphene.Node.to_global_id("Product", product.pk),
+ }
+ ProductChannelListing.objects.filter(product=product, channel=channel_USD).delete()
+
+ response = app_api_client.post_graphql(
+ QUERY_PRODUCT,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ check_no_permissions=False,
+ )
+ content = get_graphql_content(response)
+ product_data = content["data"]["product"]
+ assert product_data is not None
+ assert product_data["name"] == product.name
+
+
+def test_product_query_by_id_available_as_customer(
+ user_api_client, product, channel_USD
+):
+ variables = {
+ "id": graphene.Node.to_global_id("Product", product.pk),
+ "channel": channel_USD.slug,
+ }
# when
response = user_api_client.post_graphql(QUERY_PRODUCT, variables=variables)
@@ -173,14 +340,33 @@ def test_product_query_by_id(
product_data = content["data"]["product"]
assert product_data is not None
assert product_data["name"] == product.name
- assert product_data["visibleInListings"] is True
+
+
+def test_product_query_by_id_not_available_as_customer(
+ user_api_client, product, channel_USD
+):
+ variables = {
+ "id": graphene.Node.to_global_id("Product", product.pk),
+ "channel": channel_USD.slug,
+ }
+ ProductChannelListing.objects.filter(product=product, channel=channel_USD).update(
+ is_published=False
+ )
+
+ response = user_api_client.post_graphql(QUERY_PRODUCT, variables=variables)
+ content = get_graphql_content(response)
+ product_data = content["data"]["product"]
+ assert product_data is None
def test_product_unpublished_query_by_id_as_app(
- app_api_client, unavailable_product, permission_manage_products
+ app_api_client, unavailable_product, permission_manage_products, channel_USD
):
# given
- variables = {"id": graphene.Node.to_global_id("Product", unavailable_product.pk)}
+ variables = {
+ "id": graphene.Node.to_global_id("Product", unavailable_product.pk),
+ "channel": channel_USD.slug,
+ }
# when
response = app_api_client.post_graphql(
@@ -198,7 +384,7 @@ def test_product_unpublished_query_by_id_as_app(
def test_product_query_by_id_weight_returned_in_default_unit(
- user_api_client, product, site_settings
+ user_api_client, product, site_settings, channel_USD
):
# given
product.weight = Weight(kg=10)
@@ -207,7 +393,10 @@ def test_product_query_by_id_weight_returned_in_default_unit(
site_settings.default_weight_unit = WeightUnits.POUND
site_settings.save(update_fields=["default_weight_unit"])
- variables = {"id": graphene.Node.to_global_id("Product", product.pk)}
+ variables = {
+ "id": graphene.Node.to_global_id("Product", product.pk),
+ "channel": channel_USD.slug,
+ }
# when
response = user_api_client.post_graphql(QUERY_PRODUCT, variables=variables)
@@ -221,7 +410,9 @@ def test_product_query_by_id_weight_returned_in_default_unit(
assert product_data["weight"]["unit"] == WeightUnits.POUND.upper()
-def test_product_query_by_id_weight_is_rounded(user_api_client, product, site_settings):
+def test_product_query_by_id_weight_is_rounded(
+ user_api_client, product, site_settings, channel_USD
+):
# given
product.weight = Weight(kg=1.83456)
product.save(update_fields=["weight"])
@@ -229,7 +420,10 @@ def test_product_query_by_id_weight_is_rounded(user_api_client, product, site_se
site_settings.default_weight_unit = WeightUnits.KILOGRAM
site_settings.save(update_fields=["default_weight_unit"])
- variables = {"id": graphene.Node.to_global_id("Product", product.pk)}
+ variables = {
+ "id": graphene.Node.to_global_id("Product", product.pk),
+ "channel": channel_USD.slug,
+ }
# when
response = user_api_client.post_graphql(QUERY_PRODUCT, variables=variables)
@@ -243,10 +437,210 @@ def test_product_query_by_id_weight_is_rounded(user_api_client, product, site_se
assert product_data["weight"]["unit"] == WeightUnits.KILOGRAM.upper()
-def test_product_query_by_slug(
- user_api_client, product,
+def test_product_query_by_slug(user_api_client, product, channel_USD):
+ variables = {
+ "id": graphene.Node.to_global_id("Product", product.pk),
+ "channel": channel_USD.slug,
+ }
+ ProductChannelListing.objects.filter(product=product, channel=channel_USD).update(
+ is_published=False
+ )
+
+ response = user_api_client.post_graphql(QUERY_PRODUCT, variables=variables)
+ content = get_graphql_content(response)
+ product_data = content["data"]["product"]
+ assert product_data is None
+
+
+def test_product_query_by_id_not_existing_in_channel_as_customer(
+ user_api_client, product, channel_USD
+):
+ variables = {
+ "id": graphene.Node.to_global_id("Product", product.pk),
+ "channel": channel_USD.slug,
+ }
+ ProductChannelListing.objects.filter(product=product, channel=channel_USD).delete()
+
+ response = user_api_client.post_graphql(QUERY_PRODUCT, variables=variables)
+ content = get_graphql_content(response)
+ product_data = content["data"]["product"]
+ assert product_data is None
+
+
+def test_product_query_by_slug_available_as_staff_user(
+ staff_api_client, permission_manage_products, product, channel_USD
+):
+ variables = {
+ "slug": product.slug,
+ "channel": channel_USD.slug,
+ }
+
+ response = staff_api_client.post_graphql(
+ QUERY_PRODUCT,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ check_no_permissions=False,
+ )
+ content = get_graphql_content(response)
+ product_data = content["data"]["product"]
+ assert product_data is not None
+ assert product_data["name"] == product.name
+
+
+def test_product_query_by_slug_not_available_as_staff_user(
+ staff_api_client, permission_manage_products, product, channel_USD
+):
+ variables = {
+ "slug": product.slug,
+ "channel": channel_USD.slug,
+ }
+ ProductChannelListing.objects.filter(product=product, channel=channel_USD).update(
+ is_published=False
+ )
+
+ response = staff_api_client.post_graphql(
+ QUERY_PRODUCT,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ check_no_permissions=False,
+ )
+ content = get_graphql_content(response)
+ product_data = content["data"]["product"]
+ assert product_data is not None
+ assert product_data["name"] == product.name
+
+
+def test_product_query_by_slug_not_existing_in_channel_as_staff_user(
+ staff_api_client, permission_manage_products, product, channel_USD
+):
+ variables = {
+ "slug": product.slug,
+ "channel": channel_USD.slug,
+ }
+ ProductChannelListing.objects.filter(product=product, channel=channel_USD).delete()
+
+ response = staff_api_client.post_graphql(
+ QUERY_PRODUCT,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ check_no_permissions=False,
+ )
+ content = get_graphql_content(response)
+ product_data = content["data"]["product"]
+ assert product_data is None
+
+
+def test_product_query_by_slug_as_staff_user_without_channel(
+ staff_api_client, permission_manage_products, product, channel_USD
+):
+ variables = {
+ "slug": product.slug,
+ }
+ ProductChannelListing.objects.filter(product=product, channel=channel_USD).delete()
+
+ response = staff_api_client.post_graphql(
+ QUERY_PRODUCT,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ check_no_permissions=False,
+ )
+ content = get_graphql_content(response)
+ product_data = content["data"]["product"]
+ assert product_data is not None
+ assert product_data["name"] == product.name
+
+
+def test_product_query_by_slug_available_as_app(
+ app_api_client, permission_manage_products, product, channel_USD
+):
+ variables = {
+ "slug": product.slug,
+ "channel": channel_USD.slug,
+ }
+
+ response = app_api_client.post_graphql(
+ QUERY_PRODUCT,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ check_no_permissions=False,
+ )
+ content = get_graphql_content(response)
+ product_data = content["data"]["product"]
+ assert product_data is not None
+ assert product_data["name"] == product.name
+
+
+def test_product_query_by_slug_not_available_as_app(
+ app_api_client, permission_manage_products, product, channel_USD
):
- variables = {"slug": product.slug}
+ variables = {
+ "slug": product.slug,
+ "channel": channel_USD.slug,
+ }
+ ProductChannelListing.objects.filter(product=product, channel=channel_USD).update(
+ is_published=False
+ )
+
+ response = app_api_client.post_graphql(
+ QUERY_PRODUCT,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ check_no_permissions=False,
+ )
+ content = get_graphql_content(response)
+ product_data = content["data"]["product"]
+ assert product_data is not None
+ assert product_data["name"] == product.name
+
+
+def test_product_query_by_slug_not_existing_in_channel_as_app(
+ app_api_client, permission_manage_products, product, channel_USD
+):
+ variables = {
+ "slug": product.slug,
+ "channel": channel_USD.slug,
+ }
+ ProductChannelListing.objects.filter(product=product, channel=channel_USD).delete()
+
+ response = app_api_client.post_graphql(
+ QUERY_PRODUCT,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ check_no_permissions=False,
+ )
+ content = get_graphql_content(response)
+ product_data = content["data"]["product"]
+ assert product_data is None
+
+
+def test_product_query_by_slug_as_app_without_channel(
+ app_api_client, permission_manage_products, product, channel_USD
+):
+ variables = {
+ "slug": product.slug,
+ }
+ ProductChannelListing.objects.filter(product=product, channel=channel_USD).delete()
+
+ response = app_api_client.post_graphql(
+ QUERY_PRODUCT,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ check_no_permissions=False,
+ )
+ content = get_graphql_content(response)
+ product_data = content["data"]["product"]
+ assert product_data is not None
+ assert product_data["name"] == product.name
+
+
+def test_product_query_by_slug_available_as_customer(
+ user_api_client, product, channel_USD
+):
+ variables = {
+ "slug": product.slug,
+ "channel": channel_USD.slug,
+ }
+
response = user_api_client.post_graphql(QUERY_PRODUCT, variables=variables)
content = get_graphql_content(response)
product_data = content["data"]["product"]
@@ -254,13 +648,34 @@ def test_product_query_by_slug(
assert product_data["name"] == product.name
-def test_product_query_is_available_for_purchase_true(user_api_client, product):
+def test_product_query_by_slug_not_available_as_customer(
+ user_api_client, product, channel_USD
+):
+ variables = {
+ "slug": product.slug,
+ "channel": channel_USD.slug,
+ }
+ ProductChannelListing.objects.filter(product=product, channel=channel_USD).update(
+ is_published=False
+ )
+
+ response = user_api_client.post_graphql(QUERY_PRODUCT, variables=variables)
+ content = get_graphql_content(response)
+ product_data = content["data"]["product"]
+ assert product_data is None
+
+
+def test_product_query_is_available_for_purchase_true(
+ user_api_client, product, channel_USD
+):
# given
available_for_purchase = datetime.today() - timedelta(days=1)
- product.available_for_purchase = available_for_purchase
- product.save(update_fields=["available_for_purchase"])
+ product.channel_listings.update(available_for_purchase=available_for_purchase)
- variables = {"id": graphene.Node.to_global_id("Product", product.pk)}
+ variables = {
+ "id": graphene.Node.to_global_id("Product", product.pk),
+ "channel": channel_USD.slug,
+ }
# when
response = user_api_client.post_graphql(QUERY_PRODUCT, variables=variables)
@@ -275,13 +690,17 @@ def test_product_query_is_available_for_purchase_true(user_api_client, product):
assert product_data["isAvailableForPurchase"] is True
-def test_product_query_is_available_for_purchase_false(user_api_client, product):
+def test_product_query_is_available_for_purchase_false(
+ user_api_client, product, channel_USD
+):
# given
available_for_purchase = datetime.today() + timedelta(days=1)
- product.available_for_purchase = available_for_purchase
- product.save(update_fields=["available_for_purchase"])
+ product.channel_listings.update(available_for_purchase=available_for_purchase)
- variables = {"id": graphene.Node.to_global_id("Product", product.pk)}
+ variables = {
+ "id": graphene.Node.to_global_id("Product", product.pk),
+ "channel": channel_USD.slug,
+ }
# when
response = user_api_client.post_graphql(QUERY_PRODUCT, variables=variables)
@@ -297,13 +716,15 @@ def test_product_query_is_available_for_purchase_false(user_api_client, product)
def test_product_query_is_available_for_purchase_false_no_available_for_purchase_date(
- user_api_client, product
+ user_api_client, product, channel_USD
):
# given
- product.available_for_purchase = None
- product.save(update_fields=["available_for_purchase"])
+ product.channel_listings.update(available_for_purchase=None)
- variables = {"id": graphene.Node.to_global_id("Product", product.pk)}
+ variables = {
+ "id": graphene.Node.to_global_id("Product", product.pk),
+ "channel": channel_USD.slug,
+ }
# when
response = user_api_client.post_graphql(QUERY_PRODUCT, variables=variables)
@@ -317,15 +738,19 @@ def test_product_query_is_available_for_purchase_false_no_available_for_purchase
def test_product_query_unpublished_products_by_slug(
- user_api_client, product, permission_manage_products
+ user_api_client, product, permission_manage_products, channel_USD
):
# given
user = user_api_client.user
user.user_permissions.add(permission_manage_products)
- product.is_published = False
- product.save(update_fields=["is_published"])
- variables = {"slug": product.slug}
+ ProductChannelListing.objects.filter(product=product, channel=channel_USD).update(
+ is_published=False
+ )
+ variables = {
+ "slug": product.slug,
+ "channel": channel_USD.slug,
+ }
# when
response = user_api_client.post_graphql(QUERY_PRODUCT, variables=variables)
@@ -337,21 +762,72 @@ def test_product_query_unpublished_products_by_slug(
assert product_data["name"] == product.name
-def test_product_query_unpublished_products_by_slug_and_anonympus_user(
- api_client, product,
+def test_product_query_unpublished_products_by_slug_and_anonympus_user(
+ api_client, product, channel_USD
+):
+ # given
+ ProductChannelListing.objects.filter(product=product, channel=channel_USD).update(
+ is_published=False
+ )
+ variables = {
+ "slug": product.slug,
+ "channel": channel_USD.slug,
+ }
+
+ # when
+ response = api_client.post_graphql(QUERY_PRODUCT, variables=variables)
+
+ # then
+ content = get_graphql_content(response)
+ product_data = content["data"]["product"]
+ assert product_data is None
+
+
+def test_product_query_by_slug_not_existing_in_channel_as_customer(
+ user_api_client, product, channel_USD
+):
+ variables = {
+ "slug": product.slug,
+ "channel": channel_USD.slug,
+ }
+ ProductChannelListing.objects.filter(product=product, channel=channel_USD).delete()
+
+ response = user_api_client.post_graphql(QUERY_PRODUCT, variables=variables)
+ content = get_graphql_content(response)
+ product_data = content["data"]["product"]
+ assert product_data is None
+
+
+QUERY_PRODUCT_WITHOUT_CHANNEL = """
+ query ($id: ID){
+ product(
+ id: $id
+ ) {
+ id
+ name
+ }
+ }
+ """
+
+
+def test_product_query_by_id_without_channel_not_available_as_staff_user(
+ staff_api_client, permission_manage_products, product, channel_USD
):
- # given
- product.is_published = False
- product.save(update_fields=["is_published"])
- variables = {"slug": product.slug}
-
- # when
- response = api_client.post_graphql(QUERY_PRODUCT, variables=variables)
+ variables = {"id": graphene.Node.to_global_id("Product", product.pk)}
+ ProductChannelListing.objects.filter(product=product, channel=channel_USD).update(
+ is_published=False
+ )
- # then
+ response = staff_api_client.post_graphql(
+ QUERY_PRODUCT_WITHOUT_CHANNEL,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ check_no_permissions=False,
+ )
content = get_graphql_content(response)
product_data = content["data"]["product"]
- assert product_data is None
+ assert product_data is not None
+ assert product_data["name"] == product.name
def test_product_query_error_when_id_and_slug_provided(
@@ -381,59 +857,242 @@ def test_product_query_error_when_no_param(
assert len(content["errors"]) == 1
-def test_fetch_all_products(user_api_client, product):
- response = user_api_client.post_graphql(QUERY_FETCH_ALL_PRODUCTS)
+def test_fetch_all_products_available_as_staff_user(
+ staff_api_client, permission_manage_products, product, channel_USD
+):
+ variables = {"channel": channel_USD.slug}
+ response = staff_api_client.post_graphql(
+ QUERY_FETCH_ALL_PRODUCTS,
+ variables,
+ permissions=(permission_manage_products,),
+ check_no_permissions=False,
+ )
+ content = get_graphql_content(response)
+ num_products = Product.objects.count()
+ assert content["data"]["products"]["totalCount"] == num_products
+ assert len(content["data"]["products"]["edges"]) == num_products
+
+
+def test_fetch_all_products_not_available_as_staff_user(
+ staff_api_client, permission_manage_products, product, channel_USD
+):
+ variables = {"channel": channel_USD.slug}
+ ProductChannelListing.objects.filter(product=product, channel=channel_USD).update(
+ is_published=False
+ )
+
+ response = staff_api_client.post_graphql(
+ QUERY_FETCH_ALL_PRODUCTS,
+ variables,
+ permissions=(permission_manage_products,),
+ check_no_permissions=False,
+ )
+ content = get_graphql_content(response)
+ num_products = Product.objects.count()
+ assert content["data"]["products"]["totalCount"] == num_products
+ assert len(content["data"]["products"]["edges"]) == num_products
+
+
+def test_fetch_all_products_not_existing_in_channel_as_staff_user(
+ staff_api_client, permission_manage_products, channel_USD, product_list
+):
+ variables = {"channel": channel_USD.slug}
+ ProductChannelListing.objects.filter(
+ product=product_list[0], channel=channel_USD
+ ).delete()
+
+ response = staff_api_client.post_graphql(
+ QUERY_FETCH_ALL_PRODUCTS,
+ variables,
+ permissions=(permission_manage_products,),
+ check_no_permissions=False,
+ )
+ content = get_graphql_content(response)
+
+ # if channel slug is provided we return all products related to this channel
+ num_products = Product.objects.count() - 1
+
+ assert content["data"]["products"]["totalCount"] == num_products
+ assert len(content["data"]["products"]["edges"]) == num_products
+
+
+def test_fetch_all_products_as_staff_user_without_channel_slug(
+ staff_api_client, permission_manage_products, product_list, channel_USD
+):
+ ProductChannelListing.objects.filter(
+ product=product_list[0], channel=channel_USD
+ ).delete()
+
+ response = staff_api_client.post_graphql(
+ QUERY_FETCH_ALL_PRODUCTS,
+ permissions=(permission_manage_products,),
+ check_no_permissions=False,
+ )
+ content = get_graphql_content(response)
+ num_products = Product.objects.count()
+ assert content["data"]["products"]["totalCount"] == num_products
+ assert len(content["data"]["products"]["edges"]) == num_products
+
+
+def test_fetch_all_products_available_as_app(
+ app_api_client, permission_manage_products, product, channel_USD
+):
+ variables = {"channel": channel_USD.slug}
+ response = app_api_client.post_graphql(
+ QUERY_FETCH_ALL_PRODUCTS,
+ variables,
+ permissions=(permission_manage_products,),
+ check_no_permissions=False,
+ )
content = get_graphql_content(response)
num_products = Product.objects.count()
assert content["data"]["products"]["totalCount"] == num_products
assert len(content["data"]["products"]["edges"]) == num_products
-def test_fetch_all_products_app(
- app_api_client, unavailable_product, permission_manage_products,
+def test_fetch_all_products_not_available_as_app(
+ app_api_client, permission_manage_products, product, channel_USD
):
+ variables = {"channel": channel_USD.slug}
+ ProductChannelListing.objects.filter(product=product, channel=channel_USD).update(
+ is_published=False
+ )
+
response = app_api_client.post_graphql(
QUERY_FETCH_ALL_PRODUCTS,
- permissions=[permission_manage_products],
+ variables,
+ permissions=(permission_manage_products,),
check_no_permissions=False,
)
content = get_graphql_content(response)
- product_data = content["data"]["products"]["edges"][0]["node"]
- assert product_data["name"] == unavailable_product.name
- assert product_data["isPublished"] == unavailable_product.is_published
+ num_products = Product.objects.count()
+ assert content["data"]["products"]["totalCount"] == num_products
+ assert len(content["data"]["products"]["edges"]) == num_products
-def test_fetch_unavailable_products(user_api_client, product):
- Product.objects.update(is_published=False)
- query = """
- query {
- products(first: 1) {
- totalCount
- edges {
- node {
- id
- }
- }
- }
- }
- """
- response = user_api_client.post_graphql(query)
+def test_fetch_all_products_not_existing_in_channel_as_app(
+ app_api_client, permission_manage_products, product_list, channel_USD
+):
+ variables = {"channel": channel_USD.slug}
+ ProductChannelListing.objects.filter(
+ product=product_list[0], channel=channel_USD
+ ).delete()
+
+ response = app_api_client.post_graphql(
+ QUERY_FETCH_ALL_PRODUCTS,
+ variables,
+ permissions=(permission_manage_products,),
+ check_no_permissions=False,
+ )
+ content = get_graphql_content(response)
+ # if channel slug is provided we return all products related to this channel
+
+ num_products = Product.objects.count() - 1
+ assert content["data"]["products"]["totalCount"] == num_products
+ assert len(content["data"]["products"]["edges"]) == num_products
+
+
+def test_fetch_all_products_as_app_without_channel_slug(
+ app_api_client, permission_manage_products, product_list, channel_USD
+):
+ ProductChannelListing.objects.filter(
+ product=product_list[0], channel=channel_USD
+ ).delete()
+
+ response = app_api_client.post_graphql(
+ QUERY_FETCH_ALL_PRODUCTS,
+ permissions=(permission_manage_products,),
+ check_no_permissions=False,
+ )
+ content = get_graphql_content(response)
+ num_products = Product.objects.count()
+ assert content["data"]["products"]["totalCount"] == num_products
+ assert len(content["data"]["products"]["edges"]) == num_products
+
+
+def test_fetch_all_products_available_as_customer(
+ user_api_client, product, channel_USD
+):
+ variables = {"channel": channel_USD.slug}
+ response = user_api_client.post_graphql(QUERY_FETCH_ALL_PRODUCTS, variables)
+ content = get_graphql_content(response)
+ num_products = Product.objects.count()
+ assert content["data"]["products"]["totalCount"] == num_products
+ assert len(content["data"]["products"]["edges"]) == num_products
+
+
+def test_fetch_all_products_not_available_as_customer(
+ user_api_client, product, channel_USD
+):
+ variables = {"channel": channel_USD.slug}
+ ProductChannelListing.objects.filter(product=product, channel=channel_USD).update(
+ is_published=False
+ )
+
+ response = user_api_client.post_graphql(QUERY_FETCH_ALL_PRODUCTS, variables,)
+ content = get_graphql_content(response)
+ assert content["data"]["products"]["totalCount"] == 0
+ assert not content["data"]["products"]["edges"]
+
+
+def test_fetch_all_products_not_existing_in_channel_as_customer(
+ user_api_client, product, channel_USD
+):
+ variables = {"channel": channel_USD.slug}
+ ProductChannelListing.objects.filter(product=product, channel=channel_USD).delete()
+
+ response = user_api_client.post_graphql(QUERY_FETCH_ALL_PRODUCTS, variables)
+ content = get_graphql_content(response)
+ assert content["data"]["products"]["totalCount"] == 0
+ assert not content["data"]["products"]["edges"]
+
+
+def test_fetch_all_products_available_as_anonymous(api_client, product, channel_USD):
+ variables = {"channel": channel_USD.slug}
+ response = api_client.post_graphql(QUERY_FETCH_ALL_PRODUCTS, variables)
+ content = get_graphql_content(response)
+ num_products = Product.objects.count()
+ assert content["data"]["products"]["totalCount"] == num_products
+ assert len(content["data"]["products"]["edges"]) == num_products
+
+
+def test_fetch_all_products_not_available_as_anonymous(
+ api_client, product, channel_USD
+):
+ variables = {"channel": channel_USD.slug}
+ ProductChannelListing.objects.filter(product=product, channel=channel_USD).update(
+ is_published=False
+ )
+
+ response = api_client.post_graphql(QUERY_FETCH_ALL_PRODUCTS, variables,)
+ content = get_graphql_content(response)
+ assert content["data"]["products"]["totalCount"] == 0
+ assert not content["data"]["products"]["edges"]
+
+
+def test_fetch_all_products_not_existing_in_channel_as_anonymous(
+ api_client, product, channel_USD
+):
+ variables = {"channel": channel_USD.slug}
+ ProductChannelListing.objects.filter(product=product, channel=channel_USD).delete()
+
+ response = api_client.post_graphql(QUERY_FETCH_ALL_PRODUCTS, variables)
content = get_graphql_content(response)
assert content["data"]["products"]["totalCount"] == 0
assert not content["data"]["products"]["edges"]
def test_fetch_all_products_visible_in_listings(
- user_api_client, product_list, permission_manage_products,
+ user_api_client, product_list, permission_manage_products, channel_USD
):
# given
- product_list[0].visible_in_listings = False
- product_list[0].save(update_fields=["visible_in_listings"])
+ product_list[0].channel_listings.update(visible_in_listings=False)
product_count = Product.objects.count()
+ variables = {"channel": channel_USD.slug}
# when
- response = user_api_client.post_graphql(QUERY_FETCH_ALL_PRODUCTS)
+ response = user_api_client.post_graphql(QUERY_FETCH_ALL_PRODUCTS, variables)
# then
content = get_graphql_content(response)
@@ -444,17 +1103,18 @@ def test_fetch_all_products_visible_in_listings(
def test_fetch_all_products_visible_in_listings_by_staff_with_perm(
- staff_api_client, product_list, permission_manage_products,
+ staff_api_client, product_list, permission_manage_products, channel_USD
):
# given
- product_list[0].visible_in_listings = False
- product_list[0].save(update_fields=["visible_in_listings"])
+ product_list[0].channel_listings.update(visible_in_listings=False)
product_count = Product.objects.count()
+ variables = {"channel": channel_USD.slug}
# when
response = staff_api_client.post_graphql(
QUERY_FETCH_ALL_PRODUCTS,
+ variables,
permissions=[permission_manage_products],
check_no_permissions=False,
)
@@ -466,16 +1126,16 @@ def test_fetch_all_products_visible_in_listings_by_staff_with_perm(
def test_fetch_all_products_visible_in_listings_by_staff_without_perm(
- staff_api_client, product_list, permission_manage_products,
+ staff_api_client, product_list, permission_manage_products, channel_USD
):
# given
- product_list[0].visible_in_listings = False
- product_list[0].save(update_fields=["visible_in_listings"])
+ product_list[0].channel_listings.update(visible_in_listings=False)
product_count = Product.objects.count()
+ variables = {"channel": channel_USD.slug}
# when
- response = staff_api_client.post_graphql(QUERY_FETCH_ALL_PRODUCTS)
+ response = staff_api_client.post_graphql(QUERY_FETCH_ALL_PRODUCTS, variables)
# then
content = get_graphql_content(response)
@@ -486,17 +1146,18 @@ def test_fetch_all_products_visible_in_listings_by_staff_without_perm(
def test_fetch_all_products_visible_in_listings_by_app_with_perm(
- app_api_client, product_list, permission_manage_products,
+ app_api_client, product_list, permission_manage_products, channel_USD
):
# given
- product_list[0].visible_in_listings = False
- product_list[0].save(update_fields=["visible_in_listings"])
+ product_list[0].channel_listings.update(visible_in_listings=False)
product_count = Product.objects.count()
+ variables = {"channel": channel_USD.slug}
# when
response = app_api_client.post_graphql(
QUERY_FETCH_ALL_PRODUCTS,
+ variables,
permissions=[permission_manage_products],
check_no_permissions=False,
)
@@ -508,16 +1169,16 @@ def test_fetch_all_products_visible_in_listings_by_app_with_perm(
def test_fetch_all_products_visible_in_listings_by_app_without_perm(
- app_api_client, product_list, permission_manage_products,
+ app_api_client, product_list, permission_manage_products, channel_USD
):
# given
- product_list[0].visible_in_listings = False
- product_list[0].save(update_fields=["visible_in_listings"])
+ product_list[0].channel_listings.update(visible_in_listings=False)
product_count = Product.objects.count()
+ variables = {"channel": channel_USD.slug}
# when
- response = app_api_client.post_graphql(QUERY_FETCH_ALL_PRODUCTS)
+ response = app_api_client.post_graphql(QUERY_FETCH_ALL_PRODUCTS, variables)
# then
content = get_graphql_content(response)
@@ -527,13 +1188,15 @@ def test_fetch_all_products_visible_in_listings_by_app_without_perm(
assert graphene.Node.to_global_id("Product", product_list[0].pk) not in products_ids
-def test_product_query(staff_api_client, product, permission_manage_products, stock):
+def test_fetch_product_from_category_query(
+ staff_api_client, product, permission_manage_products, stock, channel_USD
+):
category = Category.objects.first()
product = category.products.first()
query = """
query {
category(id: "%(category_id)s") {
- products(first: 20) {
+ products(first: 20, channel: "%(channel_slug)s") {
edges {
node {
id
@@ -549,6 +1212,25 @@ def test_product_query(staff_api_client, product, permission_manage_products, st
}
variants {
name
+ channelListings {
+ costPrice {
+ amount
+ }
+ }
+ }
+ channelListings {
+ purchaseCost {
+ start {
+ amount
+ }
+ stop {
+ amount
+ }
+ }
+ margin {
+ start
+ stop
+ }
}
isAvailable
pricing {
@@ -568,25 +1250,14 @@ def test_product_query(staff_api_client, product, permission_manage_products, st
}
}
}
- purchaseCost {
- start {
- amount
- }
- stop {
- amount
- }
- }
- margin {
- start
- stop
- }
}
}
}
}
}
""" % {
- "category_id": graphene.Node.to_global_id("Category", category.id)
+ "category_id": graphene.Node.to_global_id("Category", category.id),
+ "channel_slug": channel_USD.slug,
}
staff_api_client.user.user_permissions.add(permission_manage_products)
response = staff_api_client.post_graphql(query)
@@ -598,14 +1269,27 @@ def test_product_query(staff_api_client, product, permission_manage_products, st
assert product_data["name"] == product.name
assert product_data["url"] == ""
assert product_data["slug"] == product.slug
- from ....product.utils.costs import get_product_costs_data
- purchase_cost, margin = get_product_costs_data(product)
- assert purchase_cost.start.amount == product_data["purchaseCost"]["start"]["amount"]
- assert purchase_cost.stop.amount == product_data["purchaseCost"]["stop"]["amount"]
- assert product_data["isAvailable"] is product.is_visible
- assert margin[0] == product_data["margin"]["start"]
- assert margin[1] == product_data["margin"]["stop"]
+ variant = product.variants.first()
+ variant_channel_listing = variant.channel_listings.filter(channel_id=channel_USD.id)
+ purchase_cost, margin = get_product_costs_data(
+ variant_channel_listing, True, channel_USD.currency_code
+ )
+ cost_start = product_data["channelListings"][0]["purchaseCost"]["start"]["amount"]
+ cost_stop = product_data["channelListings"][0]["purchaseCost"]["stop"]["amount"]
+
+ assert purchase_cost.start.amount == cost_start
+ assert purchase_cost.stop.amount == cost_stop
+ assert product_data["isAvailable"] is True
+ assert margin[0] == product_data["channelListings"][0]["margin"]["start"]
+ assert margin[1] == product_data["channelListings"][0]["margin"]["stop"]
+
+ variant = product.variants.first()
+ variant_channel_listing = variant.channel_listings.get(channel_id=channel_USD.id)
+ variant_channel_data = product_data["variants"][0]["channelListings"][0]
+ variant_cost = variant_channel_data["costPrice"]["amount"]
+
+ assert variant_channel_listing.cost_price.amount == variant_cost
def test_products_query_with_filter_attributes(
@@ -837,23 +1521,29 @@ def test_products_query_with_filter(
staff_api_client,
product,
permission_manage_products,
+ channel_USD,
):
- assert product.is_published is True
assert "Juice1" not in product.name
second_product = product
second_product.id = None
second_product.name = "Apple Juice1"
second_product.slug = "apple-juice1"
- second_product.is_published = products_filter.get("isPublished", True)
second_product.save()
- second_product.variants.create(
- product=second_product,
- sku=second_product.slug,
- cost_price=Money("1.00", "USD"),
+ variant_second_product = second_product.variants.create(
+ product=second_product, sku=second_product.slug,
+ )
+ ProductVariantChannelListing.objects.create(
+ variant=variant_second_product,
+ channel=channel_USD,
price_amount=Decimal(1.99),
+ cost_price_amount=Decimal(1),
+ currency=channel_USD.currency_code,
+ )
+ ProductChannelListing.objects.create(
+ product=second_product, channel=channel_USD, is_published=True,
)
- variables = {"filter": products_filter}
+ variables = {"filter": {"search": "Juice1"}, "channel": channel_USD.slug}
staff_api_client.user.user_permissions.add(permission_manage_products)
response = staff_api_client.post_graphql(query_products_with_filter, variables)
content = get_graphql_content(response)
@@ -873,9 +1563,11 @@ def test_products_query_with_filter_search_by_sku(
product_with_two_variants,
product_with_default_variant,
permission_manage_products,
+ channel_USD,
):
- product_with_default_variant.is_published = is_published
- product_with_default_variant.save(update_fields=["is_published"])
+ ProductChannelListing.objects.filter(
+ product=product_with_default_variant, channel=channel_USD
+ ).update(is_published=is_published)
variables = {"filter": {"search": "1234"}}
staff_api_client.user.user_permissions.add(permission_manage_products)
response = staff_api_client.post_graphql(query_products_with_filter, variables)
@@ -935,6 +1627,7 @@ def test_products_query_with_filter_stocks(
product_with_single_variant,
product_with_two_variants,
warehouse,
+ channel_USD,
):
product1 = product_with_single_variant
product2 = product_with_two_variants
@@ -984,7 +1677,8 @@ def test_products_query_with_filter_stocks(
variables = {
"filter": {
"stocks": {"quantity": quantity_input, "warehouseIds": warehouse_pks}
- }
+ },
+ "channel": channel_USD.slug,
}
response = staff_api_client.post_graphql(
query_products_with_filter, variables, check_no_permissions=False
@@ -1002,13 +1696,16 @@ def test_products_query_with_filter_stocks(
def test_query_products_with_filter_ids(
- api_client, product_list, query_products_with_filter
+ api_client, product_list, query_products_with_filter, channel_USD
):
# given
product_ids = [
graphene.Node.to_global_id("Product", product.id) for product in product_list
][:2]
- variables = {"filter": {"ids": product_ids}}
+ variables = {
+ "filter": {"ids": product_ids},
+ "channel": channel_USD.slug,
+ }
# when
response = api_client.post_graphql(query_products_with_filter, variables)
@@ -1021,11 +1718,11 @@ def test_query_products_with_filter_ids(
assert [node["node"]["id"] for node in products_data] == product_ids
-def test_query_product_image_by_id(user_api_client, product_with_image):
+def test_query_product_image_by_id(user_api_client, product_with_image, channel_USD):
image = product_with_image.images.first()
query = """
- query productImageById($imageId: ID!, $productId: ID!) {
- product(id: $productId) {
+ query productImageById($imageId: ID!, $productId: ID!, $channel: String) {
+ product(id: $productId, channel: $channel) {
imageById(id: $imageId) {
id
url
@@ -1036,13 +1733,16 @@ def test_query_product_image_by_id(user_api_client, product_with_image):
variables = {
"productId": graphene.Node.to_global_id("Product", product_with_image.pk),
"imageId": graphene.Node.to_global_id("ProductImage", image.pk),
+ "channel": channel_USD.slug,
}
response = user_api_client.post_graphql(query, variables)
- get_graphql_content(response)
+ data = get_graphql_content(response)
+ assert data["data"]["product"]["imageById"]["id"]
+ assert data["data"]["product"]["imageById"]["url"]
def test_product_with_collections(
- staff_api_client, product, collection, permission_manage_products
+ staff_api_client, product, published_collection, permission_manage_products
):
query = """
query getProduct($productID: ID!) {
@@ -1053,7 +1753,7 @@ def test_product_with_collections(
}
}
"""
- product.collections.add(collection)
+ product.collections.add(published_collection)
product.save()
product_id = graphene.Node.to_global_id("Product", product.id)
@@ -1062,71 +1762,22 @@ def test_product_with_collections(
response = staff_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["product"]
- assert data["collections"][0]["name"] == collection.name
+ assert data["collections"][0]["name"] == published_collection.name
assert len(data["collections"]) == 1
-def test_fetch_product_by_id(user_api_client, product):
- query = """
- query ($productId: ID!) {
- product(id: $productId) {
- name
- }
- }
- """
- variables = {"productId": graphene.Node.to_global_id("Product", product.id)}
- response = user_api_client.post_graphql(query, variables)
- content = get_graphql_content(response)
- product_data = content["data"]["product"]
- assert product_data["name"] == product.name
-
-
-def _fetch_product(client, product, permissions=None):
- query = """
- query ($productId: ID!) {
- product(id: $productId) {
- name,
- isPublished
- }
- }
- """
- variables = {"productId": graphene.Node.to_global_id("Product", product.id)}
- response = client.post_graphql(
- query, variables, permissions=permissions, check_no_permissions=False
- )
- content = get_graphql_content(response)
- return content["data"]["product"]
-
-
-def test_fetch_unpublished_product_staff_user(
- staff_api_client, unavailable_product, permission_manage_products
-):
- product_data = _fetch_product(
- staff_api_client, unavailable_product, permissions=[permission_manage_products]
- )
- assert product_data["name"] == unavailable_product.name
- assert product_data["isPublished"] == unavailable_product.is_published
-
-
-def test_fetch_unpublished_product_customer(user_api_client, unavailable_product):
- product_data = _fetch_product(user_api_client, unavailable_product)
- assert product_data is None
-
-
-def test_fetch_unpublished_product_anonymous_user(api_client, unavailable_product):
- product_data = _fetch_product(api_client, unavailable_product)
- assert product_data is None
-
-
-def test_filter_products_by_wrong_attributes(user_api_client, product):
+def test_filter_products_by_wrong_attributes(user_api_client, product, channel_USD):
product_attr = product.product_type.product_attributes.get(slug="color")
attr_value = (
product.product_type.variant_attributes.get(slug="size").values.first().id
)
query = """
- query {
- products(filter:
- {attributes: {slug: "%(slug)s", value: "%(value)s"}}, first: 1) {
+ query ($channel: String){
+ products(
+ filter: {attributes: {slug: "%(slug)s", value: "%(value)s"}},
+ first: 1,
+ channel: $channel
+ ) {
edges {
node {
name
@@ -1139,7 +1790,8 @@ def test_filter_products_by_wrong_attributes(user_api_client, product):
"value": attr_value,
}
- response = user_api_client.post_graphql(query)
+ variables = {"channel": channel_USD.slug}
+ response = user_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
products = content["data"]["products"]["edges"]
@@ -1147,11 +1799,13 @@ def test_filter_products_by_wrong_attributes(user_api_client, product):
SORT_PRODUCTS_QUERY = """
- query {
- products(sortBy: %(sort_by_product_order)s, first: 2) {
+ query ($channel:String) {
+ products (
+ sortBy: %(sort_by_product_order)s, first: 2, channel: $channel
+ ) {
edges {
node {
- isPublished
+ name
productType{
name
}
@@ -1179,30 +1833,36 @@ SORT_PRODUCTS_QUERY = """
"""
-def test_sort_products(user_api_client, product):
- # set price and update date of the first product
- product.minimal_variant_price_amount = 10
+def test_sort_products(user_api_client, product, channel_USD):
product.updated_at = datetime.utcnow()
product.save()
- # Create the second product with higher price and date
product.pk = None
product.slug = "second-product"
- product.minimal_variant_amount = 20
product.updated_at = datetime.utcnow()
product.save()
- ProductVariant.objects.create(
+ ProductChannelListing.objects.create(
product=product,
- sku="1234",
- cost_price=Money("1.00", "USD"),
+ channel=channel_USD,
+ is_published=True,
+ visible_in_listings=True,
+ )
+ variant = ProductVariant.objects.create(product=product, sku="1234")
+ ProductVariantChannelListing.objects.create(
+ variant=variant,
+ channel=channel_USD,
price_amount=Decimal(20),
+ cost_price_amount=Decimal(2),
+ currency=channel_USD.currency_code,
)
+ variables = {"channel": channel_USD.slug}
query = SORT_PRODUCTS_QUERY
# Test sorting by PRICE, ascending
- asc_price_query = query % {"sort_by_product_order": "{field: PRICE, direction:ASC}"}
- response = user_api_client.post_graphql(asc_price_query)
+ sort_by = f'{{field: PRICE, direction: ASC, channel: "{channel_USD.slug}"}}'
+ asc_price_query = query % {"sort_by_product_order": sort_by}
+ response = user_api_client.post_graphql(asc_price_query, variables)
content = get_graphql_content(response)
edges = content["data"]["products"]["edges"]
price1 = edges[0]["node"]["pricing"]["priceRangeUndiscounted"]["start"]["gross"][
@@ -1214,10 +1874,9 @@ def test_sort_products(user_api_client, product):
assert price1 < price2
# Test sorting by PRICE, descending
- desc_price_query = query % {
- "sort_by_product_order": "{field: PRICE, direction:DESC}"
- }
- response = user_api_client.post_graphql(desc_price_query)
+ sort_by = f'{{field: PRICE, direction:DESC, channel: "{channel_USD.slug}"}}'
+ desc_price_query = query % {"sort_by_product_order": sort_by}
+ response = user_api_client.post_graphql(desc_price_query, variables)
content = get_graphql_content(response)
edges = content["data"]["products"]["edges"]
price1 = edges[0]["node"]["pricing"]["priceRangeUndiscounted"]["start"]["gross"][
@@ -1229,10 +1888,9 @@ def test_sort_products(user_api_client, product):
assert price1 > price2
# Test sorting by MINIMAL_PRICE, ascending
- asc_price_query = query % {
- "sort_by_product_order": "{field: MINIMAL_PRICE, direction:ASC}"
- }
- response = user_api_client.post_graphql(asc_price_query)
+ sort_by = f'{{field: MINIMAL_PRICE, direction:ASC, channel: "{channel_USD.slug}"}}'
+ asc_price_query = query % {"sort_by_product_order": sort_by}
+ response = user_api_client.post_graphql(asc_price_query, variables)
content = get_graphql_content(response)
edges = content["data"]["products"]["edges"]
price1 = edges[0]["node"]["pricing"]["priceRange"]["start"]["gross"]["amount"]
@@ -1240,10 +1898,9 @@ def test_sort_products(user_api_client, product):
assert price1 < price2
# Test sorting by MINIMAL_PRICE, descending
- desc_price_query = query % {
- "sort_by_product_order": "{field: MINIMAL_PRICE, direction:DESC}"
- }
- response = user_api_client.post_graphql(desc_price_query)
+ sort_by = f'{{field: MINIMAL_PRICE, direction:DESC, channel: "{channel_USD.slug}"}}'
+ desc_price_query = query % {"sort_by_product_order": sort_by}
+ response = user_api_client.post_graphql(desc_price_query, variables)
content = get_graphql_content(response)
edges = content["data"]["products"]["edges"]
price1 = edges[0]["node"]["pricing"]["priceRange"]["start"]["gross"]["amount"]
@@ -1252,7 +1909,7 @@ def test_sort_products(user_api_client, product):
# Test sorting by DATE, ascending
asc_date_query = query % {"sort_by_product_order": "{field: DATE, direction:ASC}"}
- response = user_api_client.post_graphql(asc_date_query)
+ response = user_api_client.post_graphql(asc_date_query, variables)
content = get_graphql_content(response)
date_0 = content["data"]["products"]["edges"][0]["node"]["updatedAt"]
date_1 = content["data"]["products"]["edges"][1]["node"]["updatedAt"]
@@ -1260,53 +1917,23 @@ def test_sort_products(user_api_client, product):
# Test sorting by DATE, descending
desc_date_query = query % {"sort_by_product_order": "{field: DATE, direction:DESC}"}
- response = user_api_client.post_graphql(desc_date_query)
+ response = user_api_client.post_graphql(desc_date_query, variables)
content = get_graphql_content(response)
date_0 = content["data"]["products"]["edges"][0]["node"]["updatedAt"]
date_1 = content["data"]["products"]["edges"][1]["node"]["updatedAt"]
assert parse_datetime(date_0) > parse_datetime(date_1)
-def test_sort_products_published(staff_api_client, product, permission_manage_products):
- # Create the second not published product
- product.slug = "second-product"
- product.pk = None
- product.is_published = False
- product.save()
-
- staff_api_client.user.user_permissions.add(permission_manage_products)
-
- # Test sorting by PUBLISHED, ascending
- asc_published_query = SORT_PRODUCTS_QUERY % {
- "sort_by_product_order": "{field: PUBLISHED, direction:ASC}"
- }
- response = staff_api_client.post_graphql(asc_published_query)
- content = get_graphql_content(response)
- is_published_0 = content["data"]["products"]["edges"][0]["node"]["isPublished"]
- is_published_1 = content["data"]["products"]["edges"][1]["node"]["isPublished"]
- assert is_published_0 is False
- assert is_published_1 is True
-
- # Test sorting by PUBLISHED, descending
- desc_published_query = SORT_PRODUCTS_QUERY % {
- "sort_by_product_order": "{field: PUBLISHED, direction:DESC}"
- }
- response = staff_api_client.post_graphql(desc_published_query)
- content = get_graphql_content(response)
- is_published_0 = content["data"]["products"]["edges"][0]["node"]["isPublished"]
- is_published_1 = content["data"]["products"]["edges"][1]["node"]["isPublished"]
- assert is_published_0 is True
- assert is_published_1 is False
-
-
def test_sort_products_product_type_name(
- user_api_client, product, product_with_default_variant
+ user_api_client, product, product_with_default_variant, channel_USD
):
+ variables = {"channel": channel_USD.slug}
+
# Test sorting by TYPE, ascending
asc_published_query = SORT_PRODUCTS_QUERY % {
"sort_by_product_order": "{field: TYPE, direction:ASC}"
}
- response = user_api_client.post_graphql(asc_published_query)
+ response = user_api_client.post_graphql(asc_published_query, variables)
content = get_graphql_content(response)
edges = content["data"]["products"]["edges"]
product_type_name_0 = edges[0]["node"]["productType"]["name"]
@@ -1317,7 +1944,7 @@ def test_sort_products_product_type_name(
desc_published_query = SORT_PRODUCTS_QUERY % {
"sort_by_product_order": "{field: TYPE, direction:DESC}"
}
- response = user_api_client.post_graphql(desc_published_query)
+ response = user_api_client.post_graphql(desc_published_query, variables)
content = get_graphql_content(response)
product_type_name_0 = edges[0]["node"]["productType"]["name"]
product_type_name_1 = edges[1]["node"]["productType"]["name"]
@@ -1375,8 +2002,6 @@ CREATE_PRODUCT_MUTATION = """
name
}
descriptionJson
- isPublished
- publicationDate
chargeTaxes
taxType {
taxCode
@@ -1396,7 +2021,6 @@ CREATE_PRODUCT_MUTATION = """
slug
}
}
- visibleInListings
}
productErrors {
field
@@ -1409,7 +2033,6 @@ CREATE_PRODUCT_MUTATION = """
"""
-@freeze_time("2020-03-18 12:00:00")
def test_create_product(
staff_api_client,
product_type,
@@ -1417,7 +2040,6 @@ def test_create_product(
size_attribute,
description_json,
permission_manage_products,
- settings,
monkeypatch,
):
query = CREATE_PRODUCT_MUTATION
@@ -1428,11 +2050,8 @@ def test_create_product(
category_id = graphene.Node.to_global_id("Category", category.pk)
product_name = "test name"
product_slug = "product-test-slug"
- product_is_published = True
product_charge_taxes = True
- visible_in_listings = True
product_tax_rate = "STANDARD"
- product_price = "22.33"
# Mock tax interface with fake response from tax gateway
monkeypatch.setattr(
@@ -1459,15 +2078,12 @@ def test_create_product(
"name": product_name,
"slug": product_slug,
"descriptionJson": description_json,
- "isPublished": product_is_published,
"chargeTaxes": product_charge_taxes,
"taxCode": product_tax_rate,
- "basePrice": product_price,
"attributes": [
{"id": color_attr_id, "values": [color_value_slug]},
{"id": size_attr_id, "values": [non_existent_attr_value]},
],
- "visibleInListings": visible_in_listings,
}
}
@@ -1480,13 +2096,10 @@ def test_create_product(
assert data["product"]["name"] == product_name
assert data["product"]["slug"] == product_slug
assert data["product"]["descriptionJson"] == description_json
- assert data["product"]["isPublished"] == product_is_published
assert data["product"]["chargeTaxes"] == product_charge_taxes
assert data["product"]["taxType"]["taxCode"] == product_tax_rate
assert data["product"]["productType"]["name"] == product_type.name
assert data["product"]["category"]["name"] == category.name
- assert data["product"]["visibleInListings"] == visible_in_listings
- assert data["product"]["publicationDate"] == "2020-03-18"
values = (
data["product"]["attributes"][0]["values"][0]["slug"],
data["product"]["attributes"][1]["values"][0]["slug"],
@@ -1551,6 +2164,9 @@ REORDER_PRODUCT_VARIANTS_MUTATION = """
code
field
}
+ product {
+ id
+ }
}
}
"""
@@ -1717,9 +2333,7 @@ def test_create_product_no_slug_in_input(
product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
category_id = graphene.Node.to_global_id("Category", category.pk)
product_name = "test name"
- product_is_published = True
product_tax_rate = "STANDARD"
- product_price = "22.33"
# Mock tax interface with fake response from tax gateway
monkeypatch.setattr(
@@ -1735,9 +2349,7 @@ def test_create_product_no_slug_in_input(
"category": category_id,
"name": product_name,
"slug": input_slug,
- "isPublished": product_is_published,
"taxCode": product_tax_rate,
- "basePrice": product_price,
}
}
@@ -1749,7 +2361,6 @@ def test_create_product_no_slug_in_input(
assert data["productErrors"] == []
assert data["product"]["name"] == product_name
assert data["product"]["slug"] == "test-name"
- assert data["product"]["isPublished"] == product_is_published
assert data["product"]["taxType"]["taxCode"] == product_tax_rate
assert data["product"]["productType"]["name"] == product_type.name
assert data["product"]["category"]["name"] == category.name
@@ -1768,9 +2379,7 @@ def test_create_product_no_category_id(
product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
product_name = "test name"
- product_is_published = False
product_tax_rate = "STANDARD"
- product_price = "22.33"
input_slug = "test-slug"
# Mock tax interface with fake response from tax gateway
@@ -1785,9 +2394,7 @@ def test_create_product_no_category_id(
"productType": product_type_id,
"name": product_name,
"slug": input_slug,
- "isPublished": product_is_published,
"taxCode": product_tax_rate,
- "basePrice": product_price,
}
}
@@ -1799,7 +2406,6 @@ def test_create_product_no_category_id(
assert data["productErrors"] == []
assert data["product"]["name"] == product_name
assert data["product"]["slug"] == input_slug
- assert data["product"]["isPublished"] == product_is_published
assert data["product"]["taxType"]["taxCode"] == product_tax_rate
assert data["product"]["productType"]["name"] == product_type.name
assert data["product"]["category"] is None
@@ -1839,76 +2445,6 @@ def test_create_product_with_negative_weight(
assert error["code"] == ProductErrorCode.INVALID.name
-def test_create_product_with_negative_base_price(
- staff_api_client,
- product_type,
- category,
- description_json,
- permission_manage_products,
-):
- # given
- query = CREATE_PRODUCT_MUTATION
-
- staff_api_client.user.user_permissions.add(permission_manage_products)
- description_json = json.dumps(description_json)
-
- product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
- category_id = graphene.Node.to_global_id("Category", category.pk)
- product_name = "test name"
-
- variables = {
- "input": {
- "productType": product_type_id,
- "category": category_id,
- "name": product_name,
- "basePrice": -1,
- }
- }
-
- # when
- response = staff_api_client.post_graphql(query, variables)
-
- # then
- assert_negative_positive_decimal_value(response)
-
-
-def test_create_product_with_too_many_decimal_places_in_price(
- staff_api_client,
- product_type,
- category,
- description_json,
- permission_manage_products,
-):
- # given
- query = CREATE_PRODUCT_MUTATION
-
- staff_api_client.user.user_permissions.add(permission_manage_products)
- description_json = json.dumps(description_json)
-
- product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
- category_id = graphene.Node.to_global_id("Category", category.pk)
- product_name = "test name"
-
- variables = {
- "input": {
- "productType": product_type_id,
- "category": category_id,
- "name": product_name,
- "basePrice": 1.1234,
- }
- }
-
- # when
- response = staff_api_client.post_graphql(query, variables)
-
- # then
- content = get_graphql_content(response)
- data = content["data"]["productCreate"]
- error = data["productErrors"][0]
- assert error["field"] == "basePrice"
- assert error["code"] == ProductErrorCode.INVALID.name
-
-
def test_create_product_with_unicode_in_slug_and_name(
staff_api_client,
product_type,
@@ -1964,11 +2500,8 @@ def test_create_product_invalid_product_attributes(
category_id = graphene.Node.to_global_id("Category", category.pk)
product_name = "test name"
product_slug = "product-test-slug"
- product_is_published = True
product_charge_taxes = True
- visible_in_listings = True
product_tax_rate = "STANDARD"
- product_price = "22.33"
# Mock tax interface with fake response from tax gateway
monkeypatch.setattr(
@@ -1999,10 +2532,8 @@ def test_create_product_invalid_product_attributes(
"name": product_name,
"slug": product_slug,
"descriptionJson": description_json,
- "isPublished": product_is_published,
"chargeTaxes": product_charge_taxes,
"taxCode": product_tax_rate,
- "basePrice": product_price,
"attributes": [
{"id": color_attr_id, "values": [" "]},
{"id": weight_attr_id, "values": [None]},
@@ -2011,7 +2542,6 @@ def test_create_product_invalid_product_attributes(
"values": [non_existent_attr_value, color_value_slug],
},
],
- "visibleInListings": visible_in_listings,
}
}
@@ -2047,34 +2577,19 @@ QUERY_CREATE_PRODUCT_WITHOUT_VARIANTS = """
mutation createProduct(
$productTypeId: ID!,
$categoryId: ID!
- $name: String!,
- $basePrice: PositiveDecimal!,
- $sku: String,
- $trackInventory: Boolean)
+ $name: String!)
{
productCreate(
input: {
category: $categoryId,
productType: $productTypeId,
name: $name,
- basePrice: $basePrice,
- sku: $sku,
- trackInventory: $trackInventory
})
{
product {
id
name
slug
- variants{
- id
- sku
- trackInventory
- quantity
- price {
- amount
- }
- }
category {
name
}
@@ -2101,17 +2616,11 @@ def test_create_product_without_variants(
category_id = graphene.Node.to_global_id("Category", category.pk)
product_name = "test name"
product_slug = "test-name"
- product_price = 10
- sku = "sku"
- track_inventory = True
variables = {
"productTypeId": product_type_id,
"categoryId": category_id,
"name": product_name,
- "basePrice": product_price,
- "sku": sku,
- "trackInventory": track_inventory,
}
response = staff_api_client.post_graphql(
@@ -2124,76 +2633,6 @@ def test_create_product_without_variants(
assert data["product"]["slug"] == product_slug
assert data["product"]["productType"]["name"] == product_type.name
assert data["product"]["category"]["name"] == category.name
- assert data["product"]["variants"][0]["sku"] == sku
- assert data["product"]["variants"][0]["trackInventory"] == track_inventory
- assert data["product"]["variants"][0]["price"]["amount"] == product_price
-
-
-def test_create_product_without_variants_sku_validation(
- staff_api_client, product_type_without_variant, category, permission_manage_products
-):
- query = QUERY_CREATE_PRODUCT_WITHOUT_VARIANTS
-
- product_type = product_type_without_variant
- product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
- category_id = graphene.Node.to_global_id("Category", category.pk)
- product_name = "test name"
- product_price = 10
- quantity = 1
- track_inventory = True
-
- variables = {
- "productTypeId": product_type_id,
- "categoryId": category_id,
- "name": product_name,
- "basePrice": product_price,
- "sku": None,
- "quantity": quantity,
- "trackInventory": track_inventory,
- }
-
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_products]
- )
- content = get_graphql_content(response)
- data = content["data"]["productCreate"]
- assert data["errors"][0]["field"] == "sku"
- assert data["errors"][0]["message"] == "This field cannot be blank."
-
-
-def test_create_product_without_variants_sku_duplication(
- staff_api_client,
- product_type_without_variant,
- category,
- permission_manage_products,
- product_with_default_variant,
-):
- query = QUERY_CREATE_PRODUCT_WITHOUT_VARIANTS
-
- product_type = product_type_without_variant
- product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
- category_id = graphene.Node.to_global_id("Category", category.pk)
- product_name = "test name"
- product_price = 10
- track_inventory = True
- sku = "1234"
-
- variables = {
- "productTypeId": product_type_id,
- "categoryId": category_id,
- "name": product_name,
- "basePrice": product_price,
- "sku": sku,
- "trackInventory": track_inventory,
- }
-
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_products]
- )
- content = get_graphql_content(response)
- data = content["data"]["productCreate"]
- assert data["errors"][0]["field"] == "sku"
- assert data["errors"][0]["message"] == "Product with this SKU already exists."
def test_product_create_without_product_type(
@@ -2203,7 +2642,6 @@ def test_product_create_without_product_type(
mutation createProduct($categoryId: ID!) {
productCreate(input: {
name: "Product",
- basePrice: "2.5",
productType: "",
category: $categoryId}) {
product {
@@ -2227,43 +2665,10 @@ def test_product_create_without_product_type(
assert errors[0]["message"] == "This field cannot be null."
-def test_product_create_without_category_and_true_is_published_value(
- staff_api_client, permission_manage_products, product_type
-):
- query = """
- mutation createProduct($productTypeId: ID!) {
- productCreate(input: {
- name: "Product",
- basePrice: "2.5",
- productType: $productTypeId,
- isPublished: true
- }) {
- product {
- id
- }
- productErrors {
- code
- field
- }
- }
- }
- """
-
- product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
- response = staff_api_client.post_graphql(
- query,
- {"productTypeId": product_type_id},
- permissions=[permission_manage_products],
- )
- errors = get_graphql_content(response)["data"]["productCreate"]["productErrors"]
- assert errors[0]["field"] == "category"
- assert errors[0]["code"] == ProductErrorCode.REQUIRED.name
-
-
def test_product_create_with_collections_webhook(
staff_api_client,
permission_manage_products,
- collection,
+ published_collection,
product_type,
category,
monkeypatch,
@@ -2272,9 +2677,7 @@ def test_product_create_with_collections_webhook(
mutation createProduct($productTypeId: ID!, $collectionId: ID!, $categoryId: ID!) {
productCreate(input: {
name: "Product",
- basePrice: "2.5",
productType: $productTypeId,
- isPublished: true,
collections: [$collectionId],
category: $categoryId
}) {
@@ -2298,7 +2701,7 @@ def test_product_create_with_collections_webhook(
def assert_product_has_collections(product):
assert product.collections.count() > 0
- assert product.collections.first() == collection
+ assert product.collections.first() == published_collection
monkeypatch.setattr(
"saleor.plugins.manager.PluginsManager.product_created",
@@ -2307,7 +2710,7 @@ def test_product_create_with_collections_webhook(
product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
category_id = graphene.Node.to_global_id("Category", category.pk)
- collection_id = graphene.Node.to_global_id("Collection", collection.pk)
+ collection_id = graphene.Node.to_global_id("Collection", published_collection.pk)
response = staff_api_client.post_graphql(
query,
@@ -2324,150 +2727,61 @@ def test_product_create_with_collections_webhook(
MUTATION_UPDATE_PRODUCT = """
mutation updateProduct(
- $productId: ID!,
- $categoryId: ID!,
- $name: String!,
- $slug: String!,
- $descriptionJson: JSONString!,
- $isPublished: Boolean!,
- $visibleInListings: Boolean!,
- $chargeTaxes: Boolean!,
- $taxCode: String!,
- $basePrice: PositiveDecimal!,
- $attributes: [AttributeValueInput!]) {
- productUpdate(
- id: $productId,
- input: {
- category: $categoryId,
- name: $name,
- slug: $slug,
- descriptionJson: $descriptionJson,
- isPublished: $isPublished,
- visibleInListings: $visibleInListings,
- chargeTaxes: $chargeTaxes,
- taxCode: $taxCode,
- basePrice: $basePrice,
- attributes: $attributes
- }) {
- product {
- category {
- name
- }
- descriptionJson
- isPublished
- publicationDate
- chargeTaxes
- variants {
- price {
- amount
- }
- }
- taxType {
- taxCode
- description
- }
- name
- slug
- productType {
- name
- }
- attributes {
- attribute {
- id
+ $productId: ID!,
+ $categoryId: ID!,
+ $name: String!,
+ $slug: String!,
+ $descriptionJson: JSONString!,
+ $chargeTaxes: Boolean!,
+ $taxCode: String!,
+ $attributes: [AttributeValueInput!]) {
+ productUpdate(
+ id: $productId,
+ input: {
+ category: $categoryId,
+ name: $name,
+ slug: $slug,
+ descriptionJson: $descriptionJson,
+ chargeTaxes: $chargeTaxes,
+ taxCode: $taxCode,
+ attributes: $attributes
+ }) {
+ product {
+ category {
name
}
- values {
+ descriptionJson
+ chargeTaxes
+ variants {
name
- slug
}
- }
- visibleInListings
- }
- errors {
- message
- field
- }
- }
- }
-"""
-
-
-@freeze_time("2020-03-18 12:00:00")
-@patch("saleor.plugins.manager.PluginsManager.product_updated")
-def test_update_product(
- updated_webhook_mock,
- staff_api_client,
- category,
- non_default_category,
- product,
- other_description_json,
- permission_manage_products,
- monkeypatch,
- color_attribute,
-):
- query = MUTATION_UPDATE_PRODUCT
- other_description_json = json.dumps(other_description_json)
-
- product_id = graphene.Node.to_global_id("Product", product.pk)
- category_id = graphene.Node.to_global_id("Category", non_default_category.pk)
- product_name = "updated name"
- product_slug = "updated-product"
- basePrice = 10.00
- product_is_published = True
- product_visible_in_listings = False
- product_charge_taxes = True
- product_tax_rate = "STANDARD"
-
- # Mock tax interface with fake response from tax gateway
- monkeypatch.setattr(
- PluginsManager,
- "get_tax_code_from_object_meta",
- lambda self, x: TaxType(description="", code=product_tax_rate),
- )
-
- attribute_id = graphene.Node.to_global_id("Attribute", color_attribute.pk)
-
- variables = {
- "productId": product_id,
- "categoryId": category_id,
- "name": product_name,
- "slug": product_slug,
- "descriptionJson": other_description_json,
- "isPublished": product_is_published,
- "visibleInListings": product_visible_in_listings,
- "chargeTaxes": product_charge_taxes,
- "taxCode": product_tax_rate,
- "basePrice": basePrice,
- "attributes": [{"id": attribute_id, "values": ["Rainbow"]}],
- }
-
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_products]
- )
- content = get_graphql_content(response)
- data = content["data"]["productUpdate"]
- assert data["errors"] == []
- assert data["product"]["name"] == product_name
- assert data["product"]["slug"] == product_slug
- assert data["product"]["descriptionJson"] == other_description_json
- assert data["product"]["isPublished"] == product_is_published
- assert data["product"]["visibleInListings"] == product_visible_in_listings
- assert data["product"]["chargeTaxes"] == product_charge_taxes
- assert data["product"]["variants"][0]["price"]["amount"] == basePrice
- assert data["product"]["taxType"]["taxCode"] == product_tax_rate
- assert not data["product"]["category"]["name"] == category.name
- assert data["product"]["publicationDate"] == "2020-03-18"
-
- attributes = data["product"]["attributes"]
-
- assert len(attributes) == 1
- assert len(attributes[0]["values"]) == 1
-
- assert attributes[0]["attribute"]["id"] == attribute_id
- assert attributes[0]["values"][0]["name"] == "Rainbow"
- assert attributes[0]["values"][0]["slug"] == "rainbow"
-
- updated_webhook_mock.assert_called_once_with(product)
+ taxType {
+ taxCode
+ description
+ }
+ name
+ slug
+ productType {
+ name
+ }
+ attributes {
+ attribute {
+ id
+ name
+ }
+ values {
+ name
+ slug
+ }
+ }
+ }
+ errors {
+ message
+ field
+ }
+ }
+ }
+"""
@freeze_time("2020-03-18 12:00:00")
@@ -2507,7 +2821,9 @@ def test_update_product_rating(
assert product.rating == expected_rating
-def test_update_product_when_default_currency_changeed(
+@patch("saleor.plugins.manager.PluginsManager.product_updated")
+def test_update_product(
+ updated_webhook_mock,
staff_api_client,
category,
non_default_category,
@@ -2516,26 +2832,15 @@ def test_update_product_when_default_currency_changeed(
permission_manage_products,
monkeypatch,
color_attribute,
- settings,
):
- # Ensure that when default currency has changed, there is no errors
- # when updating products with different currency which has different number
- # of required decimal places
-
- settings.DEFAULT_COUNTRY = "IS"
- settings.DEFAULT_CURRENCY = "ISK"
query = MUTATION_UPDATE_PRODUCT
-
other_description_json = json.dumps(other_description_json)
product_id = graphene.Node.to_global_id("Product", product.pk)
category_id = graphene.Node.to_global_id("Category", non_default_category.pk)
product_name = "updated name"
product_slug = "updated-product"
- product_is_published = True
- product_visible_in_listings = False
product_charge_taxes = True
- basePrice = 10.00
product_tax_rate = "STANDARD"
# Mock tax interface with fake response from tax gateway
@@ -2553,11 +2858,8 @@ def test_update_product_when_default_currency_changeed(
"name": product_name,
"slug": product_slug,
"descriptionJson": other_description_json,
- "isPublished": product_is_published,
- "visibleInListings": product_visible_in_listings,
"chargeTaxes": product_charge_taxes,
"taxCode": product_tax_rate,
- "basePrice": basePrice,
"attributes": [{"id": attribute_id, "values": ["Rainbow"]}],
}
@@ -2570,10 +2872,7 @@ def test_update_product_when_default_currency_changeed(
assert data["product"]["name"] == product_name
assert data["product"]["slug"] == product_slug
assert data["product"]["descriptionJson"] == other_description_json
- assert data["product"]["isPublished"] == product_is_published
- assert data["product"]["visibleInListings"] == product_visible_in_listings
assert data["product"]["chargeTaxes"] == product_charge_taxes
- assert data["product"]["variants"][0]["price"]["amount"] == basePrice
assert data["product"]["taxType"]["taxCode"] == product_tax_rate
assert not data["product"]["category"]["name"] == category.name
@@ -2586,6 +2885,8 @@ def test_update_product_when_default_currency_changeed(
assert attributes[0]["values"][0]["name"] == "Rainbow"
assert attributes[0]["values"][0]["slug"] == "rainbow"
+ updated_webhook_mock.assert_called_once_with(product)
+
UPDATE_PRODUCT_SLUG_MUTATION = """
mutation($id: ID!, $slug: String) {
@@ -2921,301 +3222,44 @@ def test_update_product_with_no_attribute_slug_or_id(
]
-def test_update_product_without_variants(
- staff_api_client, product_with_default_variant, permission_manage_products
-):
- query = """
- mutation updateProduct(
- $productId: ID!,
- $sku: String,
- $trackInventory: Boolean)
- {
- productUpdate(
- id: $productId,
- input: {
- sku: $sku,
- trackInventory: $trackInventory,
- })
- {
- product {
- id
- variants{
- id
- sku
- trackInventory
- }
- }
- errors {
- message
- field
- }
- }
- }
- """
-
- product = product_with_default_variant
- product_id = graphene.Node.to_global_id("Product", product.pk)
- product_sku = "test_sku"
- product_track_inventory = False
-
- variables = {
- "productId": product_id,
- "sku": product_sku,
- "trackInventory": product_track_inventory,
- }
-
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_products]
- )
- content = get_graphql_content(response)
- data = content["data"]["productUpdate"]
- assert data["errors"] == []
- product = data["product"]["variants"][0]
- assert product["sku"] == product_sku
- assert product["trackInventory"] == product_track_inventory
-
-
-def test_update_product_without_variants_sku_duplication(
- staff_api_client, product_with_default_variant, permission_manage_products, product
-):
- query = """
- mutation updateProduct(
- $productId: ID!,
- $sku: String)
- {
- productUpdate(
- id: $productId,
- input: {
- sku: $sku
- })
- {
- product {
- id
- }
- errors {
- message
- field
- }
- }
- }"""
- product = product_with_default_variant
- product_id = graphene.Node.to_global_id("Product", product.pk)
- product_sku = "123"
-
- variables = {"productId": product_id, "sku": product_sku}
-
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_products]
- )
- content = get_graphql_content(response)
- data = content["data"]["productUpdate"]
- assert data["errors"]
- assert data["errors"][0]["field"] == "sku"
- assert data["errors"][0]["message"] == "Product with this SKU already exists."
-
-
def test_update_product_with_negative_weight(
staff_api_client, product_with_default_variant, permission_manage_products, product
-):
- query = """
- mutation updateProduct(
- $productId: ID!,
- $weight: WeightScalar)
- {
- productUpdate(
- id: $productId,
- input: {
- weight: $weight
- })
- {
- product {
- id
- }
- productErrors {
- field
- message
- code
- }
- }
- }
- """
- product = product_with_default_variant
- product_id = graphene.Node.to_global_id("Product", product.pk)
-
- variables = {"productId": product_id, "weight": -1}
-
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_products]
- )
- content = get_graphql_content(response)
- data = content["data"]["productUpdate"]
- error = data["productErrors"][0]
- assert error["field"] == "weight"
- assert error["code"] == ProductErrorCode.INVALID.name
-
-
-def test_update_product_with_negative_base_price(
- staff_api_client, product_with_default_variant, permission_manage_products, product
-):
- query = """
- mutation updateProduct(
- $productId: ID!,
- $basePrice: PositiveDecimal)
- {
- productUpdate(
- id: $productId,
- input: {
- basePrice: $basePrice
- })
- {
- product {
- id
- }
- productErrors {
- field
- message
- code
- }
- }
- }
- """
- staff_api_client.user.user_permissions.add(permission_manage_products)
- product = product_with_default_variant
- product_id = graphene.Node.to_global_id("Product", product.pk)
-
- variables = {"productId": product_id, "basePrice": -1}
-
- response = staff_api_client.post_graphql(query, variables)
-
- assert_negative_positive_decimal_value(response)
-
-
-def test_update_product_with_too_many_decimal_places_in_price(
- staff_api_client, product_with_default_variant, permission_manage_products, product
-):
- # given
- query = """
- mutation updateProduct(
- $productId: ID!,
- $basePrice: PositiveDecimal)
- {
- productUpdate(
- id: $productId,
- input: {
- basePrice: $basePrice
- })
- {
- product {
- id
- }
- productErrors {
- field
- message
- code
- }
- }
- }
- """
- staff_api_client.user.user_permissions.add(permission_manage_products)
- product = product_with_default_variant
- product_id = graphene.Node.to_global_id("Product", product.pk)
-
- variables = {"productId": product_id, "basePrice": 1.1001}
-
- # when
- response = staff_api_client.post_graphql(query, variables)
-
- # then
- content = get_graphql_content(response)
- data = content["data"]["productUpdate"]
- error = data["productErrors"][0]
- assert error["field"] == "basePrice"
- assert error["code"] == ProductErrorCode.INVALID.name
-
-
-def test_update_product_with_too_many_decimal_places_in_price_different_currency(
- staff_api_client, product_with_default_variant, permission_manage_products, product
-):
- # given
- query = """
- mutation updateProduct(
- $productId: ID!,
- $basePrice: PositiveDecimal)
- {
- productUpdate(
- id: $productId,
- input: {
- basePrice: $basePrice
- })
- {
- product {
- id
- }
- productErrors {
- field
- message
- code
- }
- }
- }
- """
- product_with_default_variant.currency = "ISK"
- product_with_default_variant.save(update_fields=["currency"])
- staff_api_client.user.user_permissions.add(permission_manage_products)
- product = product_with_default_variant
- product_id = graphene.Node.to_global_id("Product", product.pk)
-
- variables = {"productId": product_id, "basePrice": 1.1}
-
- # when
- response = staff_api_client.post_graphql(query, variables)
-
- # then
- content = get_graphql_content(response)
- data = content["data"]["productUpdate"]
- error = data["productErrors"][0]
- assert error["field"] == "basePrice"
- assert error["code"] == ProductErrorCode.INVALID.name
-
-
-def test_update_product_without_category_and_true_is_published_value(
- staff_api_client, permission_manage_products, product
-):
- query = """
- mutation updateProduct(
- $productId: ID!,
- $isPublished: Boolean)
- {
- productUpdate(
- id: $productId,
- input: {
- isPublished: $isPublished
- })
+):
+ query = """
+ mutation updateProduct(
+ $productId: ID!,
+ $weight: WeightScalar)
{
- product {
- id
- }
- productErrors {
- code
- field
+ productUpdate(
+ id: $productId,
+ input: {
+ weight: $weight
+ })
+ {
+ product {
+ id
+ }
+ productErrors {
+ field
+ message
+ code
+ }
}
}
- }"""
-
- product.category = None
- product.save()
+ """
+ product = product_with_default_variant
+ product_id = graphene.Node.to_global_id("Product", product.pk)
- product_id = graphene.Node.to_global_id("Product", product.id)
- variables = {"productId": product_id, "isPublished": True}
+ variables = {"productId": product_id, "weight": -1}
response = staff_api_client.post_graphql(
query, variables, permissions=[permission_manage_products]
)
-
- data = get_graphql_content(response)["data"]["productUpdate"]
- assert data["productErrors"]
- assert data["productErrors"][0]["field"] == "category"
- assert data["productErrors"][0]["code"] == ProductErrorCode.REQUIRED.name
+ content = get_graphql_content(response)
+ data = content["data"]["productUpdate"]
+ error = data["productErrors"][0]
+ assert error["field"] == "weight"
+ assert error["code"] == ProductErrorCode.INVALID.name
UPDATE_PRODUCT = """
@@ -3316,7 +3360,11 @@ def test_delete_product(staff_api_client, product, permission_manage_products):
def test_delete_product_variant_in_draft_order(
- staff_api_client, product_with_two_variants, permission_manage_products, order_list
+ staff_api_client,
+ product_with_two_variants,
+ permission_manage_products,
+ order_list,
+ channel_USD,
):
query = DELETE_PRODUCT_MUTATION
product = product_with_two_variants
@@ -3329,7 +3377,7 @@ def test_delete_product_variant_in_draft_order(
draft_order_lines_pks = []
not_draft_order_lines_pks = []
for variant in product.variants.all():
- net = variant.get_price()
+ net = variant.get_price(channel_USD.slug)
gross = Money(amount=net.amount, currency=net.currency)
order_line = OrderLine.objects.create(
@@ -3373,16 +3421,16 @@ def test_delete_product_variant_in_draft_order(
assert OrderLine.objects.filter(pk__in=not_draft_order_lines_pks).exists()
-def test_product_type(user_api_client, product_type):
+def test_product_type(user_api_client, product_type, channel_USD):
query = """
- query {
+ query ($channel: String){
productTypes(first: 20) {
totalCount
edges {
node {
id
name
- products(first: 1) {
+ products(first: 1, channel: $channel) {
edges {
node {
id
@@ -3394,7 +3442,8 @@ def test_product_type(user_api_client, product_type):
}
}
"""
- response = user_api_client.post_graphql(query)
+ variables = {"channel": channel_USD.slug}
+ response = user_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
no_product_types = ProductType.objects.count()
assert content["data"]["productTypes"]["totalCount"] == no_product_types
@@ -3408,6 +3457,7 @@ def test_product_type_query(
product,
permission_manage_products,
monkeypatch,
+ channel_USD,
):
monkeypatch.setattr(
PluginsManager,
@@ -3415,10 +3465,10 @@ def test_product_type_query(
lambda self, x: TaxType(code="123", description="Standard Taxes"),
)
query = """
- query getProductType($id: ID!) {
+ query getProductType($id: ID!, $channel: String) {
productType(id: $id) {
name
- products(first: 20) {
+ products(first: 20, channel:$channel) {
totalCount
edges {
node {
@@ -3435,9 +3485,13 @@ def test_product_type_query(
}
"""
no_products = Product.objects.count()
- product.is_published = False
- product.save()
- variables = {"id": graphene.Node.to_global_id("ProductType", product_type.id)}
+ ProductChannelListing.objects.filter(product=product, channel=channel_USD).update(
+ is_published=False
+ )
+ variables = {
+ "id": graphene.Node.to_global_id("ProductType", product_type.id),
+ "channel": channel_USD.slug,
+ }
response = user_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
@@ -3913,6 +3967,7 @@ def test_product_type_delete_mutation_variants_in_draft_order(
permission_manage_product_types_and_attributes,
product,
order_list,
+ channel_USD,
):
query = PRODUCT_TYPE_DELETE_MUTATION
product_type = product.product_type
@@ -3924,7 +3979,7 @@ def test_product_type_delete_mutation_variants_in_draft_order(
draft_order.status = OrderStatus.DRAFT
draft_order.save(update_fields=["status"])
- net = variant.get_price()
+ net = variant.get_price(channel_USD.slug)
gross = Money(amount=net.amount, currency=net.currency)
order_line_not_in_draft = OrderLine.objects.create(
@@ -4372,21 +4427,66 @@ def test_product_update_variants_names(mock__update_variants_names, product_type
assert mock__update_variants_names.call_count == 1
+def test_product_variants_by_ids(user_api_client, variant, channel_USD):
+ query = """
+ query getProduct($ids: [ID!], $channel: String) {
+ productVariants(ids: $ids, first: 1, channel: $channel) {
+ edges {
+ node {
+ id
+ }
+ }
+ }
+ }
+ """
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+
+ variables = {"ids": [variant_id], "channel": channel_USD.slug}
+ response = user_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["productVariants"]
+ assert data["edges"][0]["node"]["id"] == variant_id
+ assert len(data["edges"]) == 1
+
+
+def test_product_variants_no_ids_list(user_api_client, variant, channel_USD):
+ query = """
+ query getProductVariants($channel: String) {
+ productVariants(first: 10, channel: $channel) {
+ edges {
+ node {
+ id
+ }
+ }
+ }
+ }
+ """
+ variables = {"channel": channel_USD.slug}
+ response = user_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["productVariants"]
+ assert len(data["edges"]) == ProductVariant.objects.count()
+
+
@pytest.mark.parametrize(
"variant_price_amount, api_variant_price", [(200, 200), (0, 0)],
)
def test_product_variant_price(
- variant_price_amount, api_variant_price, user_api_client, variant, stock
+ variant_price_amount,
+ api_variant_price,
+ user_api_client,
+ variant,
+ stock,
+ channel_USD,
):
- # Set price override on variant that is different than product price
product = variant.product
- product.variants.update(price_amount=variant_price_amount, currency="USD")
- # Drop other variants
- # product.variants.exclude(id=variant.pk).delete()
+ ProductVariantChannelListing.objects.filter(
+ channel=channel_USD, variant__product_id=product.pk
+ ).update(price_amount=variant_price_amount)
query = """
- query getProductVariants($id: ID!) {
- product(id: $id) {
+ query getProductVariants($id: ID!, $channel: String) {
+ product(id: $id, channel: $channel) {
variants {
pricing {
priceUndiscounted {
@@ -4400,7 +4500,7 @@ def test_product_variant_price(
}
"""
product_id = graphene.Node.to_global_id("Product", variant.product.id)
- variables = {"id": product_id}
+ variables = {"id": product_id, "channel": channel_USD.slug}
response = user_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["product"]
@@ -4408,84 +4508,130 @@ def test_product_variant_price(
assert variant_price["amount"] == api_variant_price
+QUERY_REPORT_PRODUCT_SALES = """
+query TopProducts($period: ReportingPeriod!, $channel: String!) {
+ reportProductSales(period: $period, first: 20, channel: $channel) {
+ edges {
+ node {
+ revenue(period: $period) {
+ gross {
+ amount
+ }
+ }
+ quantityOrdered
+ sku
+ }
+ }
+ }
+}
+"""
+
+
def test_report_product_sales(
staff_api_client,
order_with_lines,
+ order_with_lines_channel_PLN,
permission_manage_products,
permission_manage_orders,
+ channel_USD,
):
- query = """
- query TopProducts($period: ReportingPeriod!) {
- reportProductSales(period: $period, first: 20) {
- edges {
- node {
- revenue(period: $period) {
- gross {
- amount
- }
- }
- quantityOrdered
- sku
- }
- }
- }
- }
- """
- variables = {"period": ReportingPeriod.TODAY.name}
+ order = order_with_lines
+ variables = {"period": ReportingPeriod.TODAY.name, "channel": channel_USD.slug}
permissions = [permission_manage_orders, permission_manage_products]
- response = staff_api_client.post_graphql(query, variables, permissions)
+ response = staff_api_client.post_graphql(
+ QUERY_REPORT_PRODUCT_SALES, variables, permissions
+ )
+ content = get_graphql_content(response)
+ edges = content["data"]["reportProductSales"]["edges"]
+
+ node_a = edges[0]["node"]
+ line_a = order.lines.get(product_sku=node_a["sku"])
+ assert node_a["quantityOrdered"] == line_a.quantity
+ amount = str(node_a["revenue"]["gross"]["amount"])
+ assert Decimal(amount) == line_a.quantity * line_a.unit_price_gross_amount
+
+ node_b = edges[1]["node"]
+ line_b = order.lines.get(product_sku=node_b["sku"])
+ assert node_b["quantityOrdered"] == line_b.quantity
+ amount = str(node_b["revenue"]["gross"]["amount"])
+ assert Decimal(amount) == line_b.quantity * line_b.unit_price_gross_amount
+
+
+def test_report_product_sales_channel_pln(
+ staff_api_client,
+ order_with_lines,
+ order_with_lines_channel_PLN,
+ permission_manage_products,
+ permission_manage_orders,
+ channel_PLN,
+):
+ order = order_with_lines_channel_PLN
+ variables = {"period": ReportingPeriod.TODAY.name, "channel": channel_PLN.slug}
+ permissions = [permission_manage_orders, permission_manage_products]
+ response = staff_api_client.post_graphql(
+ QUERY_REPORT_PRODUCT_SALES, variables, permissions
+ )
content = get_graphql_content(response)
edges = content["data"]["reportProductSales"]["edges"]
node_a = edges[0]["node"]
- line_a = order_with_lines.lines.get(product_sku=node_a["sku"])
+ line_a = order.lines.get(product_sku=node_a["sku"])
assert node_a["quantityOrdered"] == line_a.quantity
amount = str(node_a["revenue"]["gross"]["amount"])
assert Decimal(amount) == line_a.quantity * line_a.unit_price_gross_amount
node_b = edges[1]["node"]
- line_b = order_with_lines.lines.get(product_sku=node_b["sku"])
+ line_b = order.lines.get(product_sku=node_b["sku"])
assert node_b["quantityOrdered"] == line_b.quantity
amount = str(node_b["revenue"]["gross"]["amount"])
assert Decimal(amount) == line_b.quantity * line_b.unit_price_gross_amount
[email protected]("field", ("purchaseCost", "margin"))
+def test_report_product_sales_not_existing_channel(
+ staff_api_client,
+ order_with_lines,
+ order_with_lines_channel_PLN,
+ permission_manage_products,
+ permission_manage_orders,
+):
+ variables = {"period": ReportingPeriod.TODAY.name, "channel": "not-existing"}
+ permissions = [permission_manage_orders, permission_manage_products]
+ response = staff_api_client.post_graphql(
+ QUERY_REPORT_PRODUCT_SALES, variables, permissions
+ )
+ content = get_graphql_content(response)
+ assert not content["data"]["reportProductSales"]["edges"]
+
+
def test_product_restricted_fields_permissions(
staff_api_client,
permission_manage_products,
permission_manage_orders,
product,
- field,
+ channel_USD,
):
"""Ensure non-public (restricted) fields are correctly requiring
the 'manage_products' permission.
"""
query = """
- query Product($id: ID!) {
- product(id: $id) {
- %(field)s
+ query Product($id: ID!, $channel: String) {
+ product(id: $id, channel: $channel) {
+ privateMetadata { __typename}
}
}
- """ % {
- "field": "%s { __typename }" % field
+ """
+ variables = {
+ "id": graphene.Node.to_global_id("Product", product.pk),
+ "channel": channel_USD.slug,
}
- variables = {"id": graphene.Node.to_global_id("Product", product.pk)}
permissions = [permission_manage_orders, permission_manage_products]
response = staff_api_client.post_graphql(query, variables, permissions)
content = get_graphql_content(response)
- assert field in content["data"]["product"]
+ assert "privateMetadata" in content["data"]["product"]
@pytest.mark.parametrize(
- "field, is_nested",
- (
- ("digitalContent", True),
- ("margin", False),
- ("costPrice", True),
- ("price", True),
- ("quantityOrdered", False),
- ),
+ "field, is_nested", (("digitalContent", True), ("quantityOrdered", False)),
)
def test_variant_restricted_fields_permissions(
staff_api_client,
@@ -4494,13 +4640,14 @@ def test_variant_restricted_fields_permissions(
product,
field,
is_nested,
+ channel_USD,
):
"""Ensure non-public (restricted) fields are correctly requiring
the 'manage_products' permission.
"""
query = """
- query ProductVariant($id: ID!) {
- productVariant(id: $id) {
+ query ProductVariant($id: ID!, $channel: String) {
+ productVariant(id: $id, channel: $channel) {
%(field)s
}
}
@@ -4508,7 +4655,10 @@ def test_variant_restricted_fields_permissions(
"field": field if not is_nested else "%s { __typename }" % field
}
variant = product.variants.first()
- variables = {"id": graphene.Node.to_global_id("ProductVariant", variant.pk)}
+ variables = {
+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),
+ "channel": channel_USD.slug,
+ }
permissions = [permission_manage_orders, permission_manage_products]
response = staff_api_client.post_graphql(query, variables, permissions)
content = get_graphql_content(response)
@@ -4516,11 +4666,11 @@ def test_variant_restricted_fields_permissions(
def test_variant_digital_content(
- staff_api_client, permission_manage_products, digital_content
+ staff_api_client, permission_manage_products, digital_content, channel_USD
):
query = """
- query Margin($id: ID!) {
- productVariant(id: $id) {
+ query Margin($id: ID!, $channel: String) {
+ productVariant(id: $id, channel: $channel) {
digitalContent{
id
}
@@ -4528,7 +4678,10 @@ def test_variant_digital_content(
}
"""
variant = digital_content.product_variant
- variables = {"id": graphene.Node.to_global_id("ProductVariant", variant.pk)}
+ variables = {
+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),
+ "channel": channel_USD.slug,
+ }
permissions = [permission_manage_products]
response = staff_api_client.post_graphql(query, variables, permissions)
content = get_graphql_content(response)
@@ -4550,36 +4703,45 @@ def test_collections_query_with_filter(
collection_filter,
count,
query_collections_with_filter,
+ channel_USD,
staff_api_client,
permission_manage_products,
):
- Collection.objects.bulk_create(
+ collections = Collection.objects.bulk_create(
[
Collection(
id=1,
name="Collection1",
slug="collection-published1",
- is_published=True,
description="Test description",
),
Collection(
id=2,
name="Collection2",
slug="collection-published2",
- is_published=True,
description="Test description",
),
Collection(
id=3,
name="Collection3",
slug="collection-unpublished",
- is_published=False,
description="Test description",
),
]
)
-
- variables = {"filter": collection_filter}
+ published = (True, True, False)
+ CollectionChannelListing.objects.bulk_create(
+ [
+ CollectionChannelListing(
+ channel=channel_USD, collection=collection, is_published=published[num]
+ )
+ for num, collection in enumerate(collections)
+ ]
+ )
+ collection_filter["channel"] = channel_USD.slug
+ variables = {
+ "filter": collection_filter,
+ }
staff_api_client.user.user_permissions.add(permission_manage_products)
response = staff_api_client.post_graphql(query_collections_with_filter, variables)
content = get_graphql_content(response)
@@ -4613,27 +4775,38 @@ QUERY_COLLECTIONS_WITH_SORT = """
],
)
def test_collections_query_with_sort(
- collection_sort, result_order, staff_api_client, permission_manage_products, product
+ collection_sort,
+ result_order,
+ staff_api_client,
+ permission_manage_products,
+ product,
+ channel_USD,
):
- Collection.objects.bulk_create(
+ collections = Collection.objects.bulk_create(
[
- Collection(name="Coll1", slug="collection-published1", is_published=True),
- Collection(
- name="Coll2", slug="collection-unpublished2", is_published=False
- ),
- Collection(name="Coll3", slug="collection-published", is_published=True),
+ Collection(name="Coll1", slug="collection-published1"),
+ Collection(name="Coll2", slug="collection-unpublished2"),
+ Collection(name="Coll3", slug="collection-published"),
+ ]
+ )
+ published = (True, False, True)
+ CollectionChannelListing.objects.bulk_create(
+ [
+ CollectionChannelListing(
+ channel=channel_USD, collection=collection, is_published=published[num]
+ )
+ for num, collection in enumerate(collections)
]
)
product.collections.add(Collection.objects.get(name="Coll2"))
-
+ collection_sort["channel"] = channel_USD.slug
variables = {"sort_by": collection_sort}
staff_api_client.user.user_permissions.add(permission_manage_products)
response = staff_api_client.post_graphql(QUERY_COLLECTIONS_WITH_SORT, variables)
content = get_graphql_content(response)
collections = content["data"]["collections"]["edges"]
-
- for order, colllection_name in enumerate(result_order):
- assert collections[order]["node"]["name"] == colllection_name
+ for order, collection_name in enumerate(result_order):
+ assert collections[order]["node"]["name"] == collection_name
@pytest.mark.parametrize(
@@ -4726,11 +4899,7 @@ def test_categories_query_with_sort(
name="Cat1", slug="slug_category1", description="Description cat1"
)
Product.objects.create(
- name="Test",
- slug="test",
- product_type=product_type,
- category=cat1,
- is_published=True,
+ name="Test", slug="test", product_type=product_type, category=cat1,
)
Category.objects.create(
name="Cat2", slug="slug_category2", description="Description cat2"
@@ -4748,11 +4917,7 @@ def test_categories_query_with_sort(
description="Subcategory_description of cat1",
)
Product.objects.create(
- name="Test2",
- slug="test2",
- product_type=product_type,
- category=subsubcat,
- is_published=True,
+ name="Test2", slug="test2", product_type=product_type, category=subsubcat,
)
variables = {"sort_by": category_sort}
staff_api_client.user.user_permissions.add(permission_manage_products)
@@ -4926,69 +5091,6 @@ def test_product_types_query_ids_not_exists(user_api_client, category):
assert content["data"]["productTypes"] is None
-MUTATION_BULK_PUBLISH_PRODUCTS = """
- mutation publishManyProducts($ids: [ID]!, $is_published: Boolean!) {
- productBulkPublish(ids: $ids, isPublished: $is_published) {
- count
- }
- }
- """
-
-
-def test_bulk_publish_products(
- staff_api_client, product_list_unpublished, permission_manage_products
-):
- product_list = product_list_unpublished
- assert not any(product.is_published for product in product_list)
-
- variables = {
- "ids": [
- graphene.Node.to_global_id("Product", product.id)
- for product in product_list
- ],
- "is_published": True,
- }
- response = staff_api_client.post_graphql(
- MUTATION_BULK_PUBLISH_PRODUCTS,
- variables,
- permissions=[permission_manage_products],
- )
- content = get_graphql_content(response)
- product_list = Product.objects.filter(
- id__in=[product.pk for product in product_list]
- )
-
- assert content["data"]["productBulkPublish"]["count"] == len(product_list)
- assert all(product.is_published for product in product_list)
-
-
-def test_bulk_unpublish_products(
- staff_api_client, product_list_published, permission_manage_products
-):
- product_list = product_list_published
- assert all(product.is_published for product in product_list)
-
- variables = {
- "ids": [
- graphene.Node.to_global_id("Product", product.id)
- for product in product_list
- ],
- "is_published": False,
- }
- response = staff_api_client.post_graphql(
- MUTATION_BULK_PUBLISH_PRODUCTS,
- variables,
- permissions=[permission_manage_products],
- )
- content = get_graphql_content(response)
- product_list = Product.objects.filter(
- id__in=[product.pk for product in product_list]
- )
-
- assert content["data"]["productBulkPublish"]["count"] == len(product_list)
- assert not any(product.is_published for product in product_list)
-
-
QUERY_AVAILABLE_ATTRIBUTES = """
query($productTypeId:ID!, $filters: AttributeFilterInput) {
productType(id: $productTypeId) {
@@ -5137,15 +5239,16 @@ def test_filter_product_types_by_custom_search_value(
def test_product_filter_by_attribute_values(
- staff_api_client,
+ user_api_client,
permission_manage_products,
color_attribute,
pink_attribute_value,
product_with_variant_with_two_attributes,
+ channel_USD,
):
query = """
- query Products($filters: ProductFilterInput) {
- products(first: 5, filter: $filters) {
+ query Products($filters: ProductFilterInput, $channel: String) {
+ products(first: 5, filter: $filters, channel: $channel) {
edges {
node {
id
@@ -5168,9 +5271,10 @@ def test_product_filter_by_attribute_values(
variables = {
"attributes": [
{"slug": color_attribute.slug, "values": [pink_attribute_value.slug]}
- ]
+ ],
+ "channel": channel_USD.slug,
}
- response = staff_api_client.post_graphql(query, variables)
+ response = user_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
assert not content["data"]["products"]["edges"] == [
{
@@ -5224,75 +5328,6 @@ mutation createProduct(
"""
-def test_create_product_without_variant_creates_stocks(
- staff_api_client,
- category,
- permission_manage_products,
- product_type_without_variant,
- warehouse,
-):
- category_id = graphene.Node.to_global_id("Category", category.pk)
- product_type_id = graphene.Node.to_global_id(
- "ProductType", product_type_without_variant.pk
- )
- stocks = [
- {
- "warehouse": graphene.Node.to_global_id("Warehouse", warehouse.pk),
- "quantity": 20,
- }
- ]
- variables = {
- "category": category_id,
- "productType": product_type_id,
- "name": "Test",
- "stocks": stocks,
- "sku": "23434",
- "trackInventory": True,
- "basePrice": Decimal("19"),
- }
- response = staff_api_client.post_graphql(
- MUTATION_CREATE_PRODUCT_WITH_STOCKS,
- variables,
- permissions=[permission_manage_products],
- )
- content = get_graphql_content(response)
- data = content["data"]["productCreate"]
- quantity = data["product"]["variants"][0]["stockQuantity"]
- assert quantity == 20
-
-
-def test_create_product_with_variants_does_not_create_stock(
- staff_api_client, category, product_type, permission_manage_products, warehouse
-):
- category_id = graphene.Node.to_global_id("Category", category.pk)
- product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
- stocks = [
- {
- "warehouse": graphene.Node.to_global_id("Warehouse", warehouse.pk),
- "quantity": 20,
- }
- ]
- variables = {
- "category": category_id,
- "productType": product_type_id,
- "name": "Test",
- "quantity": 8,
- "stocks": stocks,
- "sku": "23434",
- "trackInventory": True,
- "basePrice": Decimal("19"),
- }
- response = staff_api_client.post_graphql(
- MUTATION_CREATE_PRODUCT_WITH_STOCKS,
- variables,
- permissions=[permission_manage_products],
- )
- content = get_graphql_content(response)
- variants = content["data"]["productCreate"]["product"]["variants"]
- assert len(variants) == 0
- assert not Stock.objects.exists()
-
-
def test_create_stocks_failed(product_with_single_variant, warehouse):
variant = product_with_single_variant.variants.first()
@@ -5378,8 +5413,6 @@ mutation createProduct(
$productType: ID!,
$category: ID!
$name: String!,
- $sku: String,
- $basePrice: PositiveDecimal!,
$weight: WeightScalar)
{
productCreate(
@@ -5387,8 +5420,6 @@ mutation createProduct(
category: $category,
productType: $productType,
name: $name,
- sku: $sku,
- basePrice: $basePrice,
weight: $weight
})
{
@@ -5439,8 +5470,6 @@ def test_create_product_with_weight_variable(
"category": category_id,
"productType": product_type_id,
"name": "Test",
- "sku": "23434",
- "basePrice": Decimal("19"),
"weight": weight,
}
response = staff_api_client.post_graphql(
@@ -5482,17 +5511,13 @@ def test_create_product_with_weight_input(
mutation createProduct(
$productType: ID!,
$category: ID!,
- $name: String!,
- $sku: String,
- $basePrice: PositiveDecimal!)
+ $name: String!)
{{
productCreate(
input: {{
category: $category,
productType: $productType,
name: $name,
- sku: $sku,
- basePrice: $basePrice,
weight: {weight}
}})
{{
@@ -5519,8 +5544,6 @@ def test_create_product_with_weight_input(
"category": category_id,
"productType": product_type_id,
"name": "Test",
- "sku": "23434",
- "basePrice": Decimal("19"),
}
response = staff_api_client.post_graphql(
query, variables, permissions=[permission_manage_products],
diff --git a/saleor/graphql/product/tests/test_product_channel_listing_update.py b/saleor/graphql/product/tests/test_product_channel_listing_update.py
new file mode 100644
index 0000000000..61352ec298
--- /dev/null
+++ b/saleor/graphql/product/tests/test_product_channel_listing_update.py
@@ -0,0 +1,990 @@
+import datetime
+from unittest.mock import patch
+
+import graphene
+from freezegun import freeze_time
+
+from ....product.error_codes import ProductErrorCode
+from ....product.utils.costs import get_product_costs_data
+from ...tests.utils import assert_no_permission, get_graphql_content
+
+PRODUCT_CHANNEL_LISTING_UPDATE_MUTATION = """
+mutation UpdateProductChannelListing(
+ $id: ID!
+ $input: ProductChannelListingUpdateInput!
+) {
+ productChannelListingUpdate(id: $id, input: $input) {
+ productChannelListingErrors {
+ field
+ message
+ code
+ channels
+ }
+ product {
+ slug
+ channelListings {
+ isPublished
+ publicationDate
+ visibleInListings
+ channel {
+ slug
+ }
+ purchaseCost {
+ start {
+ amount
+ }
+ stop {
+ amount
+ }
+ }
+ margin {
+ start
+ stop
+ }
+ isAvailableForPurchase
+ availableForPurchase
+ }
+ }
+ }
+}
+"""
+
+
+def test_product_channel_listing_update_duplicated_ids_in_add_and_remove(
+ staff_api_client, product, permission_manage_products, channel_USD
+):
+ # given
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": product_id,
+ "input": {
+ "addChannels": [{"channelId": channel_id, "isPublished": True}],
+ "removeChannels": [channel_id],
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ errors = content["data"]["productChannelListingUpdate"][
+ "productChannelListingErrors"
+ ]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "input"
+ assert errors[0]["code"] == ProductErrorCode.DUPLICATED_INPUT_ITEM.name
+ assert errors[0]["channels"] == [channel_id]
+
+
+def test_product_channel_listing_update_duplicated_channel_in_add(
+ staff_api_client, product, permission_manage_products, channel_USD
+):
+ # given
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": product_id,
+ "input": {
+ "addChannels": [
+ {"channelId": channel_id, "isPublished": True},
+ {"channelId": channel_id, "isPublished": False},
+ ],
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ errors = content["data"]["productChannelListingUpdate"][
+ "productChannelListingErrors"
+ ]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "addChannels"
+ assert errors[0]["code"] == ProductErrorCode.DUPLICATED_INPUT_ITEM.name
+ assert errors[0]["channels"] == [channel_id]
+
+
+def test_product_channel_listing_update_duplicated_channel_in_remove(
+ staff_api_client, product, permission_manage_products, channel_USD
+):
+ # given
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": product_id,
+ "input": {"removeChannels": [channel_id, channel_id]},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ errors = content["data"]["productChannelListingUpdate"][
+ "productChannelListingErrors"
+ ]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "removeChannels"
+ assert errors[0]["code"] == ProductErrorCode.DUPLICATED_INPUT_ITEM.name
+ assert errors[0]["channels"] == [channel_id]
+
+
+def test_product_channel_listing_update_with_empty_input(
+ staff_api_client, product, permission_manage_products
+):
+ # given
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ variables = {
+ "id": product_id,
+ "input": {},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ errors = content["data"]["productChannelListingUpdate"][
+ "productChannelListingErrors"
+ ]
+ assert not errors
+
+
+def test_product_channel_listing_update_with_empty_lists_in_input(
+ staff_api_client, product, permission_manage_products
+):
+ # given
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ variables = {
+ "id": product_id,
+ "input": {"addChannels": [], "removeChannels": []},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ errors = content["data"]["productChannelListingUpdate"][
+ "productChannelListingErrors"
+ ]
+ assert not errors
+
+
+def test_product_channel_listing_update_as_staff_user(
+ staff_api_client, product, permission_manage_products, channel_USD, channel_PLN
+):
+ # given
+ publication_date = datetime.date.today()
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ available_for_purchase_date = datetime.date(2007, 1, 1)
+ variables = {
+ "id": product_id,
+ "input": {
+ "addChannels": [
+ {
+ "channelId": channel_id,
+ "isPublished": False,
+ "publicationDate": publication_date,
+ "visibleInListings": True,
+ "isAvailableForPurchase": True,
+ "availableForPurchaseDate": available_for_purchase_date,
+ }
+ ]
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["productChannelListingUpdate"]
+ product_data = data["product"]
+
+ variant = product.variants.first()
+ variant_channel_listing = variant.channel_listings.filter(channel_id=channel_USD.id)
+ purchase_cost, margin = get_product_costs_data(
+ variant_channel_listing, True, channel_USD.currency_code
+ )
+ assert not data["productChannelListingErrors"]
+ assert product_data["slug"] == product.slug
+ assert product_data["channelListings"][0]["isPublished"] is True
+ assert product_data["channelListings"][0]["publicationDate"] is None
+ assert product_data["channelListings"][0]["channel"]["slug"] == channel_USD.slug
+ assert product_data["channelListings"][0]["visibleInListings"] is True
+ assert product_data["channelListings"][0]["isAvailableForPurchase"] is True
+ assert (
+ product_data["channelListings"][0]["availableForPurchase"]
+ == datetime.date(1999, 1, 1).isoformat()
+ )
+ cost_start = product_data["channelListings"][0]["purchaseCost"]["start"]["amount"]
+ cost_stop = product_data["channelListings"][0]["purchaseCost"]["stop"]["amount"]
+
+ assert purchase_cost.start.amount == cost_start
+ assert purchase_cost.stop.amount == cost_stop
+ assert margin[0] == product_data["channelListings"][0]["margin"]["start"]
+ assert margin[1] == product_data["channelListings"][0]["margin"]["stop"]
+ assert product_data["channelListings"][1]["isPublished"] is False
+ assert (
+ product_data["channelListings"][1]["publicationDate"]
+ == publication_date.isoformat()
+ )
+ assert product_data["channelListings"][1]["visibleInListings"] is True
+ assert product_data["channelListings"][1]["channel"]["slug"] == channel_PLN.slug
+ assert product_data["channelListings"][1]["isAvailableForPurchase"] is True
+ assert (
+ product_data["channelListings"][1]["availableForPurchase"]
+ == available_for_purchase_date.isoformat()
+ )
+
+
+@patch("saleor.plugins.manager.PluginsManager.product_updated")
+def test_product_channel_listing_update_trigger_webhook_product_updated(
+ mock_product_updated,
+ staff_api_client,
+ product,
+ permission_manage_products,
+ channel_USD,
+ channel_PLN,
+):
+ # given
+ publication_date = datetime.date.today()
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ available_for_purchase_date = datetime.date(2007, 1, 1)
+ variables = {
+ "id": product_id,
+ "input": {
+ "addChannels": [
+ {
+ "channelId": channel_id,
+ "isPublished": False,
+ "publicationDate": publication_date,
+ "visibleInListings": True,
+ "isAvailableForPurchase": True,
+ "availableForPurchaseDate": available_for_purchase_date,
+ }
+ ]
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ get_graphql_content(response)
+
+ # then
+ mock_product_updated.assert_called_once_with(product)
+
+
+def test_product_channel_listing_update_as_app(
+ app_api_client, product, permission_manage_products, channel_USD, channel_PLN
+):
+ # given
+ publication_date = datetime.date.today()
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ available_for_purchase_date = datetime.date(2007, 1, 1)
+ variables = {
+ "id": product_id,
+ "input": {
+ "addChannels": [
+ {
+ "channelId": channel_id,
+ "isPublished": False,
+ "publicationDate": publication_date,
+ "visibleInListings": True,
+ "isAvailableForPurchase": True,
+ "availableForPurchaseDate": available_for_purchase_date,
+ }
+ ]
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ PRODUCT_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["productChannelListingUpdate"]
+ product_data = data["product"]
+ assert not data["productChannelListingErrors"]
+ assert product_data["slug"] == product.slug
+ assert product_data["channelListings"][0]["isPublished"] is True
+ assert product_data["channelListings"][0]["publicationDate"] is None
+ assert product_data["channelListings"][0]["channel"]["slug"] == channel_USD.slug
+ assert product_data["channelListings"][0]["visibleInListings"] is True
+ assert product_data["channelListings"][0]["isAvailableForPurchase"] is True
+ assert (
+ product_data["channelListings"][0]["availableForPurchase"]
+ == datetime.date(1999, 1, 1).isoformat()
+ )
+ assert product_data["channelListings"][1]["isPublished"] is False
+ assert (
+ product_data["channelListings"][1]["publicationDate"]
+ == publication_date.isoformat()
+ )
+ assert product_data["channelListings"][1]["visibleInListings"] is True
+ assert product_data["channelListings"][1]["channel"]["slug"] == channel_PLN.slug
+ assert product_data["channelListings"][1]["isAvailableForPurchase"] is True
+ assert (
+ product_data["channelListings"][1]["availableForPurchase"]
+ == available_for_purchase_date.isoformat()
+ )
+
+
+def test_product_channel_listing_update_as_customer(
+ user_api_client, product, channel_PLN
+):
+ # given
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ variables = {
+ "id": product_id,
+ "input": {"addChannels": [{"channelId": channel_id, "isPublished": False}]},
+ }
+
+ # when
+ response = user_api_client.post_graphql(
+ PRODUCT_CHANNEL_LISTING_UPDATE_MUTATION, variables=variables
+ )
+
+ # then
+ assert_no_permission(response)
+
+
+def test_product_channel_listing_update_as_anonymous(api_client, product, channel_PLN):
+ # given
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ variables = {
+ "id": product_id,
+ "input": {"addChannels": [{"channelId": channel_id, "isPublished": False}]},
+ }
+
+ # when
+ response = api_client.post_graphql(
+ PRODUCT_CHANNEL_LISTING_UPDATE_MUTATION, variables=variables
+ )
+
+ # then
+ assert_no_permission(response)
+
+
+def test_product_channel_listing_update_add_channel(
+ staff_api_client, product, permission_manage_products, channel_USD, channel_PLN
+):
+ # given
+ publication_date = datetime.date.today()
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ available_for_purchase_date = datetime.date(2007, 1, 1)
+ variables = {
+ "id": product_id,
+ "input": {
+ "addChannels": [
+ {
+ "channelId": channel_id,
+ "isPublished": False,
+ "publicationDate": publication_date,
+ "visibleInListings": True,
+ "isAvailableForPurchase": True,
+ "availableForPurchaseDate": available_for_purchase_date,
+ }
+ ]
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["productChannelListingUpdate"]
+ product_data = data["product"]
+ assert not data["productChannelListingErrors"]
+ assert product_data["slug"] == product.slug
+ assert product_data["channelListings"][0]["isPublished"] is True
+ assert product_data["channelListings"][0]["publicationDate"] is None
+ assert product_data["channelListings"][0]["channel"]["slug"] == channel_USD.slug
+ assert product_data["channelListings"][1]["isPublished"] is False
+ assert (
+ product_data["channelListings"][1]["publicationDate"]
+ == publication_date.isoformat()
+ )
+ assert product_data["channelListings"][1]["channel"]["slug"] == channel_PLN.slug
+ assert product_data["channelListings"][1]["visibleInListings"] is True
+ assert product_data["channelListings"][1]["isAvailableForPurchase"] is True
+ assert (
+ product_data["channelListings"][1]["availableForPurchase"]
+ == available_for_purchase_date.isoformat()
+ )
+
+
+@freeze_time("2020-03-18 12:00:00")
+def test_product_channel_listing_update_add_channel_without_publication_date(
+ staff_api_client, product, permission_manage_products, channel_USD, channel_PLN
+):
+ # given
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ variables = {
+ "id": product_id,
+ "input": {"addChannels": [{"channelId": channel_id, "isPublished": True}]},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["productChannelListingUpdate"]
+ product_data = data["product"]
+ assert not data["productChannelListingErrors"]
+ assert product_data["slug"] == product.slug
+ assert product_data["channelListings"][0]["isPublished"] is True
+ assert product_data["channelListings"][0]["publicationDate"] is None
+ assert product_data["channelListings"][0]["channel"]["slug"] == channel_USD.slug
+ assert product_data["channelListings"][1]["isPublished"] is True
+ assert (
+ product_data["channelListings"][1]["publicationDate"]
+ == datetime.date(2020, 3, 18).isoformat()
+ )
+ assert product_data["channelListings"][1]["channel"]["slug"] == channel_PLN.slug
+
+
+def test_product_channel_listing_update_unpublished(
+ staff_api_client, product, permission_manage_products, channel_USD
+):
+ # given
+ product.channel_listings.update(publication_date=datetime.date.today())
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": product_id,
+ "input": {"addChannels": [{"channelId": channel_id, "isPublished": False}]},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["productChannelListingUpdate"]
+ product_data = data["product"]
+ assert not data["productChannelListingErrors"]
+ assert product_data["slug"] == product.slug
+ assert product_data["channelListings"][0]["isPublished"] is False
+ assert (
+ product_data["channelListings"][0]["publicationDate"]
+ == datetime.date.today().isoformat()
+ )
+ assert product_data["channelListings"][0]["channel"]["slug"] == channel_USD.slug
+ assert product_data["channelListings"][0]["visibleInListings"] is True
+ assert product_data["channelListings"][0]["isAvailableForPurchase"] is True
+ assert (
+ product_data["channelListings"][0]["availableForPurchase"]
+ == datetime.date(1999, 1, 1).isoformat()
+ )
+
+
+@freeze_time("2020-03-18 12:00:00")
+def test_product_channel_listing_update_publish_without_publication_date(
+ staff_api_client, product, permission_manage_products, channel_USD
+):
+ # given
+ product.channel_listings.update(is_published=False)
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": product_id,
+ "input": {"addChannels": [{"channelId": channel_id, "isPublished": True}]},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["productChannelListingUpdate"]
+ product_data = data["product"]
+ assert not data["productChannelListingErrors"]
+ assert product_data["slug"] == product.slug
+ assert product_data["channelListings"][0]["isPublished"] is True
+ assert (
+ product_data["channelListings"][0]["publicationDate"]
+ == datetime.date(2020, 3, 18).isoformat()
+ )
+ assert product_data["channelListings"][0]["channel"]["slug"] == channel_USD.slug
+
+
+def test_product_channel_listing_update_remove_publication_date(
+ staff_api_client, product, permission_manage_products, channel_USD
+):
+ # given
+ product.channel_listings.update(publication_date=datetime.date.today())
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": product_id,
+ "input": {"addChannels": [{"channelId": channel_id, "publicationDate": None}]},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["productChannelListingUpdate"]
+ product_data = data["product"]
+ assert not data["productChannelListingErrors"]
+ assert product_data["slug"] == product.slug
+ assert product_data["channelListings"][0]["isPublished"] is True
+ assert product_data["channelListings"][0]["publicationDate"] is None
+ assert product_data["channelListings"][0]["channel"]["slug"] == channel_USD.slug
+ assert product_data["channelListings"][0]["visibleInListings"] is True
+ assert product_data["channelListings"][0]["isAvailableForPurchase"] is True
+ assert (
+ product_data["channelListings"][0]["availableForPurchase"]
+ == datetime.date(1999, 1, 1).isoformat()
+ )
+
+
+def test_product_channel_listing_update_visible_in_listings(
+ staff_api_client, product, permission_manage_products, channel_USD
+):
+ # given
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": product_id,
+ "input": {
+ "addChannels": [{"channelId": channel_id, "visibleInListings": False}]
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["productChannelListingUpdate"]
+ product_data = data["product"]
+ assert not data["productChannelListingErrors"]
+ assert product_data["slug"] == product.slug
+ assert product_data["channelListings"][0]["isPublished"] is True
+ assert product_data["channelListings"][0]["publicationDate"] is None
+ assert product_data["channelListings"][0]["channel"]["slug"] == channel_USD.slug
+ assert product_data["channelListings"][0]["visibleInListings"] is False
+ assert product_data["channelListings"][0]["isAvailableForPurchase"] is True
+ assert (
+ product_data["channelListings"][0]["availableForPurchase"]
+ == datetime.date(1999, 1, 1).isoformat()
+ )
+
+
+def test_product_channel_listing_update_update_publication_data(
+ staff_api_client, product, permission_manage_products, channel_USD
+):
+ # given
+ publication_date = datetime.date.today()
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": product_id,
+ "input": {
+ "addChannels": [
+ {
+ "channelId": channel_id,
+ "isPublished": False,
+ "publicationDate": publication_date,
+ }
+ ]
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["productChannelListingUpdate"]
+ product_data = data["product"]
+ assert not data["productChannelListingErrors"]
+ assert product_data["slug"] == product.slug
+ assert product_data["channelListings"][0]["isPublished"] is False
+ assert (
+ product_data["channelListings"][0]["publicationDate"]
+ == publication_date.isoformat()
+ )
+ assert product_data["channelListings"][0]["channel"]["slug"] == channel_USD.slug
+ assert product_data["channelListings"][0]["visibleInListings"] is True
+ assert product_data["channelListings"][0]["isAvailableForPurchase"] is True
+ assert (
+ product_data["channelListings"][0]["availableForPurchase"]
+ == datetime.date(1999, 1, 1).isoformat()
+ )
+
+
+def test_product_channel_listing_update_update_is_available_for_purchase_false(
+ staff_api_client, product, permission_manage_products, channel_USD
+):
+ # given
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": product_id,
+ "input": {
+ "addChannels": [{"channelId": channel_id, "isAvailableForPurchase": False}]
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["productChannelListingUpdate"]
+ product_data = data["product"]
+ assert not data["productChannelListingErrors"]
+ assert product_data["slug"] == product.slug
+ assert product_data["channelListings"][0]["isPublished"] is True
+ assert not product_data["channelListings"][0]["publicationDate"]
+ assert product_data["channelListings"][0]["channel"]["slug"] == channel_USD.slug
+ assert product_data["channelListings"][0]["visibleInListings"] is True
+ assert product_data["channelListings"][0]["isAvailableForPurchase"] is False
+ assert not product_data["channelListings"][0]["availableForPurchase"]
+
+
+def test_product_channel_listing_update_update_is_available_for_purchase_without_date(
+ staff_api_client, product, permission_manage_products, channel_USD
+):
+ # given
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": product_id,
+ "input": {
+ "addChannels": [{"channelId": channel_id, "isAvailableForPurchase": True}]
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["productChannelListingUpdate"]
+ product_data = data["product"]
+ assert not data["productChannelListingErrors"]
+ assert product_data["slug"] == product.slug
+ assert product_data["channelListings"][0]["isPublished"] is True
+ assert not product_data["channelListings"][0]["publicationDate"]
+ assert product_data["channelListings"][0]["channel"]["slug"] == channel_USD.slug
+ assert product_data["channelListings"][0]["visibleInListings"] is True
+ assert product_data["channelListings"][0]["isAvailableForPurchase"] is True
+ assert (
+ product_data["channelListings"][0]["availableForPurchase"]
+ == datetime.date.today().isoformat()
+ )
+
+
+def test_product_channel_listing_update_update_is_available_for_purchase_past_date(
+ staff_api_client, product, permission_manage_products, channel_USD
+):
+ # given
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ available_for_purchase_date = datetime.date(2007, 1, 1)
+ variables = {
+ "id": product_id,
+ "input": {
+ "addChannels": [
+ {
+ "channelId": channel_id,
+ "isAvailableForPurchase": True,
+ "availableForPurchaseDate": available_for_purchase_date,
+ }
+ ]
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["productChannelListingUpdate"]
+ product_data = data["product"]
+ assert not data["productChannelListingErrors"]
+ assert product_data["slug"] == product.slug
+ assert product_data["channelListings"][0]["isPublished"] is True
+ assert not product_data["channelListings"][0]["publicationDate"]
+ assert product_data["channelListings"][0]["channel"]["slug"] == channel_USD.slug
+ assert product_data["channelListings"][0]["visibleInListings"] is True
+ assert product_data["channelListings"][0]["isAvailableForPurchase"] is True
+ assert (
+ product_data["channelListings"][0]["availableForPurchase"]
+ == available_for_purchase_date.isoformat()
+ )
+
+
+def test_product_channel_listing_update_update_is_available_for_purchase_future_date(
+ staff_api_client, product, permission_manage_products, channel_USD
+):
+ # given
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ available_for_purchase_date = datetime.date.today() + datetime.timedelta(days=1)
+ variables = {
+ "id": product_id,
+ "input": {
+ "addChannels": [
+ {
+ "channelId": channel_id,
+ "isAvailableForPurchase": True,
+ "availableForPurchaseDate": available_for_purchase_date,
+ }
+ ]
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["productChannelListingUpdate"]
+ product_data = data["product"]
+ assert not data["productChannelListingErrors"]
+ assert product_data["slug"] == product.slug
+ assert product_data["channelListings"][0]["isPublished"] is True
+ assert not product_data["channelListings"][0]["publicationDate"]
+ assert product_data["channelListings"][0]["channel"]["slug"] == channel_USD.slug
+ assert product_data["channelListings"][0]["visibleInListings"] is True
+ assert product_data["channelListings"][0]["isAvailableForPurchase"] is False
+ assert (
+ product_data["channelListings"][0]["availableForPurchase"]
+ == available_for_purchase_date.isoformat()
+ )
+
+
+def test_product_channel_listing_update_update_is_available_for_purchase_false_and_date(
+ staff_api_client, product, permission_manage_products, channel_USD
+):
+ # given
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ available_for_purchase_date = datetime.date.today() + datetime.timedelta(days=1)
+ variables = {
+ "id": product_id,
+ "input": {
+ "addChannels": [
+ {
+ "channelId": channel_id,
+ "isAvailableForPurchase": False,
+ "availableForPurchaseDate": available_for_purchase_date,
+ }
+ ]
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["productChannelListingUpdate"]
+ errors = data["productChannelListingErrors"]
+ assert errors[0]["field"] == "availableForPurchaseDate"
+ assert errors[0]["code"] == ProductErrorCode.INVALID.name
+ assert errors[0]["channels"] == [channel_id]
+ assert len(errors) == 1
+
+
+def test_product_channel_listing_update_remove_channel(
+ staff_api_client,
+ product_available_in_many_channels,
+ permission_manage_products,
+ channel_USD,
+ channel_PLN,
+):
+ # given
+ product = product_available_in_many_channels
+ product_channel_listing_pln = product.channel_listings.get(channel=channel_PLN)
+ variant = product.variants.get()
+ variant_channel_listing_pln = variant.channel_listings.get(channel=channel_PLN)
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": product_id,
+ "input": {"removeChannels": [channel_id]},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["productChannelListingUpdate"]
+ product_data = data["product"]
+ assert not data["productChannelListingErrors"]
+ assert product_data["slug"] == product.slug
+ assert len(product_data["channelListings"]) == 1
+ assert product.channel_listings.get() == product_channel_listing_pln
+ assert variant.channel_listings.get() == variant_channel_listing_pln
+
+
+def test_product_channel_listing_update_remove_not_assigned_channel(
+ staff_api_client, product, permission_manage_products, channel_USD, channel_PLN
+):
+ # given
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ variables = {
+ "id": product_id,
+ "input": {"removeChannels": [channel_id]},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["productChannelListingUpdate"]
+ product_data = data["product"]
+ assert not data["productChannelListingErrors"]
+ assert product_data["slug"] == product.slug
+ assert product_data["channelListings"][0]["isPublished"] is True
+ assert product_data["channelListings"][0]["publicationDate"] is None
+ assert product_data["channelListings"][0]["channel"]["slug"] == channel_USD.slug
+
+
+def test_product_channel_listing_update_publish_product_without_category(
+ staff_api_client, product, permission_manage_products, channel_USD, channel_PLN
+):
+ # given
+ product.channel_listings.all().delete()
+ product.category = None
+ product.save()
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ channel_usd_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ channel_pln_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ variables = {
+ "id": product_id,
+ "input": {
+ "addChannels": [
+ {"channelId": channel_usd_id, "isPublished": True},
+ {"channelId": channel_pln_id, "isPublished": False},
+ ]
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["productChannelListingUpdate"]
+ errors = data["productChannelListingErrors"]
+ assert errors[0]["field"] == "isPublished"
+ assert errors[0]["code"] == ProductErrorCode.PRODUCT_WITHOUT_CATEGORY.name
+ assert errors[0]["channels"] == [channel_usd_id]
+ assert len(errors) == 1
diff --git a/saleor/graphql/product/tests/test_product_minimal_variant_price.py b/saleor/graphql/product/tests/test_product_discounted_price.py
similarity index 54%
rename from saleor/graphql/product/tests/test_product_minimal_variant_price.py
rename to saleor/graphql/product/tests/test_product_discounted_price.py
index 964387c792..751db4d850 100644
--- a/saleor/graphql/product/tests/test_product_minimal_variant_price.py
+++ b/saleor/graphql/product/tests/test_product_discounted_price.py
@@ -1,219 +1,15 @@
from unittest.mock import patch
-import graphene
from freezegun import freeze_time
from graphql_relay import from_global_id, to_global_id
from ...discount.enums import DiscountValueTypeEnum
-from ...tests.utils import assert_negative_positive_decimal_value, get_graphql_content
+from ...tests.utils import get_graphql_content
-@patch(
- "saleor.graphql.product.mutations.products"
- ".update_product_minimal_variant_price_task"
-)
-def test_product_variant_create_updates_minimal_variant_price(
- mock_update_product_minimal_variant_price_task,
- staff_api_client,
- product,
- permission_manage_products,
-):
- query = """
- mutation ProductVariantCreate(
- $productId: ID!,
- $sku: String!,
- $price: PositiveDecimal,
- $attributes: [AttributeValueInput]!,
- ) {
- productVariantCreate(
- input: {
- product: $productId,
- sku: $sku,
- price: $price,
- attributes: $attributes
- }
- ) {
- productVariant {
- name
- }
- productErrors {
- message
- field
- }
- }
- }
- """
- product_id = to_global_id("Product", product.pk)
- sku = "1"
- price = "1.99"
- variant_id = graphene.Node.to_global_id(
- "Attribute", product.product_type.variant_attributes.first().pk
- )
- variant_value = "test-value"
- variables = {
- "productId": product_id,
- "sku": sku,
- "price": price,
- "attributes": [{"id": variant_id, "values": [variant_value]}],
- }
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_products]
- )
- assert response.status_code == 200
-
- content = get_graphql_content(response)
- data = content["data"]["productVariantCreate"]
- assert data["productErrors"] == []
-
- mock_update_product_minimal_variant_price_task.delay.assert_called_once_with(
- product.pk
- )
-
-
-@patch(
- "saleor.graphql.product.mutations.products"
- ".update_product_minimal_variant_price_task"
-)
-def test_product_variant_update_updates_minimal_variant_price(
- mock_update_product_minimal_variant_price_task,
- staff_api_client,
- product,
- permission_manage_products,
-):
- query = """
- mutation ProductVariantUpdate(
- $id: ID!,
- $price: PositiveDecimal,
- ) {
- productVariantUpdate(
- id: $id,
- input: {
- price: $price,
- }
- ) {
- productVariant {
- name
- }
- errors {
- message
- field
- }
- }
- }
- """
- variant = product.variants.first()
- variant_id = to_global_id("ProductVariant", variant.pk)
- price = "1.99"
- variables = {
- "id": variant_id,
- "price": price,
- }
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_products]
- )
- assert response.status_code == 200
-
- content = get_graphql_content(response)
- data = content["data"]["productVariantUpdate"]
- assert data["errors"] == []
-
- mock_update_product_minimal_variant_price_task.delay.assert_called_once_with(
- product.pk
- )
-
-
-@patch(
- "saleor.graphql.product.mutations.products"
- ".update_product_minimal_variant_price_task"
-)
-def test_product_variant_update_updates_invalid_variant_price(
- mock_update_product_minimal_variant_price_task,
- staff_api_client,
- product,
- permission_manage_products,
-):
- query = """
- mutation ProductVariantUpdate(
- $id: ID!,
- $price: PositiveDecimal,
- ) {
- productVariantUpdate(
- id: $id,
- input: {
- price: $price,
- }
- ) {
- productVariant {
- name
- }
- productErrors {
- field
- message
- code
- }
- }
- }
- """
- staff_api_client.user.user_permissions.add(permission_manage_products)
- variant = product.variants.first()
- variant_id = to_global_id("ProductVariant", variant.pk)
- price = "-1.99"
- variables = {"id": variant_id, "price": price}
-
- response = staff_api_client.post_graphql(query, variables)
-
- assert_negative_positive_decimal_value(response)
-
-
-@patch(
- "saleor.graphql.product.mutations.products"
- ".update_product_minimal_variant_price_task"
-)
-def test_product_variant_update_updates_invalid_cost_price(
- mock_update_product_minimal_variant_price_task,
- staff_api_client,
- product,
- permission_manage_products,
-):
- query = """
- mutation ProductVariantUpdate(
- $id: ID!,
- $costPrice: PositiveDecimal,
- ) {
- productVariantUpdate(
- id: $id,
- input: {
- costPrice: $costPrice,
- }
- ) {
- productVariant {
- name
- }
- productErrors {
- field
- message
- code
- }
- }
- }
- """
- staff_api_client.user.user_permissions.add(permission_manage_products)
- variant = product.variants.first()
- variant_id = to_global_id("ProductVariant", variant.pk)
- cost_price = "-1.99"
- variables = {"id": variant_id, "costPrice": cost_price}
-
- response = staff_api_client.post_graphql(query, variables)
-
- assert_negative_positive_decimal_value(response)
-
-
-@patch(
- "saleor.graphql.product.mutations.products."
- "update_product_minimal_variant_price_task"
-)
-def test_product_variant_delete_updates_minimal_variant_price(
- mock_update_product_minimal_variant_price_task,
+@patch("saleor.graphql.product.mutations.products.update_product_discounted_price_task")
+def test_product_variant_delete_updates_discounted_price(
+ mock_update_product_discounted_price_task,
staff_api_client,
product,
permission_manage_products,
@@ -241,14 +37,12 @@ def test_product_variant_delete_updates_minimal_variant_price(
data = content["data"]["productVariantDelete"]
assert data["errors"] == []
- mock_update_product_minimal_variant_price_task.delay.assert_called_once_with(
- product.pk
- )
+ mock_update_product_discounted_price_task.delay.assert_called_once_with(product.pk)
-@patch("saleor.product.utils.update_products_minimal_variant_prices_task")
-def test_category_delete_updates_minimal_variant_price(
- mock_update_products_minimal_variant_prices_task,
+@patch("saleor.product.utils.update_products_discounted_prices_task")
+def test_category_delete_updates_discounted_price(
+ mock_update_products_discounted_prices_task,
staff_api_client,
categories_tree_with_published_products,
permission_manage_products,
@@ -279,11 +73,11 @@ def test_category_delete_updates_minimal_variant_price(
data = content["data"]["categoryDelete"]
assert data["errors"] == []
- mock_update_products_minimal_variant_prices_task.delay.assert_called_once()
+ mock_update_products_discounted_prices_task.delay.assert_called_once()
(
_call_args,
call_kwargs,
- ) = mock_update_products_minimal_variant_prices_task.delay.call_args
+ ) = mock_update_products_discounted_prices_task.delay.call_args
assert set(call_kwargs["product_ids"]) == set(p.pk for p in product_list)
for product in product_list:
@@ -293,10 +87,10 @@ def test_category_delete_updates_minimal_variant_price(
@patch(
"saleor.graphql.product.mutations.products"
- ".update_products_minimal_variant_prices_of_catalogues_task"
+ ".update_products_discounted_prices_of_catalogues_task"
)
-def test_collection_add_products_updates_minimal_variant_price(
- mock_update_minimal_variant_prices_task,
+def test_collection_add_products_updates_discounted_price(
+ mock_update_products_discounted_prices_of_catalogues,
staff_api_client,
sale,
collection,
@@ -330,17 +124,17 @@ def test_collection_add_products_updates_minimal_variant_price(
data = content["data"]["collectionAddProducts"]
assert data["errors"] == []
- mock_update_minimal_variant_prices_task.delay.assert_called_once_with(
+ mock_update_products_discounted_prices_of_catalogues.delay.assert_called_once_with(
product_ids=[p.pk for p in product_list]
)
@patch(
"saleor.graphql.product.mutations"
- ".products.update_products_minimal_variant_prices_of_catalogues_task"
+ ".products.update_products_discounted_prices_of_catalogues_task"
)
-def test_collection_remove_products_updates_minimal_variant_price(
- mock_update_minimal_variant_prices_task,
+def test_collection_remove_products_updates_discounted_price(
+ mock_update_products_discounted_prices_of_catalogues,
staff_api_client,
sale,
collection,
@@ -374,7 +168,7 @@ def test_collection_remove_products_updates_minimal_variant_price(
data = content["data"]["collectionRemoveProducts"]
assert data["errors"] == []
- mock_update_minimal_variant_prices_task.delay.assert_called_once_with(
+ mock_update_products_discounted_prices_of_catalogues.delay.assert_called_once_with(
product_ids=[p.pk for p in product_list]
)
@@ -382,10 +176,10 @@ def test_collection_remove_products_updates_minimal_variant_price(
@freeze_time("2010-05-31 12:00:01")
@patch(
"saleor.graphql.discount.mutations"
- ".update_products_minimal_variant_prices_of_discount_task"
+ ".update_products_discounted_prices_of_discount_task"
)
-def test_sale_create_updates_products_minimal_variant_prices(
- mock_update_minimal_variant_prices_task,
+def test_sale_create_updates_products_discounted_prices(
+ mock_update_products_discounted_prices_of_catalogues,
staff_api_client,
permission_manage_discounts,
):
@@ -428,15 +222,17 @@ def test_sale_create_updates_products_minimal_variant_prices(
relay_sale_id = content["data"]["saleCreate"]["sale"]["id"]
_sale_class_name, sale_id_str = from_global_id(relay_sale_id)
sale_id = int(sale_id_str)
- mock_update_minimal_variant_prices_task.delay.assert_called_once_with(sale_id)
+ mock_update_products_discounted_prices_of_catalogues.delay.assert_called_once_with(
+ sale_id
+ )
@patch(
"saleor.graphql.discount.mutations"
- ".update_products_minimal_variant_prices_of_discount_task"
+ ".update_products_discounted_prices_of_discount_task"
)
-def test_sale_update_updates_products_minimal_variant_prices(
- mock_update_minimal_variant_prices_task,
+def test_sale_update_updates_products_discounted_prices(
+ mock_update_products_discounted_prices_of_discount,
staff_api_client,
sale,
permission_manage_discounts,
@@ -463,15 +259,17 @@ def test_sale_update_updates_products_minimal_variant_prices(
content = get_graphql_content(response)
assert content["data"]["saleUpdate"]["errors"] == []
- mock_update_minimal_variant_prices_task.delay.assert_called_once_with(sale.pk)
+ mock_update_products_discounted_prices_of_discount.delay.assert_called_once_with(
+ sale.pk
+ )
@patch(
"saleor.graphql.discount.mutations"
- ".update_products_minimal_variant_prices_of_discount_task"
+ ".update_products_discounted_prices_of_discount_task"
)
-def test_sale_delete_updates_products_minimal_variant_prices(
- mock_update_minimal_variant_prices_task,
+def test_sale_delete_updates_products_discounted_prices(
+ mock_update_products_discounted_prices_of_discount,
staff_api_client,
sale,
permission_manage_discounts,
@@ -498,15 +296,17 @@ def test_sale_delete_updates_products_minimal_variant_prices(
content = get_graphql_content(response)
assert content["data"]["saleDelete"]["errors"] == []
- mock_update_minimal_variant_prices_task.delay.assert_called_once_with(sale.pk)
+ mock_update_products_discounted_prices_of_discount.delay.assert_called_once_with(
+ sale.pk
+ )
@patch(
"saleor.graphql.discount.mutations"
- ".update_products_minimal_variant_prices_of_catalogues_task"
+ ".update_products_discounted_prices_of_catalogues_task"
)
-def test_sale_add_catalogues_updates_products_minimal_variant_prices(
- mock_update_minimal_variant_prices_task,
+def test_sale_add_catalogues_updates_products_discounted_prices(
+ mock_update_products_discounted_prices_of_catalogues,
staff_api_client,
sale,
product,
@@ -517,7 +317,10 @@ def test_sale_add_catalogues_updates_products_minimal_variant_prices(
query = """
mutation SaleCataloguesAdd($id: ID!, $input: CatalogueInput!) {
saleCataloguesAdd(id: $id, input: $input) {
- errors {
+ sale {
+ name
+ }
+ discountErrors {
field
message
}
@@ -543,9 +346,9 @@ def test_sale_add_catalogues_updates_products_minimal_variant_prices(
assert response.status_code == 200
content = get_graphql_content(response)
- assert content["data"]["saleCataloguesAdd"]["errors"] == []
+ assert not content["data"]["saleCataloguesAdd"]["discountErrors"]
- mock_update_minimal_variant_prices_task.delay.assert_called_once_with(
+ mock_update_products_discounted_prices_of_catalogues.delay.assert_called_once_with(
product_ids=[product.pk],
category_ids=[category.pk],
collection_ids=[collection.pk],
@@ -554,10 +357,10 @@ def test_sale_add_catalogues_updates_products_minimal_variant_prices(
@patch(
"saleor.graphql.discount.mutations"
- ".update_products_minimal_variant_prices_of_catalogues_task"
+ ".update_products_discounted_prices_of_catalogues_task"
)
-def test_sale_remove_catalogues_updates_products_minimal_variant_prices(
- mock_update_minimal_variant_prices_task,
+def test_sale_remove_catalogues_updates_products_discounted_prices(
+ mock_update_products_discounted_prices_of_catalogues,
staff_api_client,
sale,
product,
@@ -571,7 +374,10 @@ def test_sale_remove_catalogues_updates_products_minimal_variant_prices(
query = """
mutation SaleCataloguesRemove($id: ID!, $input: CatalogueInput!) {
saleCataloguesRemove(id: $id, input: $input) {
- errors {
+ sale {
+ name
+ }
+ discountErrors {
field
message
}
@@ -597,9 +403,9 @@ def test_sale_remove_catalogues_updates_products_minimal_variant_prices(
assert response.status_code == 200
content = get_graphql_content(response)
- assert content["data"]["saleCataloguesRemove"]["errors"] == []
+ assert not content["data"]["saleCataloguesRemove"]["discountErrors"]
- mock_update_minimal_variant_prices_task.delay.assert_called_once_with( # noqa
+ mock_update_products_discounted_prices_of_catalogues.delay.assert_called_once_with(
product_ids=[product.pk],
category_ids=[category.pk],
collection_ids=[collection.pk],
diff --git a/saleor/graphql/product/tests/test_product_filtering_and_sorting_with_channels.py b/saleor/graphql/product/tests/test_product_filtering_and_sorting_with_channels.py
new file mode 100644
index 0000000000..88f5f1d4b2
--- /dev/null
+++ b/saleor/graphql/product/tests/test_product_filtering_and_sorting_with_channels.py
@@ -0,0 +1,579 @@
+import datetime
+import uuid
+from decimal import Decimal
+
+import pytest
+
+from ....product.models import (
+ Product,
+ ProductChannelListing,
+ ProductType,
+ ProductVariant,
+ ProductVariantChannelListing,
+)
+from ...channel.filters import LACK_OF_CHANNEL_IN_FILTERING_MSG
+from ...channel.sorters import LACK_OF_CHANNEL_IN_SORTING_MSG
+from ...tests.utils import assert_graphql_error_with_message, get_graphql_content
+
+
+def products_for_sorting_with_channels(category, channel_USD, channel_PLN):
+ product_type = ProductType.objects.create(name="Apple")
+ products = Product.objects.bulk_create(
+ [
+ Product(
+ name="Product1",
+ slug="prod1",
+ category=category,
+ product_type=product_type,
+ description="desc1",
+ ),
+ Product(
+ name="ProductProduct1",
+ slug="prod_prod1",
+ category=category,
+ product_type=product_type,
+ ),
+ Product(
+ name="ProductProduct2",
+ slug="prod_prod2",
+ category=category,
+ product_type=product_type,
+ ),
+ Product(
+ name="Product2",
+ slug="prod2",
+ category=category,
+ product_type=product_type,
+ description="desc2",
+ ),
+ Product(
+ name="Product3",
+ slug="prod3",
+ category=category,
+ product_type=product_type,
+ description="desc3",
+ ),
+ ]
+ )
+ ProductChannelListing.objects.bulk_create(
+ [
+ ProductChannelListing(
+ product=products[0],
+ channel=channel_USD,
+ is_published=True,
+ discounted_price_amount=Decimal(5),
+ publication_date=datetime.date(2002, 1, 1),
+ ),
+ ProductChannelListing(
+ product=products[1],
+ channel=channel_USD,
+ is_published=True,
+ discounted_price_amount=Decimal(15),
+ publication_date=datetime.date(2000, 1, 1),
+ ),
+ ProductChannelListing(
+ product=products[2],
+ channel=channel_USD,
+ is_published=False,
+ discounted_price_amount=Decimal(4),
+ publication_date=datetime.date(1999, 1, 1),
+ ),
+ ProductChannelListing(
+ product=products[3],
+ channel=channel_USD,
+ is_published=True,
+ discounted_price_amount=Decimal(7),
+ publication_date=datetime.date(2001, 1, 1),
+ ),
+ # Second channel
+ ProductChannelListing(
+ product=products[0],
+ channel=channel_PLN,
+ is_published=False,
+ discounted_price_amount=Decimal(15),
+ publication_date=datetime.date(2003, 1, 1),
+ ),
+ ProductChannelListing(
+ product=products[1],
+ channel=channel_PLN,
+ is_published=True,
+ discounted_price_amount=Decimal(4),
+ publication_date=datetime.date(1999, 1, 1),
+ ),
+ ProductChannelListing(
+ product=products[2],
+ channel=channel_PLN,
+ is_published=True,
+ discounted_price_amount=Decimal(5),
+ publication_date=datetime.date(2000, 1, 1),
+ ),
+ ProductChannelListing(
+ product=products[4],
+ channel=channel_PLN,
+ is_published=True,
+ discounted_price_amount=Decimal(7),
+ publication_date=datetime.date(1998, 1, 1),
+ ),
+ ]
+ )
+ variants = ProductVariant.objects.bulk_create(
+ [
+ ProductVariant(
+ product=products[0],
+ sku=str(uuid.uuid4()).replace("-", ""),
+ track_inventory=True,
+ ),
+ ProductVariant(
+ product=products[1],
+ sku=str(uuid.uuid4()).replace("-", ""),
+ track_inventory=True,
+ ),
+ ProductVariant(
+ product=products[2],
+ sku=str(uuid.uuid4()).replace("-", ""),
+ track_inventory=True,
+ ),
+ ProductVariant(
+ product=products[3],
+ sku=str(uuid.uuid4()).replace("-", ""),
+ track_inventory=True,
+ ),
+ ProductVariant(
+ product=products[4],
+ sku=str(uuid.uuid4()).replace("-", ""),
+ track_inventory=True,
+ ),
+ ]
+ )
+ ProductVariantChannelListing.objects.bulk_create(
+ [
+ ProductVariantChannelListing(
+ variant=variants[0],
+ channel=channel_USD,
+ price_amount=Decimal(10),
+ currency=channel_USD.currency_code,
+ ),
+ ProductVariantChannelListing(
+ variant=variants[1],
+ channel=channel_USD,
+ price_amount=Decimal(15),
+ currency=channel_USD.currency_code,
+ ),
+ ProductVariantChannelListing(
+ variant=variants[2],
+ channel=channel_USD,
+ price_amount=Decimal(8),
+ currency=channel_USD.currency_code,
+ ),
+ ProductVariantChannelListing(
+ variant=variants[3],
+ channel=channel_USD,
+ price_amount=Decimal(7),
+ currency=channel_USD.currency_code,
+ ),
+ # Second channel
+ ProductVariantChannelListing(
+ variant=variants[0],
+ channel=channel_PLN,
+ price_amount=Decimal(15),
+ currency=channel_PLN.currency_code,
+ ),
+ ProductVariantChannelListing(
+ variant=variants[1],
+ channel=channel_PLN,
+ price_amount=Decimal(8),
+ currency=channel_PLN.currency_code,
+ ),
+ ProductVariantChannelListing(
+ variant=variants[2],
+ channel=channel_PLN,
+ price_amount=Decimal(10),
+ currency=channel_PLN.currency_code,
+ ),
+ ProductVariantChannelListing(
+ variant=variants[4],
+ channel=channel_PLN,
+ price_amount=Decimal(7),
+ currency=channel_PLN.currency_code,
+ ),
+ ]
+ )
+ return products
+
+
+QUERY_PRODUCTS_WITH_SORTING_AND_FILTERING = """
+ query ($sortBy: ProductOrder, $filter: ProductFilterInput){
+ products (
+ first: 10, sortBy: $sortBy, filter: $filter
+ ) {
+ edges {
+ node {
+ name
+ slug
+ }
+ }
+ }
+ }
+"""
+
+
+ "sort_by",
+ [
+ {"field": "PUBLISHED", "direction": "ASC"},
+ {"field": "PRICE", "direction": "DESC"},
+ {"field": "MINIMAL_PRICE", "direction": "DESC"},
+ {"field": "PUBLICATION_DATE", "direction": "DESC"},
+ ],
+)
+def test_products_with_sorting_and_without_channel(
+ sort_by, staff_api_client, permission_manage_products,
+):
+ # given
+ variables = {"sortBy": sort_by}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_PRODUCTS_WITH_SORTING_AND_FILTERING,
+ variables,
+ permissions=[permission_manage_products],
+ check_no_permissions=False,
+ )
+
+ # then
+ assert_graphql_error_with_message(response, LACK_OF_CHANNEL_IN_SORTING_MSG)
+
+
+ "sort_by, products_order",
+ [
+ (
+ {"field": "PUBLISHED", "direction": "ASC"},
+ ["ProductProduct2", "Product1", "Product2", "ProductProduct1", "Product3"],
+ ),
+ (
+ {"field": "PUBLISHED", "direction": "DESC"},
+ ["Product3", "ProductProduct1", "Product2", "Product1", "ProductProduct2"],
+ ),
+ (
+ {"field": "PRICE", "direction": "ASC"},
+ ["Product2", "ProductProduct2", "Product1", "ProductProduct1", "Product3"],
+ ),
+ (
+ {"field": "PRICE", "direction": "DESC"},
+ ["Product3", "ProductProduct1", "Product1", "ProductProduct2", "Product2"],
+ ),
+ (
+ {"field": "MINIMAL_PRICE", "direction": "ASC"},
+ ["ProductProduct2", "Product1", "Product2", "ProductProduct1", "Product3"],
+ ),
+ (
+ {"field": "MINIMAL_PRICE", "direction": "DESC"},
+ ["Product3", "ProductProduct1", "Product2", "Product1", "ProductProduct2"],
+ ),
+ (
+ {"field": "PUBLICATION_DATE", "direction": "ASC"},
+ ["ProductProduct2", "ProductProduct1", "Product2", "Product1", "Product3"],
+ ),
+ (
+ {"field": "PUBLICATION_DATE", "direction": "DESC"},
+ ["Product3", "Product1", "Product2", "ProductProduct1", "ProductProduct2"],
+ ),
+ ],
+)
+def test_products_with_sorting_and_channel_USD(
+ sort_by,
+ products_order,
+ staff_api_client,
+ permission_manage_products,
+ products_for_sorting_with_channels,
+ channel_USD,
+):
+ # given
+ sort_by["channel"] = channel_USD.slug
+ variables = {"sortBy": sort_by}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_PRODUCTS_WITH_SORTING_AND_FILTERING,
+ variables,
+ permissions=[permission_manage_products],
+ check_no_permissions=False,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ products_nodes = content["data"]["products"]["edges"]
+ for index, product_name in enumerate(products_order):
+ assert product_name == products_nodes[index]["node"]["name"]
+
+
+ "sort_by, products_order",
+ [
+ (
+ {"field": "PUBLISHED", "direction": "ASC"},
+ ["Product1", "Product3", "ProductProduct1", "ProductProduct2", "Product2"],
+ ),
+ (
+ {"field": "PUBLISHED", "direction": "DESC"},
+ ["Product2", "ProductProduct2", "ProductProduct1", "Product3", "Product1"],
+ ),
+ (
+ {"field": "PRICE", "direction": "ASC"},
+ ["Product3", "ProductProduct1", "ProductProduct2", "Product1", "Product2"],
+ ),
+ (
+ {"field": "PRICE", "direction": "DESC"},
+ ["Product2", "Product1", "ProductProduct2", "ProductProduct1", "Product3"],
+ ),
+ (
+ {"field": "MINIMAL_PRICE", "direction": "ASC"},
+ ["ProductProduct1", "ProductProduct2", "Product3", "Product1", "Product2"],
+ ),
+ (
+ {"field": "MINIMAL_PRICE", "direction": "DESC"},
+ ["Product2", "Product1", "Product3", "ProductProduct2", "ProductProduct1"],
+ ),
+ ],
+)
+def test_products_with_sorting_and_channel_PLN(
+ sort_by,
+ products_order,
+ staff_api_client,
+ permission_manage_products,
+ products_for_sorting_with_channels,
+ channel_PLN,
+):
+ # given
+ sort_by["channel"] = channel_PLN.slug
+ variables = {"sortBy": sort_by}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_PRODUCTS_WITH_SORTING_AND_FILTERING,
+ variables,
+ permissions=[permission_manage_products],
+ check_no_permissions=False,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ products_nodes = content["data"]["products"]["edges"]
+ for index, product_name in enumerate(products_order):
+ assert product_name == products_nodes[index]["node"]["name"]
+
+
+ "sort_by",
+ [
+ {"field": "PUBLISHED", "direction": "ASC"},
+ {"field": "PRICE", "direction": "ASC"},
+ {"field": "MINIMAL_PRICE", "direction": "ASC"},
+ ],
+)
+def test_products_with_sorting_and_not_existing_channel_asc(
+ sort_by,
+ staff_api_client,
+ permission_manage_products,
+ products_for_sorting_with_channels,
+ channel_USD,
+):
+ # given
+ products_order = [
+ "Product1",
+ "Product2",
+ "Product3",
+ "ProductProduct1",
+ "ProductProduct2",
+ ]
+ sort_by["channel"] = "Not-existing"
+ variables = {"sortBy": sort_by}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_PRODUCTS_WITH_SORTING_AND_FILTERING,
+ variables,
+ permissions=[permission_manage_products],
+ check_no_permissions=False,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ products_nodes = content["data"]["products"]["edges"]
+ for index, product_name in enumerate(products_order):
+ assert product_name == products_nodes[index]["node"]["name"]
+
+
+ "sort_by",
+ [
+ {"field": "PUBLISHED", "direction": "DESC"},
+ {"field": "PRICE", "direction": "DESC"},
+ {"field": "MINIMAL_PRICE", "direction": "DESC"},
+ ],
+)
+def test_products_with_sorting_and_not_existing_channel_desc(
+ sort_by,
+ staff_api_client,
+ permission_manage_products,
+ products_for_sorting_with_channels,
+ channel_USD,
+):
+ products_order = [
+ "ProductProduct2",
+ "ProductProduct1",
+ "Product3",
+ "Product2",
+ "Product1",
+ ]
+ # given
+ sort_by["channel"] = "Not-existing"
+ variables = {"sortBy": sort_by}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_PRODUCTS_WITH_SORTING_AND_FILTERING,
+ variables,
+ permissions=[permission_manage_products],
+ check_no_permissions=False,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ products_nodes = content["data"]["products"]["edges"]
+ for index, product_name in enumerate(products_order):
+ assert product_name == products_nodes[index]["node"]["name"]
+
+
+ "filter_by",
+ [{"isPublished": True}, {"price": {"lte": 5}}, {"minimalPrice": {"lte": 5}}],
+)
+def test_products_with_filtering_without_channel(
+ filter_by, staff_api_client, permission_manage_products
+):
+ # given
+ variables = {"filter": filter_by}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_PRODUCTS_WITH_SORTING_AND_FILTERING,
+ variables,
+ permissions=[permission_manage_products],
+ check_no_permissions=False,
+ )
+
+ # then
+ assert_graphql_error_with_message(response, LACK_OF_CHANNEL_IN_FILTERING_MSG)
+
+
+ "filter_by, products_count",
+ [
+ ({"isPublished": True}, 3),
+ ({"isPublished": False}, 1),
+ ({"price": {"lte": 8}}, 2),
+ ({"price": {"gte": 11}}, 1),
+ ({"minimalPrice": {"lte": 4}}, 1),
+ ({"minimalPrice": {"gte": 5}}, 3),
+ ],
+)
+def test_products_with_filtering_with_channel_USD(
+ filter_by,
+ products_count,
+ staff_api_client,
+ permission_manage_products,
+ products_for_sorting_with_channels,
+ channel_USD,
+):
+ # given
+ filter_by["channel"] = channel_USD.slug
+ variables = {"filter": filter_by}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_PRODUCTS_WITH_SORTING_AND_FILTERING,
+ variables,
+ permissions=[permission_manage_products],
+ check_no_permissions=False,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ products_nodes = content["data"]["products"]["edges"]
+ assert len(products_nodes) == products_count
+
+
+ "filter_by, products_count",
+ [
+ ({"isPublished": True}, 3),
+ ({"isPublished": False}, 1),
+ ({"price": {"lte": 8}}, 2),
+ ({"price": {"gte": 11}}, 1),
+ ({"minimalPrice": {"lte": 4}}, 1),
+ ({"minimalPrice": {"gte": 5}}, 3),
+ ],
+)
+def test_products_with_filtering_with_channel_PLN(
+ filter_by,
+ products_count,
+ staff_api_client,
+ permission_manage_products,
+ products_for_sorting_with_channels,
+ channel_PLN,
+):
+ # given
+ filter_by["channel"] = channel_PLN.slug
+ variables = {"filter": filter_by}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_PRODUCTS_WITH_SORTING_AND_FILTERING,
+ variables,
+ permissions=[permission_manage_products],
+ check_no_permissions=False,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ products_nodes = content["data"]["products"]["edges"]
+ assert len(products_nodes) == products_count
+
+
+ "filter_by",
+ [
+ {"isPublished": True},
+ {"isPublished": False},
+ {"price": {"lte": 8}},
+ {"price": {"gte": 11}},
+ {"minimalPrice": {"lte": 4}},
+ {"minimalPrice": {"gte": 5}},
+ ],
+)
+def test_products_with_filtering_and_not_existing_channel(
+ filter_by,
+ staff_api_client,
+ permission_manage_products,
+ products_for_sorting_with_channels,
+ channel_USD,
+):
+ # given
+ filter_by["channel"] = "Not-existing"
+ variables = {"filter": filter_by}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_PRODUCTS_WITH_SORTING_AND_FILTERING,
+ variables,
+ permissions=[permission_manage_products],
+ check_no_permissions=False,
+ )
+
+ # then
+ content = get_graphql_content(response)
+ products_nodes = content["data"]["products"]["edges"]
+ assert len(products_nodes) == 0
diff --git a/saleor/graphql/product/tests/test_product_pagination.py b/saleor/graphql/product/tests/test_product_pagination.py
index b76c68d401..8b7e0bf678 100644
--- a/saleor/graphql/product/tests/test_product_pagination.py
+++ b/saleor/graphql/product/tests/test_product_pagination.py
@@ -7,9 +7,12 @@ import pytest
from ....product.models import (
Category,
Collection,
+ CollectionChannelListing,
Product,
+ ProductChannelListing,
ProductType,
ProductVariant,
+ ProductVariantChannelListing,
)
from ....product.utils.attributes import associate_attribute_values_to_instance
from ....warehouse.models import Stock
@@ -143,22 +146,27 @@ def test_categories_pagination_with_filtering(
@pytest.fixture
-def collections_for_pagination(product, product_with_single_variant):
+def collections_for_pagination(product, product_with_single_variant, channel_USD):
collections = Collection.objects.bulk_create(
[
- Collection(name="Collection1", slug="col1", is_published=True),
- Collection(
- name="CollectionCollection1", slug="col_col1", is_published=True
- ),
- Collection(
- name="CollectionCollection2", slug="col_col2", is_published=False
- ),
- Collection(name="Collection2", slug="col2", is_published=False),
- Collection(name="Collection3", slug="col3", is_published=True),
+ Collection(name="Collection1", slug="col1"),
+ Collection(name="CollectionCollection1", slug="col_col1"),
+ Collection(name="CollectionCollection2", slug="col_col2"),
+ Collection(name="Collection2", slug="col2"),
+ Collection(name="Collection3", slug="col3"),
]
)
collections[2].products.add(product)
collections[4].products.add(product_with_single_variant)
+ published = (True, True, False, False, True)
+ CollectionChannelListing.objects.bulk_create(
+ [
+ CollectionChannelListing(
+ channel=channel_USD, is_published=published[num], collection=collection
+ )
+ for num, collection in enumerate(collections)
+ ]
+ )
return collections
@@ -217,9 +225,10 @@ def test_collections_pagination_with_sorting(
staff_api_client,
permission_manage_products,
collections_for_pagination,
+ channel_USD,
):
page_size = 3
-
+ sort_by["channel"] = channel_USD.slug
variables = {"first": page_size, "after": None, "sortBy": sort_by}
response = staff_api_client.post_graphql(
QUERY_COLLECTIONS_PAGINATION,
@@ -253,9 +262,10 @@ def test_collections_pagination_with_filtering(
staff_api_client,
permission_manage_products,
collections_for_pagination,
+ channel_USD,
):
page_size = 2
-
+ filter_by["channel"] = channel_USD.slug
variables = {"first": page_size, "after": None, "filter": filter_by}
response = staff_api_client.post_graphql(
QUERY_COLLECTIONS_PAGINATION,
@@ -271,7 +281,9 @@ def test_collections_pagination_with_filtering(
@pytest.fixture
-def products_for_pagination(product_type, color_attribute, category, warehouse):
+def products_for_pagination(
+ product_type, color_attribute, category, warehouse, channel_USD
+):
product_type2 = ProductType.objects.create(name="Apple")
products = Product.objects.bulk_create(
[
@@ -280,7 +292,6 @@ def products_for_pagination(product_type, color_attribute, category, warehouse):
slug="prod1",
category=category,
product_type=product_type2,
- is_published=True,
description="desc1",
),
Product(
@@ -288,21 +299,18 @@ def products_for_pagination(product_type, color_attribute, category, warehouse):
slug="prod_prod1",
category=category,
product_type=product_type,
- is_published=False,
),
Product(
name="ProductProduct2",
slug="prod_prod2",
category=category,
product_type=product_type2,
- is_published=True,
),
Product(
name="Product2",
slug="prod2",
category=category,
product_type=product_type,
- is_published=False,
description="desc2",
),
Product(
@@ -310,11 +318,38 @@ def products_for_pagination(product_type, color_attribute, category, warehouse):
slug="prod3",
category=category,
product_type=product_type2,
- is_published=True,
description="desc3",
),
]
)
+ ProductChannelListing.objects.bulk_create(
+ [
+ ProductChannelListing(
+ product=products[0],
+ channel=channel_USD,
+ is_published=True,
+ discounted_price_amount=Decimal(5),
+ ),
+ ProductChannelListing(
+ product=products[1],
+ channel=channel_USD,
+ is_published=True,
+ discounted_price_amount=Decimal(15),
+ ),
+ ProductChannelListing(
+ product=products[2],
+ channel=channel_USD,
+ is_published=False,
+ discounted_price_amount=Decimal(4),
+ ),
+ ProductChannelListing(
+ product=products[3],
+ channel=channel_USD,
+ is_published=True,
+ discounted_price_amount=Decimal(7),
+ ),
+ ]
+ )
product_attrib_values = color_attribute.values.all()
associate_attribute_values_to_instance(
@@ -330,31 +365,54 @@ def products_for_pagination(product_type, color_attribute, category, warehouse):
product=products[0],
sku=str(uuid.uuid4()).replace("-", ""),
track_inventory=True,
- price_amount=Decimal(10),
),
ProductVariant(
product=products[1],
sku=str(uuid.uuid4()).replace("-", ""),
track_inventory=True,
- price_amount=Decimal(15),
),
ProductVariant(
product=products[2],
sku=str(uuid.uuid4()).replace("-", ""),
track_inventory=True,
- price_amount=Decimal(8),
),
ProductVariant(
product=products[3],
sku=str(uuid.uuid4()).replace("-", ""),
track_inventory=True,
- price_amount=Decimal(7),
),
ProductVariant(
product=products[4],
sku=str(uuid.uuid4()).replace("-", ""),
track_inventory=True,
+ ),
+ ]
+ )
+ ProductVariantChannelListing.objects.bulk_create(
+ [
+ ProductVariantChannelListing(
+ variant=variants[0],
+ channel=channel_USD,
+ price_amount=Decimal(10),
+ currency=channel_USD.currency_code,
+ ),
+ ProductVariantChannelListing(
+ variant=variants[1],
+ channel=channel_USD,
price_amount=Decimal(15),
+ currency=channel_USD.currency_code,
+ ),
+ ProductVariantChannelListing(
+ variant=variants[2],
+ channel=channel_USD,
+ price_amount=Decimal(8),
+ currency=channel_USD.currency_code,
+ ),
+ ProductVariantChannelListing(
+ variant=variants[3],
+ channel=channel_USD,
+ price_amount=Decimal(7),
+ currency=channel_USD.currency_code,
),
]
)
@@ -403,29 +461,64 @@ QUERY_PRODUCTS_PAGINATION = """
{"field": "NAME", "direction": "DESC"},
["ProductProduct2", "ProductProduct1", "Product3"],
),
- (
- {"field": "PRICE", "direction": "ASC"},
- ["Product2", "ProductProduct2", "Product1"],
- ),
(
{"field": "TYPE", "direction": "ASC"},
["Product1", "Product3", "ProductProduct2"],
),
+ ],
+)
+def test_products_pagination_with_sorting(
+ sort_by,
+ products_order,
+ staff_api_client,
+ permission_manage_products,
+ products_for_pagination,
+):
+ page_size = 3
+
+ variables = {"first": page_size, "after": None, "sortBy": sort_by}
+ response = staff_api_client.post_graphql(
+ QUERY_PRODUCTS_PAGINATION,
+ variables,
+ permissions=[permission_manage_products],
+ check_no_permissions=False,
+ )
+ content = get_graphql_content(response)
+ products_nodes = content["data"]["products"]["edges"]
+ assert products_order[0] == products_nodes[0]["node"]["name"]
+ assert products_order[1] == products_nodes[1]["node"]["name"]
+ assert products_order[2] == products_nodes[2]["node"]["name"]
+ assert len(products_nodes) == page_size
+
+
+ "sort_by, products_order",
+ [
(
{"field": "PUBLISHED", "direction": "ASC"},
- ["Product2", "ProductProduct1", "Product1"],
+ ["ProductProduct2", "Product1", "Product2"],
+ ),
+ (
+ {"field": "PRICE", "direction": "ASC"},
+ ["Product2", "ProductProduct2", "Product1"],
+ ),
+ (
+ {"field": "MINIMAL_PRICE", "direction": "ASC"},
+ ["ProductProduct2", "Product1", "Product2"],
),
],
)
-def test_products_pagination_with_sorting(
+def test_products_pagination_with_sorting_and_channel(
sort_by,
products_order,
staff_api_client,
permission_manage_products,
products_for_pagination,
+ channel_USD,
):
page_size = 3
+ sort_by["channel"] = channel_USD.slug
variables = {"first": page_size, "after": None, "sortBy": sort_by}
response = staff_api_client.post_graphql(
QUERY_PRODUCTS_PAGINATION,
@@ -446,6 +539,7 @@ def test_products_pagination_with_sorting_by_attribute(
permission_manage_products,
products_for_pagination,
color_attribute,
+ channel_USD,
):
page_size = 3
products_order = ["Product2", "ProductProduct1", "Product1"]
@@ -468,7 +562,7 @@ def test_products_pagination_with_sorting_by_attribute(
def test_products_pagination_for_products_with_the_same_names_two_pages(
- staff_api_client, permission_manage_products, category, product_type
+ staff_api_client, permission_manage_products, category, product_type, channel_USD
):
products = Product.objects.bulk_create(
[
@@ -477,21 +571,18 @@ def test_products_pagination_for_products_with_the_same_names_two_pages(
slug="prod-1",
category=category,
product_type=product_type,
- is_published=True,
),
Product(
name="Product",
slug="prod-2",
category=category,
product_type=product_type,
- is_published=True,
),
Product(
name="Product",
slug="prod-3",
category=category,
product_type=product_type,
- is_published=True,
),
]
)
@@ -533,7 +624,7 @@ def test_products_pagination_for_products_with_the_same_names_two_pages(
def test_products_pagination_for_products_with_the_same_names_one_page(
- staff_api_client, permission_manage_products, category, product_type
+ staff_api_client, permission_manage_products, category, product_type, channel_USD
):
products = Product.objects.bulk_create(
[
@@ -542,21 +633,18 @@ def test_products_pagination_for_products_with_the_same_names_one_page(
slug="prod-1",
category=category,
product_type=product_type,
- is_published=True,
),
Product(
name="Product",
slug="prod-2",
category=category,
product_type=product_type,
- is_published=True,
),
Product(
name="Product",
slug="prod-3",
category=category,
product_type=product_type,
- is_published=True,
),
]
)
@@ -584,8 +672,7 @@ def test_products_pagination_for_products_with_the_same_names_one_page(
@pytest.mark.parametrize(
"filter_by, products_order",
[
- ({"isPublished": False}, ["Product2", "ProductProduct1"]),
- ({"price": {"gte": 8, "lte": 12}}, ["Product1", "ProductProduct2"]),
+ ({"hasCategory": True}, ["Product1", "Product2"]),
({"stockAvailability": "OUT_OF_STOCK"}, ["ProductProduct1", "ProductProduct2"]),
],
)
@@ -612,8 +699,40 @@ def test_products_pagination_with_filtering(
assert len(products_nodes) == page_size
+ "filter_by, products_order",
+ [
+ ({"isPublished": True}, ["Product1", "Product2"]),
+ ({"price": {"gte": 8, "lte": 12}}, ["Product1", "ProductProduct2"]),
+ ],
+)
+def test_products_pagination_with_filtering_and_channel(
+ filter_by,
+ products_order,
+ staff_api_client,
+ permission_manage_products,
+ products_for_pagination,
+ channel_USD,
+):
+ page_size = 2
+
+ filter_by["channel"] = channel_USD.slug
+ variables = {"first": page_size, "after": None, "filter": filter_by}
+ response = staff_api_client.post_graphql(
+ QUERY_PRODUCTS_PAGINATION,
+ variables,
+ permissions=[permission_manage_products],
+ check_no_permissions=False,
+ )
+ content = get_graphql_content(response)
+ products_nodes = content["data"]["products"]["edges"]
+ assert products_order[0] == products_nodes[0]["node"]["name"]
+ assert products_order[1] == products_nodes[1]["node"]["name"]
+ assert len(products_nodes) == page_size
+
+
def test_products_pagination_with_filtering_by_attribute(
- staff_api_client, permission_manage_products, products_for_pagination,
+ staff_api_client, permission_manage_products, products_for_pagination, channel_USD
):
page_size = 2
products_order = ["Product2", "ProductProduct1"]
@@ -634,7 +753,11 @@ def test_products_pagination_with_filtering_by_attribute(
def test_products_pagination_with_filtering_by_product_types(
- staff_api_client, permission_manage_products, products_for_pagination, product_type
+ staff_api_client,
+ permission_manage_products,
+ products_for_pagination,
+ product_type,
+ channel_USD,
):
page_size = 2
products_order = ["Product2", "ProductProduct1"]
@@ -656,7 +779,11 @@ def test_products_pagination_with_filtering_by_product_types(
def test_products_pagination_with_filtering_by_stocks(
- staff_api_client, permission_manage_products, products_for_pagination, warehouse
+ staff_api_client,
+ permission_manage_products,
+ products_for_pagination,
+ warehouse,
+ channel_USD,
):
page_size = 2
products_order = ["ProductProduct1", "ProductProduct2"]
diff --git a/saleor/graphql/product/tests/test_product_set_availability_for_purchase.py b/saleor/graphql/product/tests/test_product_set_availability_for_purchase.py
deleted file mode 100644
index 9a374a36f7..0000000000
--- a/saleor/graphql/product/tests/test_product_set_availability_for_purchase.py
+++ /dev/null
@@ -1,209 +0,0 @@
-import datetime
-
-import graphene
-
-from ....product.error_codes import ProductErrorCode
-from ...tests.utils import assert_no_permission, get_graphql_content
-
-MUTATION_PRODUCT_SET_AVAILABILITY_FOR_PURCHASE = """
- mutation ProductSetAvailabilityForPurchase(
- $id: ID!, $is_available: Boolean!, $start_date: Date
- ) {
- productSetAvailabilityForPurchase(
- productId: $id, isAvailable: $is_available, startDate: $start_date
- ) {
- product {
- isAvailableForPurchase
- availableForPurchase
- }
- productErrors {
- code
- field
- }
- }
- }
-"""
-
-
-def test_product_set_availability_for_purchase_by_staff(
- staff_api_client, permission_manage_products, product
-):
- # given
- query = MUTATION_PRODUCT_SET_AVAILABILITY_FOR_PURCHASE
-
- staff_user = staff_api_client.user
- staff_user.user_permissions.add(permission_manage_products)
-
- start_date = datetime.date(1999, 1, 1)
-
- variables = {
- "id": graphene.Node.to_global_id("Product", product.pk),
- "is_available": True,
- "start_date": start_date,
- }
-
- # when
- response = staff_api_client.post_graphql(query, variables)
-
- # then
- content = get_graphql_content(response)
- data = content["data"]["productSetAvailabilityForPurchase"]
- product_data = data["product"]
-
- assert not data["productErrors"]
- assert product_data["isAvailableForPurchase"] is True
- assert product_data["availableForPurchase"] == start_date.strftime("%Y-%m-%d")
-
-
-def test_product_set_availability_for_purchase_by_staff_no_permissions(
- staff_api_client, product
-):
- # given
- query = MUTATION_PRODUCT_SET_AVAILABILITY_FOR_PURCHASE
-
- start_date = datetime.date(1999, 1, 1)
-
- variables = {
- "id": graphene.Node.to_global_id("Product", product.pk),
- "is_available": True,
- "start_date": start_date,
- }
-
- # when
- response = staff_api_client.post_graphql(query, variables)
-
- # then
- assert_no_permission(response)
-
-
-def test_product_set_availability_for_purchase_by_app(
- app_api_client, permission_manage_products, product
-):
- # given
- query = MUTATION_PRODUCT_SET_AVAILABILITY_FOR_PURCHASE
-
- app = app_api_client.app
- app.permissions.add(permission_manage_products)
-
- variables = {
- "id": graphene.Node.to_global_id("Product", product.pk),
- "is_available": True,
- }
-
- # when
- response = app_api_client.post_graphql(query, variables)
-
- # then
- content = get_graphql_content(response)
- data = content["data"]["productSetAvailabilityForPurchase"]
- product_data = data["product"]
-
- assert not data["productErrors"]
- assert product_data["isAvailableForPurchase"] is True
- assert product_data["availableForPurchase"] == datetime.date.today().strftime(
- "%Y-%m-%d"
- )
-
-
-def test_product_set_availability_for_purchase_by_app_no_permissions(
- app_api_client, product
-):
- # given
- query = MUTATION_PRODUCT_SET_AVAILABILITY_FOR_PURCHASE
-
- start_date = datetime.date(1999, 1, 1)
-
- variables = {
- "id": graphene.Node.to_global_id("Product", product.pk),
- "is_available": True,
- "start_date": start_date,
- }
-
- # when
- response = app_api_client.post_graphql(query, variables)
-
- # then
- assert_no_permission(response)
-
-
-def test_product_set_availability_for_purchase_by_customer(user_api_client, product):
- # given
- query = MUTATION_PRODUCT_SET_AVAILABILITY_FOR_PURCHASE
-
- start_date = datetime.date(1999, 1, 1)
-
- variables = {
- "id": graphene.Node.to_global_id("Product", product.pk),
- "is_available": True,
- "start_date": start_date,
- }
-
- # when
- response = user_api_client.post_graphql(query, variables)
-
- # then
- assert_no_permission(response)
-
-
-def test_product_set_availability_for_purchase_is_available_false_and_start_date_given(
- staff_api_client, permission_manage_products, product
-):
- # given
- query = MUTATION_PRODUCT_SET_AVAILABILITY_FOR_PURCHASE
-
- staff_user = staff_api_client.user
- staff_user.user_permissions.add(permission_manage_products)
-
- start_date = datetime.date(1999, 1, 1)
-
- variables = {
- "id": graphene.Node.to_global_id("Product", product.pk),
- "is_available": False,
- "start_date": start_date,
- }
-
- # when
- response = staff_api_client.post_graphql(query, variables)
-
- # then
- content = get_graphql_content(response)
- data = content["data"]["productSetAvailabilityForPurchase"]
- product_data = data["product"]
- errors = data["productErrors"]
-
- assert not product_data
- assert len(errors) == 1
- assert errors[0]["code"] == ProductErrorCode.INVALID.name
- assert errors[0]["field"] == "startDate"
-
-
-def test_product_set_availability_for_purchase_is_available_false(
- staff_api_client, permission_manage_products, product
-):
- # given
- query = MUTATION_PRODUCT_SET_AVAILABILITY_FOR_PURCHASE
-
- staff_user = staff_api_client.user
- staff_user.user_permissions.add(permission_manage_products)
-
- product.available_for_purchase = datetime.date(1999, 1, 1)
- product.save(update_fields=["available_for_purchase"])
-
- assert product.available_for_purchase
-
- variables = {
- "id": graphene.Node.to_global_id("Product", product.pk),
- "is_available": False,
- }
-
- # when
- response = staff_api_client.post_graphql(query, variables)
-
- # then
- content = get_graphql_content(response)
- data = content["data"]["productSetAvailabilityForPurchase"]
- product_data = data["product"]
-
- assert not data["productErrors"]
- assert product_data["isAvailableForPurchase"] is False
- assert product_data["availableForPurchase"] is None
diff --git a/saleor/graphql/product/tests/test_product_sorting.py b/saleor/graphql/product/tests/test_product_sorting.py
index 5b43202256..ea1d6550ee 100644
--- a/saleor/graphql/product/tests/test_product_sorting.py
+++ b/saleor/graphql/product/tests/test_product_sorting.py
@@ -5,7 +5,7 @@ import graphene
import pytest
from freezegun import freeze_time
-from ....product.models import Product
+from ....product.models import Product, ProductChannelListing
from ...tests.utils import get_graphql_content
COLLECTION_RESORT_QUERY = """
@@ -82,13 +82,14 @@ def test_sort_products_within_collection_invalid_product_id(
def test_sort_products_within_collection(
staff_api_client,
staff_user,
- collection,
+ published_collection,
collection_with_products,
permission_manage_products,
+ channel_USD,
):
staff_api_client.user.user_permissions.add(permission_manage_products)
- collection_id = graphene.Node.to_global_id("Collection", collection.pk)
+ collection_id = graphene.Node.to_global_id("Collection", published_collection.pk)
products = collection_with_products
product = graphene.Node.to_global_id("Product", products[0].pk)
@@ -127,12 +128,11 @@ def test_sort_products_within_collection(
GET_SORTED_PRODUCTS_QUERY = """
-query Products($sortBy: ProductOrder) {
- products(first: 10, sortBy: $sortBy) {
+query Products($sortBy: ProductOrder, $channel: String) {
+ products(first: 10, sortBy: $sortBy, channel: $channel) {
edges {
node {
id
- publicationDate
}
}
}
@@ -146,27 +146,40 @@ query Products($sortBy: ProductOrder) {
(("ASC", "publication_date"), ("DESC", "-publication_date")),
)
def test_sort_products_by_publication_date(
- direction, order_direction, staff_api_client, product_list
+ direction, order_direction, api_client, product_list, channel_USD
):
-
+ product_channel_listings = []
for iter_value, product in enumerate(product_list):
- product.publication_date = date.today() - timedelta(days=iter_value)
- Product.objects.bulk_update(product_list, ["publication_date"])
+ product_channel_listing = product.channel_listings.get(channel=channel_USD)
+ product_channel_listing.publication_date = date.today() - timedelta(
+ days=iter_value
+ )
+ product_channel_listings.append(product_channel_listing)
+ ProductChannelListing.objects.bulk_update(
+ product_channel_listings, ["publication_date"]
+ )
variables = {
- "sortBy": {"direction": direction, "field": "PUBLICATION_DATE"},
+ "sortBy": {
+ "direction": direction,
+ "field": "PUBLICATION_DATE",
+ "channel": channel_USD.slug,
+ },
+ "channel": channel_USD.slug,
}
# when
- response = staff_api_client.post_graphql(GET_SORTED_PRODUCTS_QUERY, variables)
+ response = api_client.post_graphql(GET_SORTED_PRODUCTS_QUERY, variables)
# then
content = get_graphql_content(response)
data = content["data"]["products"]["edges"]
+ if direction == "ASC":
+ product_list.reverse()
+
assert [node["node"]["id"] for node in data] == [
- graphene.Node.to_global_id("Product", product.pk)
- for product in Product.objects.order_by(order_direction)
+ graphene.Node.to_global_id("Product", product.pk) for product in product_list
]
@@ -174,7 +187,7 @@ def test_sort_products_by_publication_date(
"direction, order_direction", (("ASC", "rating"), ("DESC", "-rating")),
)
def test_sort_products_by_rating(
- direction, order_direction, staff_api_client, product_list
+ direction, order_direction, api_client, product_list, channel_USD
):
for product in product_list:
@@ -183,10 +196,11 @@ def test_sort_products_by_rating(
variables = {
"sortBy": {"direction": direction, "field": "RATING"},
+ "channel": channel_USD.slug,
}
# when
- response = staff_api_client.post_graphql(GET_SORTED_PRODUCTS_QUERY, variables)
+ response = api_client.post_graphql(GET_SORTED_PRODUCTS_QUERY, variables)
# then
content = get_graphql_content(response)
diff --git a/saleor/graphql/product/tests/test_product_sorting_attributes.py b/saleor/graphql/product/tests/test_product_sorting_attributes.py
index 61ce16b858..507b6f8315 100644
--- a/saleor/graphql/product/tests/test_product_sorting_attributes.py
+++ b/saleor/graphql/product/tests/test_product_sorting_attributes.py
@@ -15,9 +15,11 @@ query products(
$field: ProductOrderField
$attributeId: ID
$direction: OrderDirection!
+ $channel: String
) {
products(
- first: 100
+ first: 100,
+ channel: $channel,
sortBy: { field: $field, attributeId: $attributeId, direction: $direction }
) {
edges {
@@ -43,7 +45,7 @@ DUMMIES = ("Oopsie",)
@pytest.fixture
-def products_structures(category):
+def products_structures(category, channel_USD):
def attr_value(attribute, *values):
return [attribute.values.get_or_create(name=v, slug=v)[0] for v in values]
@@ -99,16 +101,27 @@ def products_structures(category):
slug=f"{attrs[0]}-apple-{attrs[1]}-({i})",
product_type=pt_apples,
category=category,
- is_published=True,
- visible_in_listings=True,
)
for i, attrs in enumerate(zip(COLORS, TRADEMARKS))
]
)
)
for product_apple in apples:
- product_models.ProductVariant.objects.create(
- product=product_apple, sku=product_apple.slug, price_amount=Decimal(10)
+ product_models.ProductChannelListing.objects.create(
+ product=product_apple,
+ channel=channel_USD,
+ is_published=True,
+ visible_in_listings=True,
+ )
+ variant = product_models.ProductVariant.objects.create(
+ product=product_apple, sku=product_apple.slug
+ )
+ product_models.ProductVariantChannelListing.objects.create(
+ variant=variant,
+ channel=channel_USD,
+ price_amount=Decimal(10),
+ cost_price_amount=Decimal(1),
+ currency=channel_USD.currency_code,
)
oranges = list(
product_models.Product.objects.bulk_create(
@@ -118,38 +131,68 @@ def products_structures(category):
slug=f"{attrs[0]}-orange-{attrs[1]}-({i})",
product_type=pt_oranges,
category=category,
- is_published=True,
- visible_in_listings=True,
)
for i, attrs in enumerate(zip(COLORS, TRADEMARKS))
]
)
)
for product_orange in oranges:
- product_models.ProductVariant.objects.create(
- product=product_orange, sku=product_orange.slug, price_amount=Decimal(10)
+ product_models.ProductChannelListing.objects.create(
+ product=product_orange,
+ channel=channel_USD,
+ is_published=True,
+ visible_in_listings=True,
+ )
+ variant = product_models.ProductVariant.objects.create(
+ product=product_orange, sku=product_orange.slug
+ )
+ product_models.ProductVariantChannelListing.objects.create(
+ variant=variant,
+ channel=channel_USD,
+ cost_price_amount=Decimal(1),
+ price_amount=Decimal(10),
+ currency=channel_USD.currency_code,
)
dummy = product_models.Product.objects.create(
name="Oopsie Dummy",
slug="oopsie-dummy",
product_type=pt_other,
category=category,
- is_published=True,
- visible_in_listings=True,
)
- product_models.ProductVariant.objects.create(
- product=dummy, sku=dummy.slug, price_amount=Decimal(10)
+ product_models.ProductChannelListing.objects.create(
+ product=dummy, channel=channel_USD, is_published=True, visible_in_listings=True,
+ )
+ variant = product_models.ProductVariant.objects.create(
+ product=dummy, sku=dummy.slug
+ )
+ product_models.ProductVariantChannelListing.objects.create(
+ variant=variant,
+ channel=channel_USD,
+ cost_price_amount=Decimal(1),
+ price_amount=Decimal(10),
+ currency=channel_USD.currency_code,
)
other_dummy = product_models.Product.objects.create(
name="Another Dummy but first in ASC and has no attribute value",
slug="another-dummy",
product_type=pt_other,
category=category,
+ )
+ product_models.ProductChannelListing.objects.create(
+ product=other_dummy,
+ channel=channel_USD,
is_published=True,
visible_in_listings=True,
)
- product_models.ProductVariant.objects.create(
- product=other_dummy, sku=other_dummy.slug, price_amount=Decimal(10)
+ variant = product_models.ProductVariant.objects.create(
+ product=other_dummy, sku=other_dummy.slug
+ )
+ product_models.ProductVariantChannelListing.objects.create(
+ variant=variant,
+ channel=channel_USD,
+ cost_price_amount=Decimal(1),
+ price_amount=Decimal(10),
+ currency=channel_USD.currency_code,
)
dummy_attr_value = attr_value(dummy_attr, DUMMIES[0])
associate_attribute_values_to_instance(dummy, dummy_attr, *dummy_attr_value)
@@ -168,12 +211,19 @@ def products_structures(category):
return colors_attr, trademark_attr, dummy_attr
-def test_sort_products_cannot_sort_both_by_field_and_by_attribute(api_client):
+def test_sort_products_cannot_sort_both_by_field_and_by_attribute(
+ api_client, channel_USD
+):
"""Ensure one cannot both sort by a supplied field and sort by a given attribute ID
at the same time.
"""
query = QUERY_SORT_PRODUCTS_BY_ATTRIBUTE
- variables = {"field": "NAME", "attributeId": "SomeAttributeId", "direction": "ASC"}
+ variables = {
+ "field": "NAME",
+ "attributeId": "SomeAttributeId",
+ "direction": "ASC",
+ "channel": channel_USD.slug,
+ }
response = api_client.post_graphql(query, variables)
response = get_graphql_content(response, ignore_errors=True)
@@ -435,14 +485,18 @@ EXPECTED_SORTED_DATA_MULTIPLE_VALUES_ASC = [
@pytest.mark.parametrize("ascending", [True, False])
def test_sort_product_by_attribute_single_value(
- api_client, products_structures, ascending
+ api_client, products_structures, ascending, channel_USD
):
_, attribute, _ = products_structures
attribute_id: str = graphene.Node.to_global_id("Attribute", attribute.pk)
direction = "ASC" if ascending else "DESC"
query = QUERY_SORT_PRODUCTS_BY_ATTRIBUTE
- variables = {"attributeId": attribute_id, "direction": direction}
+ variables = {
+ "attributeId": attribute_id,
+ "direction": direction,
+ "channel": channel_USD.slug,
+ }
response = get_graphql_content(api_client.post_graphql(query, variables))
products = response["data"]["products"]["edges"]
@@ -457,14 +511,18 @@ def test_sort_product_by_attribute_single_value(
@pytest.mark.parametrize("ascending", [True, False])
def test_sort_product_by_attribute_multiple_values(
- api_client, products_structures, ascending
+ api_client, products_structures, ascending, channel_USD
):
attribute, _, _ = products_structures
attribute_id: str = graphene.Node.to_global_id("Attribute", attribute.pk)
direction = "ASC" if ascending else "DESC"
query = QUERY_SORT_PRODUCTS_BY_ATTRIBUTE
- variables = {"attributeId": attribute_id, "direction": direction}
+ variables = {
+ "attributeId": attribute_id,
+ "direction": direction,
+ "channel": channel_USD.slug,
+ }
response = get_graphql_content(api_client.post_graphql(query, variables))
products = response["data"]["products"]["edges"]
@@ -483,10 +541,7 @@ def test_sort_product_not_having_attribute_data(api_client, category, count_quer
after the product creation.
"""
expected_results = ["Z", "Y", "A"]
- product_create_kwargs = {
- "category": category,
- "is_published": True,
- }
+ product_create_kwargs = {"category": category}
# Create two product types, with one forced to be at the bottom (no such attribute)
product_type = product_models.ProductType.objects.create(
@@ -538,7 +593,7 @@ def test_sort_product_not_having_attribute_data(api_client, category, count_quer
],
)
def test_sort_product_by_attribute_using_invalid_attribute_id(
- api_client, product_list_published, attribute_id
+ api_client, product_list_published, attribute_id, channel_USD
):
"""Ensure passing an empty attribute ID as sorting field does nothing."""
@@ -546,7 +601,11 @@ def test_sort_product_by_attribute_using_invalid_attribute_id(
# Products are ordered in descending order to ensure we
# are not actually trying to sort them at all
- variables = {"attributeId": attribute_id, "direction": "DESC"}
+ variables = {
+ "attributeId": attribute_id,
+ "direction": "DESC",
+ "channel": channel_USD.slug,
+ }
response = get_graphql_content(api_client.post_graphql(query, variables))
products = response["data"]["products"]["edges"]
@@ -557,7 +616,7 @@ def test_sort_product_by_attribute_using_invalid_attribute_id(
@pytest.mark.parametrize("direction", ["ASC", "DESC"])
def test_sort_product_by_attribute_using_attribute_having_no_products(
- api_client, product_list_published, direction
+ api_client, product_list_published, direction, channel_USD
):
"""Ensure passing an empty attribute ID as sorting field does nothing."""
@@ -569,7 +628,11 @@ def test_sort_product_by_attribute_using_attribute_having_no_products(
attribute_id: str = graphene.Node.to_global_id(
"Attribute", attribute_without_products.pk
)
- variables = {"attributeId": attribute_id, "direction": direction}
+ variables = {
+ "attributeId": attribute_id,
+ "direction": direction,
+ "channel": channel_USD.slug,
+ }
response = get_graphql_content(api_client.post_graphql(query, variables))
products = response["data"]["products"]["edges"]
diff --git a/saleor/graphql/product/tests/test_variant.py b/saleor/graphql/product/tests/test_variant.py
index b87c56725e..3010799f8c 100644
--- a/saleor/graphql/product/tests/test_variant.py
+++ b/saleor/graphql/product/tests/test_variant.py
@@ -10,20 +10,20 @@ from ....core.weight import WeightUnits
from ....order import OrderStatus
from ....order.models import OrderLine
from ....product.error_codes import ProductErrorCode
-from ....product.models import Product, ProductVariant
+from ....product.models import Product, ProductChannelListing, ProductVariant
from ....product.utils.attributes import associate_attribute_values_to_instance
from ....warehouse.error_codes import StockErrorCode
from ....warehouse.models import Stock, Warehouse
from ...core.enums import WeightUnitsEnum
-from ...tests.utils import assert_negative_positive_decimal_value, get_graphql_content
+from ...tests.utils import assert_no_permission, get_graphql_content
def test_fetch_variant(
- staff_api_client, product, permission_manage_products, site_settings
+ staff_api_client, product, permission_manage_products, site_settings, channel_USD,
):
query = """
- query ProductVariantDetails($id: ID!, $countyCode: CountryCode) {
- productVariant(id: $id) {
+ query ProductVariantDetails($id: ID!, $countyCode: CountryCode, $channel: String) {
+ productVariant(id: $id, channel: $channel) {
id
stocks(countryCode: $countyCode) {
id
@@ -53,9 +53,18 @@ def test_fetch_variant(
id
}
name
- price {
- currency
- amount
+ channelListings {
+ channel {
+ slug
+ }
+ price {
+ currency
+ amount
+ }
+ costPrice {
+ currency
+ amount
+ }
}
product {
id
@@ -76,7 +85,7 @@ def test_fetch_variant(
site_settings.save(update_fields=["default_weight_unit"])
variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
- variables = {"id": variant_id, "countyCode": "EU"}
+ variables = {"id": variant_id, "countyCode": "EU", "channel": channel_USD.slug}
staff_api_client.user.user_permissions.add(permission_manage_products)
# when
@@ -89,6 +98,145 @@ def test_fetch_variant(
assert len(data["stocks"]) == variant.stocks.count()
assert data["weight"]["value"] == 10000
assert data["weight"]["unit"] == WeightUnitsEnum.G.name
+ channel_listing_data = data["channelListings"][0]
+ channel_listing = variant.channel_listings.get()
+ assert channel_listing_data["channel"]["slug"] == channel_listing.channel.slug
+ assert channel_listing_data["price"]["currency"] == channel_listing.currency
+ assert channel_listing_data["price"]["amount"] == channel_listing.price_amount
+ assert channel_listing_data["costPrice"]["currency"] == channel_listing.currency
+ assert (
+ channel_listing_data["costPrice"]["amount"] == channel_listing.cost_price_amount
+ )
+
+
+QUERY_PRODUCT_VARIANT_CHANNEL_LISTING = """
+ query ProductVariantDetails($id: ID!, $channel: String) {
+ productVariant(id: $id, channel: $channel) {
+ id
+ channelListings {
+ channel {
+ slug
+ }
+ price {
+ currency
+ amount
+ }
+ costPrice {
+ currency
+ amount
+ }
+ }
+ }
+ }
+"""
+
+
+def test_get_product_variant_channel_listing_as_staff_user(
+ staff_api_client,
+ product_available_in_many_channels,
+ permission_manage_products,
+ channel_USD,
+):
+ # given
+ variant = product_available_in_many_channels.variants.get()
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ variables = {"id": variant_id, "channel": channel_USD.slug}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_PRODUCT_VARIANT_CHANNEL_LISTING,
+ variables,
+ permissions=[permission_manage_products],
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["productVariant"]
+ channel_listings = variant.channel_listings.all()
+ for channel_listing in channel_listings:
+ assert {
+ "channel": {"slug": channel_listing.channel.slug},
+ "price": {
+ "currency": channel_listing.currency,
+ "amount": channel_listing.price_amount,
+ },
+ "costPrice": {
+ "currency": channel_listing.currency,
+ "amount": channel_listing.cost_price_amount,
+ },
+ } in data["channelListings"]
+ assert len(data["channelListings"]) == variant.channel_listings.count()
+
+
+def test_get_product_variant_channel_listing_as_app(
+ app_api_client,
+ product_available_in_many_channels,
+ permission_manage_products,
+ channel_USD,
+):
+ # given
+ variant = product_available_in_many_channels.variants.get()
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ variables = {"id": variant_id, "channel": channel_USD.slug}
+
+ # when
+ response = app_api_client.post_graphql(
+ QUERY_PRODUCT_VARIANT_CHANNEL_LISTING,
+ variables,
+ permissions=[permission_manage_products],
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["productVariant"]
+ channel_listings = variant.channel_listings.all()
+ for channel_listing in channel_listings:
+ assert {
+ "channel": {"slug": channel_listing.channel.slug},
+ "price": {
+ "currency": channel_listing.currency,
+ "amount": channel_listing.price_amount,
+ },
+ "costPrice": {
+ "currency": channel_listing.currency,
+ "amount": channel_listing.cost_price_amount,
+ },
+ } in data["channelListings"]
+ assert len(data["channelListings"]) == variant.channel_listings.count()
+
+
+def test_get_product_variant_channel_listing_as_customer(
+ user_api_client, product_available_in_many_channels, channel_USD,
+):
+ # given
+ variant = product_available_in_many_channels.variants.get()
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ variables = {"id": variant_id, "channel": channel_USD.slug}
+
+ # when
+ response = user_api_client.post_graphql(
+ QUERY_PRODUCT_VARIANT_CHANNEL_LISTING, variables,
+ )
+
+ # then
+ assert_no_permission(response)
+
+
+def test_get_product_variant_channel_listing_as_anonymous(
+ api_client, product_available_in_many_channels, channel_USD,
+):
+ # given
+ variant = product_available_in_many_channels.variants.get()
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ variables = {"id": variant_id, "channel": channel_USD.slug}
+
+ # when
+ response = api_client.post_graphql(
+ QUERY_PRODUCT_VARIANT_CHANNEL_LISTING, variables,
+ )
+
+ # then
+ assert_no_permission(response)
CREATE_VARIANT_MUTATION = """
@@ -96,8 +244,6 @@ CREATE_VARIANT_MUTATION = """
$productId: ID!,
$sku: String,
$stocks: [StockInput!],
- $price: PositiveDecimal,
- $costPrice: PositiveDecimal,
$attributes: [AttributeValueInput]!,
$weight: WeightScalar,
$trackInventory: Boolean) {
@@ -106,8 +252,6 @@ CREATE_VARIANT_MUTATION = """
product: $productId,
sku: $sku,
stocks: $stocks,
- price: $price,
- costPrice: $costPrice,
attributes: $attributes,
trackInventory: $trackInventory,
weight: $weight
@@ -129,11 +273,6 @@ CREATE_VARIANT_MUTATION = """
slug
}
}
- price {
- currency
- amount
- localized
- }
costPrice {
currency
amount
@@ -168,8 +307,6 @@ def test_create_variant(
query = CREATE_VARIANT_MUTATION
product_id = graphene.Node.to_global_id("Product", product.pk)
sku = "1"
- price = 1.32
- cost_price = 3.22
weight = 10.22
variant_slug = product_type.variant_attributes.first().slug
variant_id = graphene.Node.to_global_id(
@@ -187,8 +324,6 @@ def test_create_variant(
"productId": product_id,
"sku": sku,
"stocks": stocks,
- "costPrice": cost_price,
- "price": price,
"weight": weight,
"attributes": [{"id": variant_id, "values": [variant_value]}],
"trackInventory": True,
@@ -200,8 +335,6 @@ def test_create_variant(
assert not content["productErrors"]
data = content["productVariant"]
assert data["name"] == variant_value
- assert data["costPrice"]["amount"] == cost_price
- assert data["price"]["amount"] == price
assert data["sku"] == sku
assert data["attributes"][0]["attribute"]["slug"] == variant_slug
assert data["attributes"][0]["values"][0]["slug"] == variant_value
@@ -213,29 +346,6 @@ def test_create_variant(
updated_webhook_mock.assert_called_once_with(product)
-def test_create_product_variant_without_price(
- staff_api_client, product, product_type, permission_manage_products
-):
- query = CREATE_VARIANT_MUTATION
- product_id = graphene.Node.to_global_id("Product", product.pk)
- attr_id = graphene.Node.to_global_id(
- "Attribute", product_type.variant_attributes.first().pk
- )
- attr_value = "test-value"
- variables = {
- "productId": product_id,
- "attributes": [{"id": attr_id, "values": [attr_value]}],
- }
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_products]
- )
- content = get_graphql_content(response)
- data = content["data"]["productVariantCreate"]
- error = data["productErrors"][0]
- assert error["field"] == "price"
- assert error["code"] == ProductErrorCode.REQUIRED.name
-
-
def test_create_product_variant_with_negative_weight(
staff_api_client, product, product_type, permission_manage_products
):
@@ -303,7 +413,6 @@ def test_create_product_variant_not_all_attributes(
variables = {
"productId": product_id,
- "price": 15,
"sku": sku,
"attributes": [{"id": variant_id, "values": [variant_value]}],
}
@@ -321,33 +430,6 @@ def test_create_product_variant_not_all_attributes(
assert not product.variants.filter(sku=sku).exists()
-def test_create_product_variant_too_many_places_in_cost_price(
- staff_api_client, product, product_type, permission_manage_products
-):
- query = CREATE_VARIANT_MUTATION
- product_id = graphene.Node.to_global_id("Product", product.pk)
-
- variant_id = graphene.Node.to_global_id(
- "Attribute", product_type.variant_attributes.first().pk
- )
- variant_value = "test-value"
-
- variables = {
- "productId": product_id,
- "weight": 1,
- "attributes": [{"id": variant_id, "values": [variant_value]}],
- "costPrice": 1.40001,
- }
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_products]
- )
- content = get_graphql_content(response)
- data = content["data"]["productVariantCreate"]
- error = data["productErrors"][0]
- assert error["field"] == "costPrice"
- assert error["code"] == ProductErrorCode.INVALID.name
-
-
def test_create_product_variant_duplicated_attributes(
staff_api_client,
product_with_variant_with_two_attributes,
@@ -363,7 +445,6 @@ def test_create_product_variant_duplicated_attributes(
sku = str(uuid4())[:12]
variables = {
"productId": product_id,
- "price": 15,
"sku": sku,
"attributes": [
{"id": color_attribute_id, "values": ["red"]},
@@ -471,8 +552,6 @@ def test_create_product_variant_update_with_new_attributes(
mutation VariantUpdate(
$id: ID!
$attributes: [AttributeValueInput]
- $costPrice: PositiveDecimal
- $price: PositiveDecimal
$sku: String
$trackInventory: Boolean!
) {
@@ -480,8 +559,6 @@ def test_create_product_variant_update_with_new_attributes(
id: $id
input: {
attributes: $attributes
- costPrice: $costPrice
- price: $price
sku: $sku
trackInventory: $trackInventory
}
@@ -519,9 +596,7 @@ def test_create_product_variant_update_with_new_attributes(
variables = {
"attributes": [{"id": size_attribute_id, "values": ["XXXL"]}],
- "costPrice": 10,
"id": variant_id,
- "price": 0,
"sku": "21599567",
"trackInventory": True,
}
@@ -551,31 +626,28 @@ def test_update_product_variant(
mutation updateVariant (
$id: ID!,
$sku: String!,
- $price: PositiveDecimal,
- $costPrice: PositiveDecimal,
$trackInventory: Boolean!,
- $attributes: [AttributeValueInput],
- ) {
+ $attributes: [AttributeValueInput]) {
productVariantUpdate(
id: $id,
input: {
sku: $sku,
- price: $price,
- costPrice: $costPrice,
trackInventory: $trackInventory,
attributes: $attributes,
}) {
productVariant {
name
sku
+ channelListings {
+ channel {
+ slug
+ }
+ }
costPrice {
currency
amount
localized
}
- price {
- amount
- }
}
}
}
@@ -585,14 +657,10 @@ def test_update_product_variant(
variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)
sku = "test sku"
- cost_price = 3.3
- price = 15
variables = {
"id": variant_id,
"sku": sku,
- "price": price,
- "costPrice": cost_price,
"trackInventory": True,
"attributes": [{"id": attribute_id, "values": ["S"]}],
}
@@ -604,8 +672,6 @@ def test_update_product_variant(
content = get_graphql_content(response)
data = content["data"]["productVariantUpdate"]["productVariant"]
assert data["name"] == variant.name
- assert data["costPrice"]["amount"] == cost_price
- assert data["price"]["amount"] == price
assert data["sku"] == sku
updated_webhook_mock.assert_called_once_with(product)
@@ -616,14 +682,12 @@ def test_update_product_variant_with_negative_weight(
query = """
mutation updateVariant (
$id: ID!,
- $price: PositiveDecimal,
$weight: WeightScalar
) {
productVariantUpdate(
id: $id,
input: {
weight: $weight,
- price: $price
}
){
productVariant {
@@ -639,7 +703,7 @@ def test_update_product_variant_with_negative_weight(
"""
variant = product.variants.first()
variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
- variables = {"id": variant_id, "weight": -1, "price": 15}
+ variables = {"id": variant_id, "weight": -1}
response = staff_api_client.post_graphql(
query, variables, permissions=[permission_manage_products]
)
@@ -651,128 +715,15 @@ def test_update_product_variant_with_negative_weight(
assert error["code"] == ProductErrorCode.INVALID.name
-def test_update_product_variant_unset_cost_price(
- staff_api_client, product, size_attribute, permission_manage_products
-):
- """Ensure setting nullable amounts to null is properly handled
- (setting the amount to none) and doesn't override the currency.
- """
- query = """
- mutation updateVariant (
- $id: ID!,
- $sku: String!,
- $price: PositiveDecimal,
- $costPrice: PositiveDecimal,
- $attributes: [AttributeValueInput],
- ) {
- productVariantUpdate(
- id: $id,
- input: {
- sku: $sku,
- price: $price,
- costPrice: $costPrice,
- attributes: $attributes,
- }) {
- productVariant {
- name
- sku
- costPrice {
- currency
- amount
- localized
- }
- }
- }
- }
-
- """
- variant = product.variants.first()
- variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
- attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)
- sku = variant.sku
-
- variables = {
- "id": variant_id,
- "sku": sku,
- "costPrice": None,
- "price": 15,
- "attributes": [{"id": attribute_id, "values": ["S"]}],
- }
-
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_products]
- )
- variant.refresh_from_db()
-
- assert variant.currency is not None
- assert getattr(variant, "cost_price") is None
-
- content = get_graphql_content(response)
- data = content["data"]["productVariantUpdate"]["productVariant"]
- assert data["costPrice"] is None
-
-
-def test_update_product_variant_invalid_price(
- staff_api_client, product, size_attribute, permission_manage_products
-):
- query = """
- mutation updateVariant(
- $id: ID!
- $sku: String!
- $price: PositiveDecimal
- $costPrice: PositiveDecimal,
- $attributes: [AttributeValueInput],
- ) {
- productVariantUpdate(
- id: $id
- input: {
- sku: $sku,
- price: $price,
- costPrice: $costPrice,
- attributes: $attributes,
- }
- ) {
- productErrors {
- field
- message
- code
- }
- }
- }
- """
- variant = product.variants.first()
- variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
- attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)
-
- variables = {
- "id": variant_id,
- "sku": variant.sku,
- "costPrice": 15,
- "price": 1234567891234,
- "attributes": [{"id": attribute_id, "values": ["S"]}],
- }
-
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_products]
- )
- content = get_graphql_content(response)
-
- errors = content["data"]["productVariantUpdate"]["productErrors"]
- assert errors[0]["field"] == "price"
- assert errors[0]["code"] == ProductErrorCode.INVALID.name
-
-
QUERY_UPDATE_VARIANT_ATTRIBUTES = """
mutation updateVariant (
$id: ID!,
$sku: String,
- $price: PositiveDecimal,
$attributes: [AttributeValueInput]!) {
productVariantUpdate(
id: $id,
input: {
sku: $sku,
- price: $price,
attributes: $attributes
}) {
errors {
@@ -788,47 +739,6 @@ QUERY_UPDATE_VARIANT_ATTRIBUTES = """
"""
-def test_update_product_variant_with_too_many_decimal_values_in_price(
- staff_api_client, product, permission_manage_products
-):
- query = """
- mutation updateVariant (
- $id: ID!,
- $price: PositiveDecimal,
- $weight: WeightScalar
- ) {
- productVariantUpdate(
- id: $id,
- input: {
- weight: $weight,
- price: $price
- }
- ){
- productVariant {
- name
- }
- productErrors {
- field
- message
- code
- }
- }
- }
- """
- variant = product.variants.first()
- variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
- variables = {"id": variant_id, "weight": 1, "price": 15.234}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_products]
- )
- variant.refresh_from_db()
- content = get_graphql_content(response)
- data = content["data"]["productVariantUpdate"]
- error = data["productErrors"][0]
- assert error["field"] == "price"
- assert error["code"] == ProductErrorCode.INVALID.name
-
-
def test_update_product_variant_not_all_attributes(
staff_api_client, product, product_type, color_attribute, permission_manage_products
):
@@ -849,7 +759,6 @@ def test_update_product_variant_not_all_attributes(
variables = {
"id": variant_id,
"sku": sku,
- "price": 15,
"attributes": [{"id": attr_id, "values": [variant_value]}],
}
@@ -887,7 +796,6 @@ def test_update_product_variant_with_current_attribute(
variables = {
"id": variant_id,
"sku": sku,
- "price": 15,
"attributes": [
{"id": color_attribute_id, "values": ["red"]},
{"id": size_attribute_id, "values": ["small"]},
@@ -930,7 +838,6 @@ def test_update_product_variant_with_new_attribute(
variables = {
"id": variant_id,
"sku": sku,
- "price": 15,
"attributes": [
{"id": color_attribute_id, "values": ["red"]},
{"id": size_attribute_id, "values": ["big"]},
@@ -984,7 +891,6 @@ def test_update_product_variant_with_duplicated_attribute(
variables = {
"id": variant_id,
- "price": 15,
"attributes": [
{"id": color_attribute_id, "values": ["blue"]},
{"id": size_attribute_id, "values": ["big"]},
@@ -1035,7 +941,6 @@ def test_update_product_variant_requires_values(
variables = {
"id": variant_id,
- "price": 15,
"attributes": [{"id": attr_id, "values": values}],
"sku": sku,
}
@@ -1067,9 +972,6 @@ def test_update_product_variant_with_price_does_not_raise_price_validation_error
}) {
productVariant {
id
- price {
- amount
- }
}
productErrors {
field
@@ -1094,10 +996,6 @@ def test_update_product_variant_with_price_does_not_raise_price_validation_error
# then mutation passes without validation errors
content = get_graphql_content(response)
assert not content["data"]["productVariantUpdate"]["productErrors"]
- assert (
- content["data"]["productVariantUpdate"]["productVariant"]["price"]["amount"]
- == variant.price.amount
- )
DELETE_VARIANT_MUTATION = """
@@ -1128,7 +1026,7 @@ def test_delete_variant(staff_api_client, product, permission_manage_products):
def test_delete_variant_in_draft_order(
- staff_api_client, order_line, permission_manage_products, order_list
+ staff_api_client, order_line, permission_manage_products, order_list, channel_USD,
):
query = DELETE_VARIANT_MUTATION
@@ -1140,7 +1038,7 @@ def test_delete_variant_in_draft_order(
variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
variables = {"id": variant_id}
- net = variant.get_price()
+ net = variant.get_price(channel_USD)
gross = Money(amount=net.amount, currency=net.currency)
order_not_draft = order_list[-1]
order_line_not_in_draft = OrderLine.objects.create(
@@ -1268,10 +1166,10 @@ def test_delete_default_all_product_variant_left_product_default_variant_unset(
assert not product.default_variant
-def _fetch_all_variants(client, permissions=None):
+def _fetch_all_variants(client, variables={}, permissions=None):
query = """
- query fetchAllVariants {
- productVariants(first: 10) {
+ query fetchAllVariants($channel: String) {
+ productVariants(first: 10, channel: $channel) {
totalCount
edges {
node {
@@ -1282,7 +1180,7 @@ def _fetch_all_variants(client, permissions=None):
}
"""
response = client.post_graphql(
- query, {}, permissions=permissions, check_no_permissions=False
+ query, variables, permissions=permissions, check_no_permissions=False
)
content = get_graphql_content(response)
return content["data"]["productVariants"]
@@ -1291,31 +1189,57 @@ def _fetch_all_variants(client, permissions=None):
def test_fetch_all_variants_staff_user(
staff_api_client, unavailable_product_with_variant, permission_manage_products
):
+ variant = unavailable_product_with_variant.variants.first()
data = _fetch_all_variants(
staff_api_client, permissions=[permission_manage_products]
)
- variant = unavailable_product_with_variant.variants.first()
variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
assert data["totalCount"] == 1
assert data["edges"][0]["node"]["id"] == variant_id
-def test_fetch_all_variants_customer(user_api_client, unavailable_product_with_variant):
- data = _fetch_all_variants(user_api_client)
+def test_fetch_all_variants_staff_user_with_channel(
+ staff_api_client,
+ product_list_with_variants_many_channel,
+ permission_manage_products,
+ channel_PLN,
+):
+ variables = {"channel": channel_PLN.slug}
+ data = _fetch_all_variants(
+ staff_api_client, variables, permissions=[permission_manage_products]
+ )
+ assert data["totalCount"] == 2
+
+
+def test_fetch_all_variants_staff_user_without_channel(
+ staff_api_client,
+ product_list_with_variants_many_channel,
+ permission_manage_products,
+):
+ data = _fetch_all_variants(
+ staff_api_client, permissions=[permission_manage_products]
+ )
+ assert data["totalCount"] == 3
+
+
+def test_fetch_all_variants_customer(
+ user_api_client, unavailable_product_with_variant, channel_USD
+):
+ data = _fetch_all_variants(user_api_client, variables={"channel": channel_USD.slug})
assert data["totalCount"] == 0
def test_fetch_all_variants_anonymous_user(
- api_client, unavailable_product_with_variant
+ api_client, unavailable_product_with_variant, channel_USD
):
- data = _fetch_all_variants(api_client)
+ data = _fetch_all_variants(api_client, variables={"channel": channel_USD.slug})
assert data["totalCount"] == 0
-def test_product_variants_by_ids(user_api_client, variant):
+def test_product_variants_by_ids(user_api_client, variant, channel_USD):
query = """
- query getProduct($ids: [ID!]) {
- productVariants(ids: $ids, first: 1) {
+ query getProduct($ids: [ID!], $channel: String) {
+ productVariants(ids: $ids, first: 1, channel: $channel) {
edges {
node {
id
@@ -1326,7 +1250,7 @@ def test_product_variants_by_ids(user_api_client, variant):
"""
variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
- variables = {"ids": [variant_id]}
+ variables = {"ids": [variant_id], "channel": channel_USD.slug}
response = user_api_client.post_graphql(query, variables)
content = get_graphql_content(response)
data = content["data"]["productVariants"]
@@ -1335,86 +1259,89 @@ def test_product_variants_by_ids(user_api_client, variant):
def test_product_variants_visible_in_listings_by_customer(
- user_api_client, product_list
+ user_api_client, product_list, channel_USD
):
# given
- product_list[0].visible_in_listings = False
- product_list[0].save(update_fields=["visible_in_listings"])
+ product_list[0].channel_listings.all().update(visible_in_listings=False)
product_count = Product.objects.count()
# when
- data = _fetch_all_variants(user_api_client)
+ data = _fetch_all_variants(user_api_client, variables={"channel": channel_USD.slug})
assert data["totalCount"] == product_count - 1
def test_product_variants_visible_in_listings_by_staff_without_perm(
- staff_api_client, product_list
+ staff_api_client, product_list, channel_USD
):
# given
- product_list[0].visible_in_listings = False
- product_list[0].save(update_fields=["visible_in_listings"])
+ product_list[0].channel_listings.all().update(visible_in_listings=False)
product_count = Product.objects.count()
# when
- data = _fetch_all_variants(staff_api_client)
+ data = _fetch_all_variants(
+ staff_api_client, variables={"channel": channel_USD.slug}
+ )
assert data["totalCount"] == product_count - 1
def test_product_variants_visible_in_listings_by_staff_with_perm(
- staff_api_client, product_list, permission_manage_products
+ staff_api_client, product_list, permission_manage_products, channel_USD
):
# given
- product_list[0].visible_in_listings = False
- product_list[0].save(update_fields=["visible_in_listings"])
+ product_list[0].channel_listings.all().update(visible_in_listings=False)
product_count = Product.objects.count()
# when
data = _fetch_all_variants(
- staff_api_client, permissions=[permission_manage_products]
+ staff_api_client,
+ variables={"channel": channel_USD.slug},
+ permissions=[permission_manage_products],
)
assert data["totalCount"] == product_count
def test_product_variants_visible_in_listings_by_app_without_perm(
- app_api_client, product_list
+ app_api_client, product_list, channel_USD
):
# given
- product_list[0].visible_in_listings = False
- product_list[0].save(update_fields=["visible_in_listings"])
+ product_list[0].channel_listings.all().update(visible_in_listings=False)
product_count = Product.objects.count()
# when
- data = _fetch_all_variants(app_api_client)
+ data = _fetch_all_variants(app_api_client, variables={"channel": channel_USD.slug})
assert data["totalCount"] == product_count - 1
def test_product_variants_visible_in_listings_by_app_with_perm(
- app_api_client, product_list, permission_manage_products
+ app_api_client, product_list, permission_manage_products, channel_USD
):
# given
- product_list[0].visible_in_listings = False
- product_list[0].save(update_fields=["visible_in_listings"])
+ product_list[0].channel_listings.all().update(visible_in_listings=False)
product_count = Product.objects.count()
# when
- data = _fetch_all_variants(app_api_client, permissions=[permission_manage_products])
+ data = _fetch_all_variants(
+ app_api_client,
+ variables={"channel": channel_USD.slug},
+ permissions=[permission_manage_products],
+ )
assert data["totalCount"] == product_count
-def _fetch_variant(client, variant, permissions=None):
+def _fetch_variant(client, variant, channel_slug=None, permissions=None):
query = """
- query ProductVariantDetails($variantId: ID!) {
- productVariant(id: $variantId) {
+ query ProductVariantDetails($variantId: ID!, $channel: String) {
+ productVariant(id: $variantId, channel: $channel) {
id
product {
id
@@ -1423,6 +1350,8 @@ def _fetch_variant(client, variant, permissions=None):
}
"""
variables = {"variantId": graphene.Node.to_global_id("ProductVariant", variant.id)}
+ if channel_slug:
+ variables["channel"] = channel_slug
response = client.post_graphql(
query, variables, permissions=permissions, check_no_permissions=False
)
@@ -1435,7 +1364,7 @@ def test_fetch_unpublished_variant_staff_user(
):
variant = unavailable_product_with_variant.variants.first()
data = _fetch_variant(
- staff_api_client, variant, permissions=[permission_manage_products]
+ staff_api_client, variant, permissions=[permission_manage_products],
)
variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
@@ -1448,18 +1377,18 @@ def test_fetch_unpublished_variant_staff_user(
def test_fetch_unpublished_variant_customer(
- user_api_client, unavailable_product_with_variant
+ user_api_client, unavailable_product_with_variant, channel_USD
):
variant = unavailable_product_with_variant.variants.first()
- data = _fetch_variant(user_api_client, variant)
+ data = _fetch_variant(user_api_client, variant, channel_slug=channel_USD.slug)
assert data is None
def test_fetch_unpublished_variant_anonymous_user(
- api_client, unavailable_product_with_variant
+ api_client, unavailable_product_with_variant, channel_USD
):
variant = unavailable_product_with_variant.variants.first()
- data = _fetch_variant(api_client, variant)
+ data = _fetch_variant(api_client, variant, channel_slug=channel_USD.slug)
assert data is None
@@ -1474,19 +1403,30 @@ PRODUCT_VARIANT_BULK_CREATE_MUTATION = """
code
index
warehouses
+ channels
}
productVariants{
id
sku
- price {
- amount
- }
stocks {
warehouse {
slug
}
quantity
}
+ channelListings {
+ channel {
+ slug
+ }
+ price {
+ currency
+ amount
+ }
+ costPrice {
+ currency
+ amount
+ }
+ }
}
count
}
@@ -1506,11 +1446,9 @@ def test_product_variant_bulk_create_by_attribute_id(
variants = [
{
"sku": sku,
- "costPrice": None,
"weight": 2.5,
"trackInventory": True,
"attributes": [{"id": attribut_id, "values": [attribute_value.name]}],
- "price": 10,
}
]
@@ -1526,85 +1464,16 @@ def test_product_variant_bulk_create_by_attribute_id(
assert product_variant_count + 1 == ProductVariant.objects.count()
assert attribute_value_count == size_attribute.values.count()
product_variant = ProductVariant.objects.get(sku=sku)
- assert not product_variant.cost_price
product.refresh_from_db()
assert product.default_variant == product_variant
- "price_field", ("price", "costPrice",),
-)
-def test_product_variant_bulk_create_by_attribute_id_with_negative_price(
- staff_api_client, product, size_attribute, permission_manage_products, price_field
-):
- # given
- product_id = graphene.Node.to_global_id("Product", product.pk)
- attribut_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)
- attribute_value = size_attribute.values.last()
- sku = str(uuid4())[:12]
- variant = {
- "sku": sku,
- "weight": 2.5,
- "trackInventory": True,
- "attributes": [{"id": attribut_id, "values": [attribute_value.name]}],
- "price": 10,
- price_field: "-1",
- }
-
- variables = {"productId": product_id, "variants": [variant]}
- staff_api_client.user.user_permissions.add(permission_manage_products)
-
- # when
- response = staff_api_client.post_graphql(
- PRODUCT_VARIANT_BULK_CREATE_MUTATION, variables
- )
-
- # then
- assert_negative_positive_decimal_value(response)
-
-
- "price_field", ("price", "costPrice",),
-)
-def test_product_variant_bulk_create_too_many_decimal_places_in_price(
- staff_api_client, product, size_attribute, permission_manage_products, price_field
-):
- # given
- product_id = graphene.Node.to_global_id("Product", product.pk)
- attribut_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)
- attribute_value = size_attribute.values.last()
- sku = str(uuid4())[:12]
- variant = {
- "sku": sku,
- "weight": 2.5,
- "trackInventory": True,
- "attributes": [{"id": attribut_id, "values": [attribute_value.name]}],
- "price": 10,
- price_field: 1.1234,
- }
-
- variables = {"productId": product_id, "variants": [variant]}
- staff_api_client.user.user_permissions.add(permission_manage_products)
-
- # when
- response = staff_api_client.post_graphql(
- PRODUCT_VARIANT_BULK_CREATE_MUTATION, variables
- )
-
- # then
- content = get_graphql_content(response)
- data = content["data"]["productVariantBulkCreate"]
- error = data["bulkProductErrors"][0]
- assert error["field"] == price_field
- assert error["code"] == ProductErrorCode.INVALID.name
-
-
def test_product_variant_bulk_create_empty_attribute(
staff_api_client, product, size_attribute, permission_manage_products
):
product_variant_count = ProductVariant.objects.count()
product_id = graphene.Node.to_global_id("Product", product.pk)
- variants = [{"sku": str(uuid4())[:12], "attributes": [], "price": 10}]
+ variants = [{"sku": str(uuid4())[:12], "attributes": []}]
variables = {"productId": product_id, "variants": variants}
staff_api_client.user.user_permissions.add(permission_manage_products)
@@ -1630,12 +1499,10 @@ def test_product_variant_bulk_create_with_new_attribute_value(
{
"sku": str(uuid4())[:12],
"attributes": [{"id": size_attribute_id, "values": [attribute_value.name]}],
- "price": 10,
},
{
"sku": str(uuid4())[:12],
"attributes": [{"id": size_attribute_id, "values": ["Test-attribute"]}],
- "price": 10,
},
]
@@ -1672,7 +1539,6 @@ def test_product_variant_bulk_create_stocks_input(
}
],
"attributes": [{"id": size_attribute_id, "values": [attribute_value.name]}],
- "price": 10,
},
{
"sku": str(uuid4())[:12],
@@ -1691,7 +1557,6 @@ def test_product_variant_bulk_create_stocks_input(
),
},
],
- "price": 10,
},
]
@@ -1716,7 +1581,6 @@ def test_product_variant_bulk_create_stocks_input(
"quantity": variants[0]["stocks"][0]["quantity"],
}
],
- "price": {"amount": 10.0},
},
variants[1]["sku"]: {
"sku": variants[1]["sku"],
@@ -1730,7 +1594,6 @@ def test_product_variant_bulk_create_stocks_input(
"quantity": variants[1]["stocks"][1]["quantity"],
},
],
- "price": {"amount": 10.0},
},
}
for variant_data in data["productVariants"]:
@@ -1738,7 +1601,6 @@ def test_product_variant_bulk_create_stocks_input(
assert variant_data["sku"] in expected_result
expected_variant = expected_result[variant_data["sku"]]
expected_stocks = expected_variant["stocks"]
- assert variant_data["price"] == expected_variant["price"]
assert all([stock in expected_stocks for stock in variant_data["stocks"]])
@@ -1761,7 +1623,6 @@ def test_product_variant_bulk_create_duplicated_warehouses(
}
],
"attributes": [{"id": size_attribute_id, "values": [attribute_value.name]}],
- "price": 10,
},
{
"sku": str(uuid4())[:12],
@@ -1770,7 +1631,6 @@ def test_product_variant_bulk_create_duplicated_warehouses(
{"quantity": 15, "warehouse": warehouse1_id},
{"quantity": 15, "warehouse": warehouse1_id},
],
- "price": 10,
},
]
@@ -1792,6 +1652,259 @@ def test_product_variant_bulk_create_duplicated_warehouses(
assert error["warehouses"] == [warehouse1_id]
+def test_product_variant_bulk_create_channel_listings_input(
+ staff_api_client,
+ product_available_in_many_channels,
+ permission_manage_products,
+ warehouses,
+ size_attribute,
+ channel_USD,
+ channel_PLN,
+):
+ product = product_available_in_many_channels
+ ProductChannelListing.objects.filter(product=product, channel=channel_PLN).update(
+ is_published=False
+ )
+ product_variant_count = ProductVariant.objects.count()
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ attribute_value_count = size_attribute.values.count()
+ size_attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)
+ attribute_value = size_attribute.values.last()
+ variants = [
+ {
+ "sku": str(uuid4())[:12],
+ "channelListings": [
+ {
+ "price": 10.0,
+ "costPrice": 11.0,
+ "channelId": graphene.Node.to_global_id("Channel", channel_USD.pk),
+ }
+ ],
+ "attributes": [{"id": size_attribute_id, "values": [attribute_value.name]}],
+ },
+ {
+ "sku": str(uuid4())[:12],
+ "attributes": [{"id": size_attribute_id, "values": ["Test-attribute"]}],
+ "channelListings": [
+ {
+ "price": 15.0,
+ "costPrice": 16.0,
+ "channelId": graphene.Node.to_global_id("Channel", channel_USD.pk),
+ },
+ {
+ "price": 12.0,
+ "costPrice": 13.0,
+ "channelId": graphene.Node.to_global_id("Channel", channel_PLN.pk),
+ },
+ ],
+ },
+ ]
+
+ variables = {"productId": product_id, "variants": variants}
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_BULK_CREATE_MUTATION, variables
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productVariantBulkCreate"]
+ assert not data["bulkProductErrors"]
+ assert data["count"] == 2
+ assert product_variant_count + 2 == ProductVariant.objects.count()
+ assert attribute_value_count + 1 == size_attribute.values.count()
+
+ expected_result = {
+ variants[0]["sku"]: {
+ "sku": variants[0]["sku"],
+ "channelListings": [
+ {
+ "channel": {"slug": channel_USD.slug},
+ "price": {
+ "amount": variants[0]["channelListings"][0]["price"],
+ "currency": channel_USD.currency_code,
+ },
+ "costPrice": {
+ "amount": variants[0]["channelListings"][0]["costPrice"],
+ "currency": channel_USD.currency_code,
+ },
+ }
+ ],
+ },
+ variants[1]["sku"]: {
+ "sku": variants[1]["sku"],
+ "channelListings": [
+ {
+ "channel": {"slug": channel_USD.slug},
+ "price": {
+ "amount": variants[1]["channelListings"][0]["price"],
+ "currency": channel_USD.currency_code,
+ },
+ "costPrice": {
+ "amount": variants[1]["channelListings"][0]["costPrice"],
+ "currency": channel_USD.currency_code,
+ },
+ },
+ {
+ "channel": {"slug": channel_PLN.slug},
+ "price": {
+ "amount": variants[1]["channelListings"][1]["price"],
+ "currency": channel_PLN.currency_code,
+ },
+ "costPrice": {
+ "amount": variants[1]["channelListings"][1]["costPrice"],
+ "currency": channel_PLN.currency_code,
+ },
+ },
+ ],
+ },
+ }
+ for variant_data in data["productVariants"]:
+ variant_data.pop("id")
+ assert variant_data["sku"] in expected_result
+ expected_variant = expected_result[variant_data["sku"]]
+ expected_channel_listing = expected_variant["channelListings"]
+ assert all(
+ [
+ channelListing in expected_channel_listing
+ for channelListing in variant_data["channelListings"]
+ ]
+ )
+
+
+def test_product_variant_bulk_create_duplicated_channels(
+ staff_api_client,
+ product_available_in_many_channels,
+ permission_manage_products,
+ warehouses,
+ size_attribute,
+ channel_USD,
+):
+ product = product_available_in_many_channels
+ product_variant_count = ProductVariant.objects.count()
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ size_attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)
+ attribute_value = size_attribute.values.last()
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.pk)
+ variants = [
+ {
+ "sku": str(uuid4())[:12],
+ "channelListings": [
+ {"price": 10.0, "channelId": channel_id},
+ {"price": 10.0, "channelId": channel_id},
+ ],
+ "attributes": [{"id": size_attribute_id, "values": [attribute_value.name]}],
+ },
+ ]
+
+ variables = {"productId": product_id, "variants": variants}
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_BULK_CREATE_MUTATION, variables
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productVariantBulkCreate"]
+ assert len(data["bulkProductErrors"]) == 1
+ error = data["bulkProductErrors"][0]
+ assert error["field"] == "channelListings"
+ assert error["code"] == ProductErrorCode.DUPLICATED_INPUT_ITEM.name
+ assert error["index"] == 0
+ assert error["channels"] == [channel_id]
+ assert product_variant_count == ProductVariant.objects.count()
+
+
+def test_product_variant_bulk_create_too_many_decimal_places_in_price(
+ staff_api_client,
+ product_available_in_many_channels,
+ permission_manage_products,
+ size_attribute,
+ channel_USD,
+ channel_PLN,
+):
+ product = product_available_in_many_channels
+ product_variant_count = ProductVariant.objects.count()
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ size_attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)
+ attribute_value = size_attribute.values.last()
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.pk)
+ channel_pln_id = graphene.Node.to_global_id("Channel", channel_PLN.pk)
+ variants = [
+ {
+ "sku": str(uuid4())[:12],
+ "channelListings": [
+ {"price": 10.1234, "costPrice": 10.1234, "channelId": channel_id},
+ {"price": 10.12345, "costPrice": 10.12345, "channelId": channel_pln_id},
+ ],
+ "attributes": [{"id": size_attribute_id, "values": [attribute_value.name]}],
+ },
+ ]
+
+ variables = {"productId": product_id, "variants": variants}
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_BULK_CREATE_MUTATION, variables
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productVariantBulkCreate"]
+ assert len(data["bulkProductErrors"]) == 4
+ errors = data["bulkProductErrors"]
+ assert errors[0]["field"] == "price"
+ assert errors[0]["code"] == ProductErrorCode.INVALID.name
+ assert errors[0]["index"] == 0
+ assert errors[0]["channels"] == [channel_id]
+ assert errors[1]["field"] == "price"
+ assert errors[1]["code"] == ProductErrorCode.INVALID.name
+ assert errors[1]["index"] == 0
+ assert errors[1]["channels"] == [channel_pln_id]
+ assert errors[2]["field"] == "costPrice"
+ assert errors[2]["code"] == ProductErrorCode.INVALID.name
+ assert errors[2]["index"] == 0
+ assert errors[2]["channels"] == [channel_id]
+ assert errors[3]["field"] == "costPrice"
+ assert errors[3]["code"] == ProductErrorCode.INVALID.name
+ assert errors[3]["index"] == 0
+ assert errors[3]["channels"] == [channel_pln_id]
+ assert product_variant_count == ProductVariant.objects.count()
+
+
+def test_product_variant_bulk_create_product_not_assigned_to_channel(
+ staff_api_client,
+ product,
+ permission_manage_products,
+ warehouses,
+ size_attribute,
+ channel_PLN,
+):
+ product_variant_count = ProductVariant.objects.count()
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ assert not ProductChannelListing.objects.filter(
+ product=product, channel=channel_PLN
+ ).exists()
+ size_attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)
+ attribute_value = size_attribute.values.last()
+ channel_id = graphene.Node.to_global_id("Channel", channel_PLN.pk)
+ variants = [
+ {
+ "sku": str(uuid4())[:12],
+ "channelListings": [{"price": 10.0, "channelId": channel_id}],
+ "attributes": [{"id": size_attribute_id, "values": [attribute_value.name]}],
+ },
+ ]
+
+ variables = {"productId": product_id, "variants": variants}
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_BULK_CREATE_MUTATION, variables
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productVariantBulkCreate"]
+ assert len(data["bulkProductErrors"]) == 1
+ error = data["bulkProductErrors"][0]
+ assert error["field"] == "channelId"
+ assert error["code"] == ProductErrorCode.PRODUCT_NOT_ASSIGNED_TO_CHANNEL.name
+ assert error["index"] == 0
+ assert error["channels"] == [channel_id]
+ assert product_variant_count == ProductVariant.objects.count()
+
+
def test_product_variant_bulk_create_duplicated_sku(
staff_api_client,
product,
@@ -1809,12 +1922,10 @@ def test_product_variant_bulk_create_duplicated_sku(
{
"sku": sku,
"attributes": [{"id": size_attribute_id, "values": ["Test-value"]}],
- "price": 10,
},
{
"sku": sku2,
"attributes": [{"id": size_attribute_id, "values": ["Test-valuee"]}],
- "price": 10,
},
]
@@ -1845,12 +1956,10 @@ def test_product_variant_bulk_create_duplicated_sku_in_input(
{
"sku": sku,
"attributes": [{"id": size_attribute_id, "values": ["Test-value"]}],
- "price": 10,
},
{
"sku": sku,
"attributes": [{"id": size_attribute_id, "values": ["Test-value2"]}],
- "price": 10,
},
]
@@ -1884,22 +1993,18 @@ def test_product_variant_bulk_create_many_errors(
{
"sku": str(uuid4())[:12],
"attributes": [{"id": size_attribute_id, "values": ["Test-value1"]}],
- "price": 10,
},
{
"sku": str(uuid4())[:12],
"attributes": [{"id": size_attribute_id, "values": ["Test-value4"]}],
- "price": 10,
},
{
"sku": sku,
"attributes": [{"id": size_attribute_id, "values": ["Test-value2"]}],
- "price": 10,
},
{
"sku": str(uuid4())[:12],
"attributes": [{"id": invalid_attribute_id, "values": ["Test-value3"]}],
- "price": 10,
},
]
@@ -1919,6 +2024,7 @@ def test_product_variant_bulk_create_many_errors(
"code": ProductErrorCode.UNIQUE.name,
"message": ANY,
"warehouses": None,
+ "channels": None,
},
{
"field": "attributes",
@@ -1926,6 +2032,7 @@ def test_product_variant_bulk_create_many_errors(
"code": ProductErrorCode.NOT_FOUND.name,
"message": ANY,
"warehouses": None,
+ "channels": None,
},
]
for expected_error in expected_errors:
@@ -1952,7 +2059,6 @@ def test_product_variant_bulk_create_two_variants_duplicated_attribute_value(
{"id": color_attribute_id, "values": ["red"]},
{"id": size_attribute_id, "values": ["small"]},
],
- "price": 10,
}
]
variables = {"productId": product_id, "variants": variants}
@@ -1987,8 +2093,8 @@ def test_product_variant_bulk_create_two_variants_duplicated_attribute_value_in_
{"id": size_attribute_id, "values": [size_attribute.values.last().slug]},
]
variants = [
- {"sku": str(uuid4())[:12], "attributes": attributes, "price": 10},
- {"sku": str(uuid4())[:12], "attributes": attributes, "price": 10},
+ {"sku": str(uuid4())[:12], "attributes": attributes},
+ {"sku": str(uuid4())[:12], "attributes": attributes},
]
variables = {"productId": product_id, "variants": variants}
staff_api_client.user.user_permissions.add(permission_manage_products)
@@ -2024,7 +2130,6 @@ def test_product_variant_bulk_create_two_variants_duplicated_one_attribute_value
{"id": color_attribute_id, "values": ["red"]},
{"id": size_attribute_id, "values": ["big"]},
],
- "price": 10,
}
]
variables = {"productId": product_id, "variants": variants}
diff --git a/saleor/graphql/product/tests/test_variant_availability.py b/saleor/graphql/product/tests/test_variant_availability.py
index 71013a9dda..e9bb197686 100644
--- a/saleor/graphql/product/tests/test_variant_availability.py
+++ b/saleor/graphql/product/tests/test_variant_availability.py
@@ -6,77 +6,19 @@ from ...tests.utils import get_graphql_content
COUNTRY_CODE = "US"
-QUERY_DEPRECATED_VARIANT_AVAILABILITY = """
- query variantAvailability($id: ID!) {
- productVariant(id: $id) {
- isAvailable
- stockQuantity
- quantityAvailable
- }
- }
-"""
-
-
-def test_variant_availability_without_inventory_tracking(
- api_client, variant_without_inventory_tracking, settings
-):
- variant = variant_without_inventory_tracking
- variables = {"id": graphene.Node.to_global_id("ProductVariant", variant.pk)}
- response = api_client.post_graphql(QUERY_DEPRECATED_VARIANT_AVAILABILITY, variables)
- content = get_graphql_content(response)
- variant_data = content["data"]["productVariant"]
- assert variant_data["isAvailable"] is True
- assert variant_data["stockQuantity"] == settings.MAX_CHECKOUT_LINE_QUANTITY
- assert variant_data["quantityAvailable"] == settings.MAX_CHECKOUT_LINE_QUANTITY
-
-
-def test_variant_availability(api_client, variant_with_many_stocks, settings):
- variant = variant_with_many_stocks
- variables = {"id": graphene.Node.to_global_id("ProductVariant", variant.pk)}
- response = api_client.post_graphql(QUERY_DEPRECATED_VARIANT_AVAILABILITY, variables)
- content = get_graphql_content(response)
- variant_data = content["data"]["productVariant"]
- assert variant_data["isAvailable"] is True
- assert variant_data["stockQuantity"] == 7
- assert variant_data["quantityAvailable"] == 7
-
-
-def test_variant_availability_without_inventory_tracking_without_stocks(
- api_client, variant_without_inventory_tracking, settings
-):
- variant = variant_without_inventory_tracking
- variant.stocks.all().delete()
- variables = {"id": graphene.Node.to_global_id("ProductVariant", variant.pk)}
- response = api_client.post_graphql(QUERY_DEPRECATED_VARIANT_AVAILABILITY, variables)
- content = get_graphql_content(response)
- variant_data = content["data"]["productVariant"]
- assert variant_data["isAvailable"] is True
- assert variant_data["stockQuantity"] == settings.MAX_CHECKOUT_LINE_QUANTITY
- assert variant_data["quantityAvailable"] == settings.MAX_CHECKOUT_LINE_QUANTITY
-
-
-def test_variant_availability_without_stocks(api_client, variant, settings):
- variables = {"id": graphene.Node.to_global_id("ProductVariant", variant.pk)}
- response = api_client.post_graphql(QUERY_DEPRECATED_VARIANT_AVAILABILITY, variables)
- content = get_graphql_content(response)
- variant_data = content["data"]["productVariant"]
- assert variant_data["isAvailable"] is False
- assert variant_data["stockQuantity"] == 0
- assert variant_data["quantityAvailable"] == 0
-
-
def test_variant_quantity_available_without_country_code(
- api_client, variant_with_many_stocks
+ api_client, variant_with_many_stocks, channel_USD
):
query = """
- query variantAvailability($id: ID!) {
- productVariant(id: $id) {
+ query variantAvailability($id: ID!, $channel: String) {
+ productVariant(id: $id, channel: $channel) {
quantityAvailable
}
}
"""
variables = {
- "id": graphene.Node.to_global_id("ProductVariant", variant_with_many_stocks.pk)
+ "id": graphene.Node.to_global_id("ProductVariant", variant_with_many_stocks.pk),
+ "channel": channel_USD.slug,
}
response = api_client.post_graphql(query, variables)
content = get_graphql_content(response)
@@ -85,8 +27,8 @@ def test_variant_quantity_available_without_country_code(
QUERY_VARIANT_AVAILABILITY = """
- query variantAvailability($id: ID!, $country: CountryCode) {
- productVariant(id: $id) {
+ query variantAvailability($id: ID!, $country: CountryCode, $channel: String) {
+ productVariant(id: $id, channel: $channel) {
quantityAvailable(countryCode: $country)
}
}
@@ -94,11 +36,12 @@ QUERY_VARIANT_AVAILABILITY = """
def test_variant_quantity_available_with_country_code(
- api_client, variant_with_many_stocks,
+ api_client, variant_with_many_stocks, channel_USD
):
variables = {
"id": graphene.Node.to_global_id("ProductVariant", variant_with_many_stocks.pk),
"country": COUNTRY_CODE,
+ "channel": channel_USD.slug,
}
response = api_client.post_graphql(QUERY_VARIANT_AVAILABILITY, variables)
content = get_graphql_content(response)
@@ -107,11 +50,12 @@ def test_variant_quantity_available_with_country_code(
def test_variant_quantity_available_with_null_as_country_code(
- api_client, variant_with_many_stocks
+ api_client, variant_with_many_stocks, channel_USD
):
variables = {
"id": graphene.Node.to_global_id("ProductVariant", variant_with_many_stocks.pk),
"country": None,
+ "channel": channel_USD.slug,
}
response = api_client.post_graphql(QUERY_VARIANT_AVAILABILITY, variables)
content = get_graphql_content(response)
@@ -121,7 +65,7 @@ def test_variant_quantity_available_with_null_as_country_code(
@override_settings(MAX_CHECKOUT_LINE_QUANTITY=15)
def test_variant_quantity_available_with_max(
- api_client, variant_with_many_stocks, settings
+ api_client, variant_with_many_stocks, settings, channel_USD
):
stock = variant_with_many_stocks.stocks.first()
stock.quantity = 16
@@ -129,6 +73,7 @@ def test_variant_quantity_available_with_max(
variables = {
"id": graphene.Node.to_global_id("ProductVariant", variant_with_many_stocks.pk),
"country": COUNTRY_CODE,
+ "channel": channel_USD.slug,
}
response = api_client.post_graphql(QUERY_VARIANT_AVAILABILITY, variables)
content = get_graphql_content(response)
@@ -137,12 +82,13 @@ def test_variant_quantity_available_with_max(
def test_variant_quantity_available_without_stocks(
- api_client, variant_with_many_stocks,
+ api_client, variant_with_many_stocks, channel_USD
):
variant_with_many_stocks.stocks.all().delete()
variables = {
"id": graphene.Node.to_global_id("ProductVariant", variant_with_many_stocks.pk),
"country": COUNTRY_CODE,
+ "channel": channel_USD.slug,
}
response = api_client.post_graphql(QUERY_VARIANT_AVAILABILITY, variables)
content = get_graphql_content(response)
@@ -155,10 +101,12 @@ def test_variant_quantity_available_with_allocations(
variant_with_many_stocks,
order_line_with_allocation_in_many_stocks,
order_line_with_one_allocation,
+ channel_USD,
):
variables = {
"id": graphene.Node.to_global_id("ProductVariant", variant_with_many_stocks.pk),
"country": COUNTRY_CODE,
+ "channel": channel_USD.slug,
}
response = api_client.post_graphql(QUERY_VARIANT_AVAILABILITY, variables)
content = get_graphql_content(response)
@@ -168,13 +116,14 @@ def test_variant_quantity_available_with_allocations(
@override_settings(MAX_CHECKOUT_LINE_QUANTITY=15)
def test_variant_quantity_available_without_inventory_tracking(
- api_client, variant_with_many_stocks, settings
+ api_client, variant_with_many_stocks, settings, channel_USD
):
variant_with_many_stocks.track_inventory = False
variant_with_many_stocks.save(update_fields=["track_inventory"])
variables = {
"id": graphene.Node.to_global_id("ProductVariant", variant_with_many_stocks.pk),
"country": COUNTRY_CODE,
+ "channel": channel_USD.slug,
}
response = api_client.post_graphql(QUERY_VARIANT_AVAILABILITY, variables)
content = get_graphql_content(response)
@@ -184,13 +133,14 @@ def test_variant_quantity_available_without_inventory_tracking(
@override_settings(MAX_CHECKOUT_LINE_QUANTITY=15)
def test_variant_quantity_available_without_inventory_tracking_and_stocks(
- api_client, variant, settings
+ api_client, variant, settings, channel_USD
):
variant.track_inventory = False
variant.save(update_fields=["track_inventory"])
variables = {
"id": graphene.Node.to_global_id("ProductVariant", variant.pk),
"country": COUNTRY_CODE,
+ "channel": channel_USD.slug,
}
response = api_client.post_graphql(QUERY_VARIANT_AVAILABILITY, variables)
content = get_graphql_content(response)
diff --git a/saleor/graphql/product/tests/test_variant_channel_listing_update.py b/saleor/graphql/product/tests/test_variant_channel_listing_update.py
new file mode 100644
index 0000000000..588f0122c1
--- /dev/null
+++ b/saleor/graphql/product/tests/test_variant_channel_listing_update.py
@@ -0,0 +1,481 @@
+from unittest.mock import patch
+
+import graphene
+
+from ....product.error_codes import ProductErrorCode
+from ....product.models import ProductChannelListing
+from ...tests.utils import (
+ assert_negative_positive_decimal_value,
+ assert_no_permission,
+ get_graphql_content,
+)
+
+PRODUCT_VARIANT_CHANNEL_LISTING_UPDATE_MUTATION = """
+mutation UpdateProductVariantChannelListing(
+ $id: ID!,
+ $input: [ProductVariantChannelListingAddInput!]!
+) {
+ productVariantChannelListingUpdate(id: $id, input: $input) {
+ productChannelListingErrors {
+ field
+ message
+ code
+ channels
+ }
+ variant {
+ id
+ channelListings {
+ channel {
+ id
+ slug
+ currencyCode
+ }
+ price {
+ amount
+ currency
+ }
+ costPrice {
+ amount
+ currency
+ }
+ margin
+ }
+ }
+ }
+}
+"""
+
+
+def test_variant_channel_listing_update_duplicated_channel(
+ staff_api_client, product, permission_manage_products, channel_USD
+):
+ # given
+ variant = product.variants.get()
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": variant_id,
+ "input": [
+ {"channelId": channel_id, "price": 1},
+ {"channelId": channel_id, "price": 2},
+ ],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ errors = content["data"]["productVariantChannelListingUpdate"][
+ "productChannelListingErrors"
+ ]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "channelId"
+ assert errors[0]["code"] == ProductErrorCode.DUPLICATED_INPUT_ITEM.name
+ assert errors[0]["channels"] == [channel_id]
+
+
+def test_variant_channel_listing_update_with_empty_input(
+ staff_api_client, product, permission_manage_products
+):
+ # given
+ variant = product.variants.get()
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ variables = {
+ "id": variant_id,
+ "input": [],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ errors = content["data"]["productVariantChannelListingUpdate"][
+ "productChannelListingErrors"
+ ]
+ assert not errors
+
+
+def test_variant_channel_listing_update_not_assigned_channel(
+ staff_api_client, product, permission_manage_products, channel_PLN
+):
+ # given
+ variant = product.variants.get()
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ variables = {
+ "id": variant_id,
+ "input": [{"channelId": channel_id, "price": 1}],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ errors = content["data"]["productVariantChannelListingUpdate"][
+ "productChannelListingErrors"
+ ]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "input"
+ assert errors[0]["code"] == ProductErrorCode.PRODUCT_NOT_ASSIGNED_TO_CHANNEL.name
+ assert errors[0]["channels"] == [channel_id]
+
+
+def test_variant_channel_listing_update_negative_price(
+ staff_api_client, product, permission_manage_products, channel_USD
+):
+ # given
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ variant = product.variants.get()
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": variant_id,
+ "input": [{"channelId": channel_id, "price": -1}],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_CHANNEL_LISTING_UPDATE_MUTATION, variables=variables
+ )
+
+ # then
+ assert_negative_positive_decimal_value(response)
+
+
+def test_variant_channel_listing_update_with_too_many_decimal_places_in_price(
+ staff_api_client, product, permission_manage_products, channel_USD
+):
+ # given
+ variant = product.variants.get()
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": variant_id,
+ "input": [{"channelId": channel_id, "price": 1.1234}],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ error = content["data"]["productVariantChannelListingUpdate"][
+ "productChannelListingErrors"
+ ][0]
+ assert error["field"] == "price"
+ assert error["code"] == ProductErrorCode.INVALID.name
+
+
+def test_variant_channel_listing_update_as_staff_user(
+ staff_api_client, product, permission_manage_products, channel_USD, channel_PLN
+):
+ # given
+ ProductChannelListing.objects.create(
+ product=product, channel=channel_PLN, is_published=True,
+ )
+ variant = product.variants.get()
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ channel_usd_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ channel_pln_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ price = 1
+ second_price = 20
+ variables = {
+ "id": variant_id,
+ "input": [
+ {"channelId": channel_usd_id, "price": price, "costPrice": price},
+ {
+ "channelId": channel_pln_id,
+ "price": second_price,
+ "costPrice": second_price,
+ },
+ ],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["productVariantChannelListingUpdate"]
+ variant_data = data["variant"]
+ assert not data["productChannelListingErrors"]
+ assert variant_data["id"] == variant_id
+ assert variant_data["channelListings"][0]["price"]["currency"] == "USD"
+ assert variant_data["channelListings"][0]["price"]["amount"] == price
+ assert variant_data["channelListings"][0]["costPrice"]["amount"] == price
+ assert variant_data["channelListings"][0]["channel"]["slug"] == channel_USD.slug
+ assert variant_data["channelListings"][1]["price"]["currency"] == "PLN"
+ assert variant_data["channelListings"][1]["price"]["amount"] == second_price
+ assert variant_data["channelListings"][1]["costPrice"]["amount"] == second_price
+ assert variant_data["channelListings"][1]["channel"]["slug"] == channel_PLN.slug
+
+
+@patch("saleor.plugins.manager.PluginsManager.product_updated")
+def test_variant_channel_listing_update_trigger_webhook_product_updated(
+ mock_product_updated,
+ staff_api_client,
+ product,
+ permission_manage_products,
+ channel_USD,
+ channel_PLN,
+):
+ # given
+ ProductChannelListing.objects.create(
+ product=product, channel=channel_PLN, is_published=True,
+ )
+ variant = product.variants.get()
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ channel_usd_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ channel_pln_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ price = 1
+ second_price = 20
+ variables = {
+ "id": variant_id,
+ "input": [
+ {"channelId": channel_usd_id, "price": price, "costPrice": price},
+ {
+ "channelId": channel_pln_id,
+ "price": second_price,
+ "costPrice": second_price,
+ },
+ ],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ get_graphql_content(response)
+
+ # then
+ mock_product_updated.assert_called_once_with(product)
+
+
+def test_variant_channel_listing_update_as_app(
+ app_api_client, product, permission_manage_products, channel_USD, channel_PLN
+):
+ # given
+ ProductChannelListing.objects.create(
+ product=product, channel=channel_PLN, is_published=True,
+ )
+ variant = product.variants.get()
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ channel_usd_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ channel_pln_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ variables = {
+ "id": variant_id,
+ "input": [
+ {"channelId": channel_usd_id, "price": 1},
+ {"channelId": channel_pln_id, "price": 20},
+ ],
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ PRODUCT_VARIANT_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["productVariantChannelListingUpdate"]
+ variant_data = data["variant"]
+ assert not data["productChannelListingErrors"]
+ assert variant_data["id"] == variant_id
+ assert variant_data["channelListings"][0]["price"]["currency"] == "USD"
+ assert variant_data["channelListings"][0]["price"]["amount"] == 1
+ assert variant_data["channelListings"][0]["channel"]["slug"] == channel_USD.slug
+ assert variant_data["channelListings"][1]["price"]["currency"] == "PLN"
+ assert variant_data["channelListings"][1]["price"]["amount"] == 20
+ assert variant_data["channelListings"][1]["channel"]["slug"] == channel_PLN.slug
+
+
+def test_variant_channel_listing_update_as_customer(
+ user_api_client, product, channel_USD, channel_PLN
+):
+ # given
+ ProductChannelListing.objects.create(
+ product=product, channel=channel_PLN, is_published=True,
+ )
+ variant = product.variants.get()
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ channel_usd_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ channel_pln_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ variables = {
+ "id": variant_id,
+ "input": [
+ {"channelId": channel_usd_id, "price": 1},
+ {"channelId": channel_pln_id, "price": 20},
+ ],
+ }
+
+ # when
+ response = user_api_client.post_graphql(
+ PRODUCT_VARIANT_CHANNEL_LISTING_UPDATE_MUTATION, variables=variables,
+ )
+
+ # then
+ assert_no_permission(response)
+
+
+def test_variant_channel_listing_update_as_anonymous(
+ api_client, product, channel_USD, channel_PLN
+):
+ # given
+ ProductChannelListing.objects.create(
+ product=product, channel=channel_PLN, is_published=True,
+ )
+ variant = product.variants.get()
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ channel_usd_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ channel_pln_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ variables = {
+ "id": variant_id,
+ "input": [
+ {"channelId": channel_usd_id, "price": 1},
+ {"channelId": channel_pln_id, "price": 20},
+ ],
+ }
+
+ # when
+ response = api_client.post_graphql(
+ PRODUCT_VARIANT_CHANNEL_LISTING_UPDATE_MUTATION, variables=variables,
+ )
+
+ # then
+ assert_no_permission(response)
+
+
+@patch("saleor.graphql.product.mutations.channels.update_product_discounted_price_task")
+def test_product_variant_channel_listing_update_updates_discounted_price(
+ mock_update_product_discounted_price_task,
+ staff_api_client,
+ product,
+ permission_manage_products,
+ channel_USD,
+):
+ query = PRODUCT_VARIANT_CHANNEL_LISTING_UPDATE_MUTATION
+ variant = product.variants.get()
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+
+ variables = {
+ "id": variant_id,
+ "input": [{"channelId": channel_id, "price": "1.99"}],
+ }
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+ assert response.status_code == 200
+
+ content = get_graphql_content(response)
+ data = content["data"]["productVariantChannelListingUpdate"]
+ assert data["productChannelListingErrors"] == []
+
+ mock_update_product_discounted_price_task.delay.assert_called_once_with(product.pk)
+
+
+def test_product_variant_channel_listing_update_remove_cost_price(
+ staff_api_client, product, permission_manage_products, channel_USD,
+):
+ # given
+ query = PRODUCT_VARIANT_CHANNEL_LISTING_UPDATE_MUTATION
+ variant = product.variants.get()
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": variant_id,
+ "input": [{"channelId": channel_id, "price": 1, "costPrice": None}],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["productVariantChannelListingUpdate"]
+ variant_data = data["variant"]
+ assert not data["productChannelListingErrors"]
+ assert variant_data["id"] == variant_id
+ assert variant_data["channelListings"][0]["price"]["currency"] == "USD"
+ assert variant_data["channelListings"][0]["price"]["amount"] == 1
+ assert not variant_data["channelListings"][0]["costPrice"]
+ assert variant_data["channelListings"][0]["channel"]["slug"] == channel_USD.slug
+
+
+def test_product_channel_listing_update_too_many_decimal_places_in_cost_price(
+ app_api_client, product, permission_manage_products, channel_USD
+):
+ # given
+ variant = product.variants.get()
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ channel_usd_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": variant_id,
+ "input": [{"channelId": channel_usd_id, "costPrice": 1.03321, "price": 1}],
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ PRODUCT_VARIANT_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_products,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["productVariantChannelListingUpdate"]
+ assert data["productChannelListingErrors"][0]["field"] == "costPrice"
+ assert (
+ data["productChannelListingErrors"][0]["code"] == ProductErrorCode.INVALID.name
+ )
+
+
+def test_product_channel_listing_update_invalid_cost_price(
+ staff_api_client, product, permission_manage_products, channel_USD
+):
+ # given
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ variant = product.variants.get()
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ variables = {
+ "id": variant_id,
+ "input": [{"channelId": channel_id, "costPrice": -1, "price": 1}],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_CHANNEL_LISTING_UPDATE_MUTATION, variables=variables
+ )
+
+ # then
+ assert_negative_positive_decimal_value(response)
diff --git a/saleor/graphql/product/tests/test_variant_pricing.py b/saleor/graphql/product/tests/test_variant_pricing.py
index e516defa51..0edf3ee880 100644
--- a/saleor/graphql/product/tests/test_variant_pricing.py
+++ b/saleor/graphql/product/tests/test_variant_pricing.py
@@ -8,8 +8,8 @@ from ....product.utils.availability import get_variant_availability
from ...tests.utils import get_graphql_content
QUERY_GET_VARIANT_PRICING = """
-query {
- products(first: 1) {
+query ($channel: String) {
+ products(first: 1, channel: $channel) {
edges {
node {
variants {
@@ -46,11 +46,14 @@ query {
"""
-def test_get_variant_pricing_on_sale(api_client, sale, product):
- price = product.variants.first().price
- discounted_price = price.amount - sale.value
+def test_get_variant_pricing_on_sale(api_client, sale, product, channel_USD):
+ price = product.variants.first().channel_listings.get().price
+ sale_discounted_value = sale.channel_listings.get().discount_value
+ discounted_price = price.amount - sale_discounted_value
- response = api_client.post_graphql(QUERY_GET_VARIANT_PRICING, {})
+ response = api_client.post_graphql(
+ QUERY_GET_VARIANT_PRICING, {"channel": channel_USD.slug}
+ )
content = get_graphql_content(response)
pricing = content["data"]["products"]["edges"][0]["node"]["variants"][0]["pricing"]
@@ -74,10 +77,12 @@ def test_get_variant_pricing_on_sale(api_client, sale, product):
assert pricing["price"]["net"]["amount"] == discounted_price
-def test_get_variant_pricing_not_on_sale(api_client, product):
- price = product.variants.first().price
+def test_get_variant_pricing_not_on_sale(api_client, product, channel_USD):
+ price = product.variants.first().channel_listings.get().price
- response = api_client.post_graphql(QUERY_GET_VARIANT_PRICING, {})
+ response = api_client.post_graphql(
+ QUERY_GET_VARIANT_PRICING, {"channel": channel_USD.slug}
+ )
content = get_graphql_content(response)
pricing = content["data"]["products"]["edges"][0]["node"]["variants"][0]["pricing"]
@@ -100,14 +105,26 @@ def test_get_variant_pricing_not_on_sale(api_client, product):
assert pricing["price"]["net"]["amount"] == price.amount
-def test_variant_pricing(variant: ProductVariant, monkeypatch, settings, stock):
+def test_variant_pricing(
+ variant: ProductVariant, monkeypatch, settings, stock, channel_USD
+):
taxed_price = TaxedMoney(Money("10.0", "USD"), Money("12.30", "USD"))
monkeypatch.setattr(
PluginsManager, "apply_taxes_to_product", Mock(return_value=taxed_price)
)
+ product = variant.product
+ product_channel_listing = product.channel_listings.get()
+ variant_channel_listing = variant.channel_listings.get()
+
pricing = get_variant_availability(
- variant=variant, product=variant.product, collections=[], discounts=[]
+ variant=variant,
+ variant_channel_listing=variant_channel_listing,
+ product=product,
+ product_channel_listing=product_channel_listing,
+ collections=[],
+ discounts=[],
+ channel=channel_USD,
)
assert pricing.price == taxed_price
assert pricing.price_local_currency is None
@@ -122,16 +139,25 @@ def test_variant_pricing(variant: ProductVariant, monkeypatch, settings, stock):
pricing = get_variant_availability(
variant=variant,
- product=variant.product,
+ variant_channel_listing=variant_channel_listing,
+ product=product,
+ product_channel_listing=product_channel_listing,
collections=[],
discounts=[],
+ channel=channel_USD,
local_currency="PLN",
country="US",
)
assert pricing.price_local_currency.currency == "PLN" # type: ignore
pricing = get_variant_availability(
- variant=variant, product=variant.product, collections=[], discounts=[]
+ variant=variant,
+ variant_channel_listing=variant_channel_listing,
+ product=product,
+ product_channel_listing=product_channel_listing,
+ collections=[],
+ discounts=[],
+ channel=channel_USD,
)
assert pricing.price.tax.amount
assert pricing.price_undiscounted.tax.amount
diff --git a/saleor/graphql/product/tests/test_variant_query.py b/saleor/graphql/product/tests/test_variant_query.py
index c3bcb7278a..09fe935329 100644
--- a/saleor/graphql/product/tests/test_variant_query.py
+++ b/saleor/graphql/product/tests/test_variant_query.py
@@ -3,8 +3,8 @@ import graphene
from ...tests.utils import assert_graphql_error_with_message, get_graphql_content
VARIANT_QUERY = """
-query variant($id: ID, $sku: String){
- productVariant(id:$id, sku:$sku){
+query variant($id: ID, $sku: String, $channel: String){
+ productVariant(id: $id, sku: $sku, channel: $channel){
sku
}
}
@@ -90,12 +90,12 @@ def test_get_unpublished_variant_by_id_as_app(
def test_get_unpublished_variant_by_id_as_customer(
- user_api_client, unavailable_product_with_variant
+ user_api_client, unavailable_product_with_variant, channel_USD
):
# given
variant = unavailable_product_with_variant.variants.first()
variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
- variables = {"id": variant_id}
+ variables = {"id": variant_id, "channel": channel_USD.slug}
# when
response = user_api_client.post_graphql(
@@ -108,12 +108,12 @@ def test_get_unpublished_variant_by_id_as_customer(
def test_get_unpublished_variant_by_id_as_anonymous_user(
- api_client, unavailable_product_with_variant
+ api_client, unavailable_product_with_variant, channel_USD
):
# given
variant = unavailable_product_with_variant.variants.first()
variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
- variables = {"id": variant_id}
+ variables = {"id": variant_id, "channel": channel_USD.slug}
# when
response = api_client.post_graphql(
@@ -165,10 +165,10 @@ def test_get_variant_by_id_as_app(app_api_client, permission_manage_products, va
assert data["sku"] == variant.sku
-def test_get_variant_by_id_as_customer(user_api_client, variant):
+def test_get_variant_by_id_as_customer(user_api_client, variant, channel_USD):
# given
variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
- variables = {"id": variant_id}
+ variables = {"id": variant_id, "channel": channel_USD.slug}
# when
response = user_api_client.post_graphql(
@@ -181,10 +181,10 @@ def test_get_variant_by_id_as_customer(user_api_client, variant):
assert data["sku"] == variant.sku
-def test_get_variant_by_id_as_anonymous_user(api_client, variant):
+def test_get_variant_by_id_as_anonymous_user(api_client, variant, channel_USD):
# given
variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
- variables = {"id": variant_id}
+ variables = {"id": variant_id, "channel": channel_USD.slug}
# when
response = api_client.post_graphql(
@@ -240,11 +240,11 @@ def test_get_unpublished_variant_by_sku_as_app(
def test_get_unpublished_variant_by_sku_as_customer(
- user_api_client, unavailable_product_with_variant
+ user_api_client, unavailable_product_with_variant, channel_USD
):
# given
variant = unavailable_product_with_variant.variants.first()
- variables = {"sku": variant.sku}
+ variables = {"sku": variant.sku, "channel": channel_USD.slug}
# when
response = user_api_client.post_graphql(
@@ -257,11 +257,11 @@ def test_get_unpublished_variant_by_sku_as_customer(
def test_get_unpublished_variant_by_sku_as_anonymous_user(
- api_client, unavailable_product_with_variant
+ api_client, unavailable_product_with_variant, channel_USD
):
# given
variant = unavailable_product_with_variant.variants.first()
- variables = {"sku": variant.sku}
+ variables = {"sku": variant.sku, "channel": channel_USD.slug}
# when
response = api_client.post_graphql(
@@ -311,9 +311,9 @@ def test_get_variant_by_sku_as_app(app_api_client, permission_manage_products, v
assert data["sku"] == variant.sku
-def test_get_variant_by_sku_as_customer(user_api_client, variant):
+def test_get_variant_by_sku_as_customer(user_api_client, variant, channel_USD):
# given
- variables = {"sku": variant.sku}
+ variables = {"sku": variant.sku, "channel": channel_USD.slug}
# when
response = user_api_client.post_graphql(
@@ -326,9 +326,9 @@ def test_get_variant_by_sku_as_customer(user_api_client, variant):
assert data["sku"] == variant.sku
-def test_get_variant_by_sku_as_anonymous_user(api_client, variant):
+def test_get_variant_by_sku_as_anonymous_user(api_client, variant, channel_USD):
# given
- variables = {"sku": variant.sku}
+ variables = {"sku": variant.sku, "channel": channel_USD.slug}
# when
response = api_client.post_graphql(
diff --git a/saleor/graphql/product/tests/test_variant_with_filtering.py b/saleor/graphql/product/tests/test_variant_with_filtering.py
index a11ac35bbd..c47643f958 100644
--- a/saleor/graphql/product/tests/test_variant_with_filtering.py
+++ b/saleor/graphql/product/tests/test_variant_with_filtering.py
@@ -1,5 +1,3 @@
-from decimal import Decimal
-
import pytest
from ....product.models import Product, ProductVariant
@@ -57,16 +55,12 @@ def products_for_variant_filtering(product_type, category):
)
ProductVariant.objects.bulk_create(
[
- ProductVariant(product=products[0], sku="P1-V1", price_amount=Decimal(15),),
- ProductVariant(product=products[0], sku="P1-V2", price_amount=Decimal(15),),
- ProductVariant(
- product=products[1], sku="PP1-V1", price_amount=Decimal(15), name="XL"
- ),
- ProductVariant(
- product=products[2], sku="PP2-V1", price_amount=Decimal(15), name="XXL"
- ),
- ProductVariant(product=products[3], sku="P2-V1", price_amount=Decimal(15),),
- ProductVariant(product=products[4], sku="P3-V1", price_amount=Decimal(15),),
+ ProductVariant(product=products[0], sku="P1-V1",),
+ ProductVariant(product=products[0], sku="P1-V2",),
+ ProductVariant(product=products[1], sku="PP1-V1", name="XL"),
+ ProductVariant(product=products[2], sku="PP2-V1", name="XXL"),
+ ProductVariant(product=products[3], sku="P2-V1",),
+ ProductVariant(product=products[4], sku="P3-V1",),
]
)
return products
diff --git a/saleor/graphql/product/types/channels.py b/saleor/graphql/product/types/channels.py
new file mode 100644
index 0000000000..34e92cf016
--- /dev/null
+++ b/saleor/graphql/product/types/channels.py
@@ -0,0 +1,159 @@
+import graphene
+
+from ....core.permissions import ProductPermissions
+from ....graphql.core.types import Money, MoneyRange
+from ....product import models
+from ....product.utils.costs import (
+ get_margin_for_variant_channel_listing,
+ get_product_costs_data,
+)
+from ...channel.dataloaders import ChannelByIdLoader
+from ...core.connection import CountableDjangoObjectType
+from ...decorators import permission_required
+from ...product.dataloaders import (
+ ProductVariantsByProductIdLoader,
+ VariantChannelListingByVariantIdAndChannelSlugLoader,
+)
+
+
+class Margin(graphene.ObjectType):
+ start = graphene.Int()
+ stop = graphene.Int()
+
+
+class ProductChannelListing(CountableDjangoObjectType):
+ discounted_price = graphene.Field(
+ Money, description="The price of the cheapest variant (including discounts)."
+ )
+ purchase_cost = graphene.Field(MoneyRange, description="Purchase cost of product.")
+ margin = graphene.Field(Margin, description="Range of margin percentage value.")
+ is_available_for_purchase = graphene.Boolean(
+ description="Whether the product is available for purchase."
+ )
+
+ class Meta:
+ description = "Represents product channel listing."
+ model = models.ProductChannelListing
+ interfaces = [graphene.relay.Node]
+ only_fields = [
+ "id",
+ "channel",
+ "is_published",
+ "publication_date",
+ "visible_in_listings",
+ "available_for_purchase",
+ ]
+
+ @staticmethod
+ def resolve_channel(root: models.ProductChannelListing, info, **_kwargs):
+ return ChannelByIdLoader(info.context).load(root.channel_id)
+
+ @staticmethod
+ @permission_required(ProductPermissions.MANAGE_PRODUCTS)
+ def resolve_purchase_cost(root: models.ProductChannelListing, info, *_kwargs):
+ channel = ChannelByIdLoader(info.context).load(root.channel_id)
+
+ def calculate_margin_with_variants(variants):
+ def calculate_margin_with_channel(channel):
+ def calculate_margin_with_channel_listings(variant_channel_listings):
+ variant_channel_listings = list(
+ filter(None, variant_channel_listings)
+ )
+ if not variant_channel_listings:
+ return None
+
+ has_variants = True if len(variant_ids_channel_slug) > 0 else False
+ purchase_cost, _margin = get_product_costs_data(
+ variant_channel_listings, has_variants, root.currency
+ )
+ return purchase_cost
+
+ variant_ids_channel_slug = [
+ (variant.id, channel.slug) for variant in variants
+ ]
+ return (
+ VariantChannelListingByVariantIdAndChannelSlugLoader(info.context)
+ .load_many(variant_ids_channel_slug)
+ .then(calculate_margin_with_channel_listings)
+ )
+
+ return channel.then(calculate_margin_with_channel)
+
+ return (
+ ProductVariantsByProductIdLoader(info.context)
+ .load(root.product_id)
+ .then(calculate_margin_with_variants)
+ )
+
+ @staticmethod
+ @permission_required(ProductPermissions.MANAGE_PRODUCTS)
+ def resolve_margin(root: models.ProductChannelListing, info, *_kwargs):
+ channel = ChannelByIdLoader(info.context).load(root.channel_id)
+
+ def calculate_margin_with_variants(variants):
+ def calculate_margin_with_channel(channel):
+ def calculate_margin_with_channel_listings(variant_channel_listings):
+ variant_channel_listings = list(
+ filter(None, variant_channel_listings)
+ )
+ if not variant_channel_listings:
+ return None
+
+ has_variants = True if len(variant_ids_channel_slug) > 0 else False
+ _purchase_cost, margin = get_product_costs_data(
+ variant_channel_listings, has_variants, root.currency
+ )
+ return Margin(margin[0], margin[1])
+
+ variant_ids_channel_slug = [
+ (variant.id, channel.slug) for variant in variants
+ ]
+ return (
+ VariantChannelListingByVariantIdAndChannelSlugLoader(info.context)
+ .load_many(variant_ids_channel_slug)
+ .then(calculate_margin_with_channel_listings)
+ )
+
+ return channel.then(calculate_margin_with_channel)
+
+ return (
+ ProductVariantsByProductIdLoader(info.context)
+ .load(root.product_id)
+ .then(calculate_margin_with_variants)
+ )
+
+ @staticmethod
+ def resolve_is_available_for_purchase(root: models.ProductChannelListing, _info):
+ return root.is_available_for_purchase()
+
+
+class ProductVariantChannelListing(CountableDjangoObjectType):
+ cost_price = graphene.Field(Money, description="Cost price of the variant.")
+ margin = graphene.Int(description="Gross margin percentage value.")
+
+ class Meta:
+ description = "Represents product varaint channel listing."
+ model = models.ProductVariantChannelListing
+ interfaces = [graphene.relay.Node]
+ only_fields = ["id", "channel", "price", "cost_price"]
+
+ @staticmethod
+ def resolve_channel(root: models.ProductVariantChannelListing, info, **_kwargs):
+ return ChannelByIdLoader(info.context).load(root.channel_id)
+
+ @staticmethod
+ @permission_required(ProductPermissions.MANAGE_PRODUCTS)
+ def resolve_margin(root: models.ProductVariantChannelListing, *_args):
+ return get_margin_for_variant_channel_listing(root)
+
+
+class CollectionChannelListing(CountableDjangoObjectType):
+ class Meta:
+ description = "Represents collection channel listing."
+ model = models.CollectionChannelListing
+ interfaces = [graphene.relay.Node]
+ only_fields = ["id", "channel", "is_published", "publication_date"]
+
+ @staticmethod
+ def resolve_channel(root: models.ProductChannelListing, info, **_kwargs):
+ return ChannelByIdLoader(info.context).load(root.channel_id)
diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.py
index 3549e74031..05f5679568 100644
--- a/saleor/graphql/product/types/products.py
+++ b/saleor/graphql/product/types/products.py
@@ -1,5 +1,4 @@
from dataclasses import asdict
-from typing import List, Union
import graphene
from django.conf import settings
@@ -19,20 +18,31 @@ from ....product.utils.availability import (
get_product_availability,
get_variant_availability,
)
-from ....product.utils.costs import get_margin_for_variant, get_product_costs_data
from ....warehouse.availability import (
get_available_quantity,
get_quantity_allocated,
is_product_in_stock,
)
from ...account.enums import CountryCodeEnum
+from ...channel import ChannelContext, ChannelQsContext
+from ...channel.dataloaders import ChannelBySlugLoader
+from ...channel.types import ChannelContextType, ChannelContextTypeWithMetadata
+from ...channel.utils import get_default_channel_slug_or_graphql_error
from ...core.connection import CountableDjangoObjectType
from ...core.enums import ReportingPeriod, TaxRateType
-from ...core.fields import FilterInputConnectionField, PrefetchingConnectionField
-from ...core.types import Image, Money, MoneyRange, TaxedMoney, TaxedMoneyRange, TaxType
+from ...core.fields import (
+ ChannelContextFilterConnectionField,
+ FilterInputConnectionField,
+ PrefetchingConnectionField,
+)
+from ...core.types import Image, Money, TaxedMoney, TaxedMoneyRange, TaxType
from ...decorators import one_of_permissions_required, permission_required
from ...discount.dataloaders import DiscountsByDateTimeLoader
from ...meta.types import ObjectWithMetadata
+from ...order.dataloaders import (
+ OrderByIdLoader,
+ OrderLinesByVariantIdAndChannelIdLoader,
+)
from ...translations.fields import TranslationField
from ...translations.types import (
CategoryTranslation,
@@ -48,80 +58,36 @@ from ...warehouse.dataloaders import (
from ...warehouse.types import Stock
from ..dataloaders import (
CategoryByIdLoader,
+ CollectionChannelListingByCollectionIdLoader,
CollectionsByProductIdLoader,
ImagesByProductIdLoader,
ImagesByProductVariantIdLoader,
ProductAttributesByProductTypeIdLoader,
ProductByIdLoader,
+ ProductChannelListingByProductIdAndChannelSlugLoader,
+ ProductChannelListingByProductIdLoader,
ProductTypeByIdLoader,
ProductVariantByIdLoader,
ProductVariantsByProductIdLoader,
SelectedAttributesByProductIdLoader,
SelectedAttributesByProductVariantIdLoader,
VariantAttributesByProductTypeIdLoader,
+ VariantChannelListingByVariantIdAndChannelSlugLoader,
+ VariantChannelListingByVariantIdLoader,
+ VariantsChannelListingByProductIdAndChanneSlugLoader,
)
from ..filters import AttributeFilterInput, ProductFilterInput
from ..resolvers import resolve_attributes
from ..sorters import ProductOrder
from .attributes import Attribute, SelectedAttribute
+from .channels import (
+ CollectionChannelListing,
+ ProductChannelListing,
+ ProductVariantChannelListing,
+)
from .digital_contents import DigitalContent
-def resolve_attribute_list(
- instance: Union[models.Product, models.ProductVariant], *, user
-) -> List[SelectedAttribute]:
- """Resolve attributes from a product into a list of `SelectedAttribute`s.
-
- Note: you have to prefetch the below M2M fields.
- - product_type -> attribute[rel] -> [rel]assignments -> values
- - product_type -> attribute[rel] -> attribute
- """
- resolved_attributes = []
- attributes_qs = None
-
- # Retrieve the product type
- if isinstance(instance, models.Product):
- product_type = instance.product_type
- product_type_attributes_assoc_field = "attributeproduct"
- assigned_attribute_instance_field = "productassignments"
- assigned_attribute_instance_filters = {"product_id": instance.pk}
- if hasattr(product_type, "storefront_attributes"):
- attributes_qs = product_type.storefront_attributes # type: ignore
- elif isinstance(instance, models.ProductVariant):
- product_type = instance.product.product_type
- product_type_attributes_assoc_field = "attributevariant"
- assigned_attribute_instance_field = "variantassignments"
- assigned_attribute_instance_filters = {"variant_id": instance.pk}
- else:
- raise AssertionError(f"{instance.__class__.__name__} is unsupported")
-
- # Retrieve all the product attributes assigned to this product type
- if not attributes_qs:
- attributes_qs = getattr(product_type, product_type_attributes_assoc_field)
- attributes_qs = attributes_qs.get_visible_to_user(user)
-
- # An empty QuerySet for unresolved values
- empty_qs = models.AttributeValue.objects.none()
-
- # Goes through all the attributes assigned to the product type
- # The assigned values are returned as a QuerySet, but will assign a
- # dummy empty QuerySet if no values are assigned to the given instance.
- for attr_data_rel in attributes_qs:
- attr_instance_data = getattr(attr_data_rel, assigned_attribute_instance_field)
-
- # Retrieve the instance's associated data
- attr_data = attr_instance_data.filter(**assigned_attribute_instance_filters)
- attr_data = attr_data.first()
-
- # Return the instance's attribute values if the assignment was found,
- # otherwise it sets the values as an empty QuerySet
- values = attr_data.values.all() if attr_data is not None else empty_qs
- resolved_attributes.append(
- SelectedAttribute(attribute=attr_data_rel.attribute, values=values)
- )
- return resolved_attributes
-
-
class Margin(graphene.ObjectType):
start = graphene.Int()
stop = graphene.Int()
@@ -177,7 +143,7 @@ class ProductPricingInfo(BasePricingInfo):
@key(fields="id")
-class ProductVariant(CountableDjangoObjectType):
+class ProductVariant(ChannelContextTypeWithMetadata, CountableDjangoObjectType):
quantity = graphene.Int(
required=True,
description="Quantity of a product available for sale.",
@@ -200,15 +166,10 @@ class ProductVariant(CountableDjangoObjectType):
"This field will be removed after 2020-07-31."
),
)
- price = graphene.Field(
- Money,
- description=(
- "Base price of a product variant. "
- "This field is restricted for admins. "
- "Use the pricing field to get the public price for customers."
- ),
+ channel_listings = graphene.List(
+ graphene.NonNull(ProductVariantChannelListing),
+ description="List of price information in channels for the product.",
)
-
pricing = graphene.Field(
VariantPricingInfo,
description=(
@@ -222,7 +183,6 @@ class ProductVariant(CountableDjangoObjectType):
"Use the stock field instead. This field will be removed after 2020-07-31."
),
)
-
attributes = graphene.List(
graphene.NonNull(SelectedAttribute),
required=True,
@@ -244,7 +204,9 @@ class ProductVariant(CountableDjangoObjectType):
lambda: ProductImage, description="List of images for the product variant."
)
translation = TranslationField(
- ProductVariantTranslation, type_name="product variant"
+ ProductVariantTranslation,
+ type_name="product variant",
+ resolver=ChannelContextType.resolve_translation,
)
digital_content = graphene.Field(
DigitalContent, description="Digital content for the product variant."
@@ -273,6 +235,7 @@ class ProductVariant(CountableDjangoObjectType):
)
class Meta:
+ default_resolver = ChannelContextType.resolver_with_context
description = (
"Represents a version of a product such as different size or color."
)
@@ -284,78 +247,104 @@ class ProductVariant(CountableDjangoObjectType):
@one_of_permissions_required(
[ProductPermissions.MANAGE_PRODUCTS, OrderPermissions.MANAGE_ORDERS]
)
- def resolve_stocks(root: models.ProductVariant, info, country_code=None):
+ def resolve_stocks(
+ root: ChannelContext[models.ProductVariant], info, country_code=None
+ ):
if not country_code:
- return root.stocks.annotate_available_quantity()
- return root.stocks.for_country(country_code).annotate_available_quantity()
+ return root.node.stocks.annotate_available_quantity()
+ return root.node.stocks.for_country(country_code).annotate_available_quantity()
@staticmethod
def resolve_quantity_available(
- root: models.ProductVariant, info, country_code=None
+ root: ChannelContext[models.ProductVariant], info, country_code=None
):
- if not root.track_inventory:
+ if not root.node.track_inventory:
return settings.MAX_CHECKOUT_LINE_QUANTITY
return AvailableQuantityByProductVariantIdAndCountryCodeLoader(
info.context
- ).load((root.id, country_code))
+ ).load((root.node.id, country_code))
@staticmethod
@permission_required(ProductPermissions.MANAGE_PRODUCTS)
- def resolve_digital_content(root: models.ProductVariant, *_args):
- return getattr(root, "digital_content", None)
+ def resolve_digital_content(root: ChannelContext[models.ProductVariant], *_args):
+ return getattr(root.node, "digital_content", None)
@staticmethod
- def resolve_stock_quantity(root: models.ProductVariant, info):
- if not root.track_inventory:
+ def resolve_stock_quantity(root: ChannelContext[models.ProductVariant], info):
+ if not root.node.track_inventory:
return settings.MAX_CHECKOUT_LINE_QUANTITY
return AvailableQuantityByProductVariantIdAndCountryCodeLoader(
info.context
- ).load((root.id, info.context.country))
-
- @staticmethod
- def resolve_attributes(root: models.ProductVariant, info):
- return SelectedAttributesByProductVariantIdLoader(info.context).load(root.id)
+ ).load((root.node.id, info.context.country))
@staticmethod
- @permission_required(ProductPermissions.MANAGE_PRODUCTS)
- def resolve_margin(root: models.ProductVariant, *_args):
- return get_margin_for_variant(root)
+ def resolve_attributes(root: ChannelContext[models.ProductVariant], info):
+ return SelectedAttributesByProductVariantIdLoader(info.context).load(
+ root.node.id
+ )
@staticmethod
@permission_required(ProductPermissions.MANAGE_PRODUCTS)
- def resolve_cost_price(root: models.ProductVariant, *_args):
- return root.cost_price
+ def resolve_channel_listings(
+ root: ChannelContext[models.ProductVariant], info, **_kwargs
+ ):
+ return VariantChannelListingByVariantIdLoader(info.context).load(root.node.id)
@staticmethod
- @permission_required(ProductPermissions.MANAGE_PRODUCTS)
- def resolve_price(root: models.ProductVariant, *_args):
- return root.price
+ def resolve_pricing(root: ChannelContext[models.ProductVariant], info):
+ if not root.channel_slug:
+ return None
- @staticmethod
- def resolve_pricing(root: models.ProductVariant, info):
context = info.context
- product = ProductByIdLoader(context).load(root.product_id)
- collections = CollectionsByProductIdLoader(context).load(root.product_id)
+ product = ProductByIdLoader(context).load(root.node.product_id)
+ product_channel_listing = ProductChannelListingByProductIdAndChannelSlugLoader(
+ context
+ ).load((root.node.product_id, root.channel_slug))
+ variant_channel_listing = VariantChannelListingByVariantIdAndChannelSlugLoader(
+ context
+ ).load((root.node.id, root.channel_slug))
+ collections = CollectionsByProductIdLoader(context).load(root.node.product_id)
+ channel = ChannelBySlugLoader(context).load(root.channel_slug)
def calculate_pricing_info(discounts):
- def calculate_pricing_with_product(product):
- def calculate_pricing_with_collections(collections):
- availability = get_variant_availability(
- variant=root,
- product=product,
- collections=collections,
- discounts=discounts,
- country=context.country,
- local_currency=context.currency,
- plugins=context.plugins,
- )
- return VariantPricingInfo(**asdict(availability))
-
- return collections.then(calculate_pricing_with_collections)
-
- return product.then(calculate_pricing_with_product)
+ def calculate_pricing_with_channel(channel):
+ def calculate_pricing_with_product_variant_channel_listings(
+ variant_channel_listing,
+ ):
+ def calculate_pricing_with_product(product):
+ def calculate_pricing_with_product_channel_listings(
+ product_channel_listing,
+ ):
+ def calculate_pricing_with_collections(collections):
+ availability = get_variant_availability(
+ variant=root.node,
+ variant_channel_listing=variant_channel_listing,
+ product=product,
+ product_channel_listing=product_channel_listing,
+ collections=collections,
+ discounts=discounts,
+ channel=channel,
+ country=context.country,
+ local_currency=context.currency,
+ plugins=context.plugins,
+ )
+ return VariantPricingInfo(**asdict(availability))
+
+ return collections.then(calculate_pricing_with_collections)
+
+ return product_channel_listing.then(
+ calculate_pricing_with_product_channel_listings
+ )
+
+ return product.then(calculate_pricing_with_product)
+
+ return variant_channel_listing.then(
+ calculate_pricing_with_product_variant_channel_listings
+ )
+
+ return channel.then(calculate_pricing_with_channel)
return (
DiscountsByDateTimeLoader(context)
@@ -364,12 +353,15 @@ class ProductVariant(CountableDjangoObjectType):
)
@staticmethod
- def resolve_product(root: models.ProductVariant, info):
- return ProductByIdLoader(info.context).load(root.product_id)
+ def resolve_product(root: ChannelContext[models.ProductVariant], info):
+ product = ProductByIdLoader(info.context).load(root.node.product_id)
+ return product.then(
+ lambda product: ChannelContext(node=product, channel_slug=root.channel_slug)
+ )
@staticmethod
- def resolve_is_available(root: models.ProductVariant, info):
- if not root.track_inventory:
+ def resolve_is_available(root: ChannelContext[models.ProductVariant], info):
+ if not root.node.track_inventory:
return True
def is_variant_in_stock(available_quantity):
@@ -377,58 +369,86 @@ class ProductVariant(CountableDjangoObjectType):
return (
AvailableQuantityByProductVariantIdAndCountryCodeLoader(info.context)
- .load((root.id, info.context.country))
+ .load((root.node.id, info.context.country))
.then(is_variant_in_stock)
)
@staticmethod
@permission_required(ProductPermissions.MANAGE_PRODUCTS)
- def resolve_quantity(root: models.ProductVariant, info):
- return get_available_quantity(root, info.context.country)
+ def resolve_quantity(root: ChannelContext[models.ProductVariant], info):
+ return get_available_quantity(root.node, info.context.country)
@staticmethod
@permission_required(ProductPermissions.MANAGE_PRODUCTS)
- def resolve_quantity_ordered(root: models.ProductVariant, *_args):
+ def resolve_quantity_ordered(root: ChannelContext[models.ProductVariant], *_args):
# This field is added through annotation when using the
# `resolve_report_product_sales` resolver.
- return getattr(root, "quantity_ordered", None)
+ return getattr(root.node, "quantity_ordered", None)
@staticmethod
@permission_required(ProductPermissions.MANAGE_PRODUCTS)
- def resolve_quantity_allocated(root: models.ProductVariant, info):
+ def resolve_quantity_allocated(root: ChannelContext[models.ProductVariant], info):
country = info.context.country
- return get_quantity_allocated(root, country)
+ return get_quantity_allocated(root.node, country)
@staticmethod
@permission_required(ProductPermissions.MANAGE_PRODUCTS)
- def resolve_revenue(root: models.ProductVariant, *_args, period):
+ def resolve_revenue(root: ChannelContext[models.ProductVariant], info, period):
start_date = reporting_period_to_date(period)
- return calculate_revenue_for_variant(root, start_date)
+ variant = root.node
+ channel_slug = root.channel_slug
+
+ def calculate_revenue_with_channel(channel):
+ if not channel:
+ return None
+
+ def calculate_revenue_with_order_lines(order_lines):
+ def calculate_revenue_with_orders(orders):
+ orders_dict = {order.id: order for order in orders}
+ return calculate_revenue_for_variant(
+ variant,
+ start_date,
+ order_lines,
+ orders_dict,
+ channel.currency_code,
+ )
- @staticmethod
- def resolve_images(root: models.ProductVariant, info, *_args):
- return ImagesByProductVariantIdLoader(info.context).load(root.id)
+ order_ids = [order_line.order_id for order_line in order_lines]
+ return (
+ OrderByIdLoader(info.context)
+ .load_many(order_ids)
+ .then(calculate_revenue_with_orders)
+ )
+
+ return (
+ OrderLinesByVariantIdAndChannelIdLoader(info.context)
+ .load((variant.id, channel.id))
+ .then(calculate_revenue_with_order_lines)
+ )
- @classmethod
- def get_node(cls, info, pk):
- requestor = get_user_or_app_from_context(info.context)
- visible_products = models.Product.objects.visible_to_user(
- requestor
- ).values_list("pk", flat=True)
- qs = cls._meta.model.objects.filter(product__id__in=visible_products)
- return qs.filter(pk=pk).first()
+ return (
+ ChannelBySlugLoader(info.context)
+ .load(channel_slug)
+ .then(calculate_revenue_with_channel)
+ )
@staticmethod
- def __resolve_reference(root, _info, **_kwargs):
- return graphene.Node.get_node_from_global_id(_info, root.id)
+ def resolve_images(root: ChannelContext[models.ProductVariant], info, *_args):
+ return ImagesByProductVariantIdLoader(info.context).load(root.node.id)
@staticmethod
- def resolve_weight(root: models.ProductVariant, _info, **_kwargs):
- return convert_weight_to_default_weight_unit(root.weight)
+ def __resolve_reference(
+ root: ChannelContext[models.ProductVariant], _info, **_kwargs
+ ):
+ return graphene.Node.get_node_from_global_id(_info, root.node.id)
+
+ @staticmethod
+ def resolve_weight(root: ChannelContext[models.ProductVariant], _info, **_kwargs):
+ return convert_weight_to_default_weight_unit(root.node.weight)
@key(fields="id")
-class Product(CountableDjangoObjectType):
+class Product(ChannelContextTypeWithMetadata, CountableDjangoObjectType):
url = graphene.String(
description="The storefront URL for the product.",
required=True,
@@ -449,9 +469,6 @@ class Product(CountableDjangoObjectType):
is_available = graphene.Boolean(
description="Whether the product is in stock and visible or not."
)
- minimal_variant_price = graphene.Field(
- Money, description="The price of the cheapest variant (including discounts)."
- )
tax_type = graphene.Field(
TaxType, description="A type of tax. Assigned by enabled tax gateway"
)
@@ -460,8 +477,10 @@ class Product(CountableDjangoObjectType):
required=True,
description="List of attributes assigned to this product.",
)
- purchase_cost = graphene.Field(MoneyRange)
- margin = graphene.Field(Margin)
+ channel_listings = graphene.List(
+ graphene.NonNull(ProductChannelListing),
+ description="List of availability in channels for the product.",
+ )
image_by_id = graphene.Field(
lambda: ProductImage,
id=graphene.Argument(graphene.ID, description="ID of a product image."),
@@ -476,59 +495,69 @@ class Product(CountableDjangoObjectType):
collections = graphene.List(
lambda: Collection, description="List of collections for the product."
)
- translation = TranslationField(ProductTranslation, type_name="product")
+ translation = TranslationField(
+ ProductTranslation,
+ type_name="product",
+ resolver=ChannelContextType.resolve_translation,
+ )
+ available_for_purchase = graphene.Date(
+ description="Date when product is available for purchase. "
+ )
is_available_for_purchase = graphene.Boolean(
description="Whether the product is available for purchase."
)
class Meta:
+ default_resolver = ChannelContextType.resolver_with_context
description = "Represents an individual item for sale in the storefront."
interfaces = [relay.Node, ObjectWithMetadata]
model = models.Product
only_fields = [
- "available_for_purchase",
"category",
"charge_taxes",
"description",
"description_json",
"id",
- "is_published",
"name",
"slug",
"product_type",
- "publication_date",
"seo_description",
"seo_title",
"updated_at",
"weight",
- "visible_in_listings",
"default_variant",
"rating",
]
@staticmethod
- def resolve_default_variant(root: models.Product, info):
- default_variant_id = root.default_variant_id
+ def resolve_default_variant(root: ChannelContext[models.Product], info):
+ default_variant_id = root.node.default_variant_id
if default_variant_id is None:
return None
- return ProductVariantByIdLoader(info.context).load(root.default_variant_id)
+ def return_default_variant_with_channel_context(variant):
+ return ChannelContext(node=variant, channel_slug=root.channel_slug)
+
+ return (
+ ProductVariantByIdLoader(info.context)
+ .load(default_variant_id)
+ .then(return_default_variant_with_channel_context)
+ )
@staticmethod
- def resolve_category(root: models.Product, info):
- category_id = root.category_id
+ def resolve_category(root: ChannelContext[models.Product], info):
+ category_id = root.node.category_id
if category_id is None:
return None
-
return CategoryByIdLoader(info.context).load(category_id)
@staticmethod
- def resolve_tax_type(root: models.Product, info):
- tax_data = info.context.plugins.get_tax_code_from_object_meta(root)
+ def resolve_tax_type(root: ChannelContext[models.Product], info):
+ tax_data = info.context.plugins.get_tax_code_from_object_meta(root.node)
return TaxType(tax_code=tax_data.code, description=tax_data.description)
@staticmethod
- def resolve_thumbnail(root: models.Product, info, *, size=255):
+ def resolve_thumbnail(root: ChannelContext[models.Product], info, *, size=255):
def return_first_thumbnail(images):
image = images[0] if images else None
if image:
@@ -539,37 +568,68 @@ class Product(CountableDjangoObjectType):
return (
ImagesByProductIdLoader(info.context)
- .load(root.id)
+ .load(root.node.id)
.then(return_first_thumbnail)
)
@staticmethod
- def resolve_url(root: models.Product, *_args):
+ def resolve_url(*_args):
return ""
@staticmethod
- def resolve_pricing(root: models.Product, info):
+ def resolve_pricing(root: ChannelContext[models.Product], info):
+ if not root.channel_slug:
+ return None
+
context = info.context
- variants = ProductVariantsByProductIdLoader(context).load(root.id)
- collections = CollectionsByProductIdLoader(context).load(root.id)
+ channel_slug = root.channel_slug
+ product_channel_listing = ProductChannelListingByProductIdAndChannelSlugLoader(
+ context
+ ).load((root.node.id, channel_slug))
+ variants = ProductVariantsByProductIdLoader(context).load(root.node.id)
+ variants_channel_listing = VariantsChannelListingByProductIdAndChanneSlugLoader(
+ context
+ ).load((root.node.id, channel_slug))
+ collections = CollectionsByProductIdLoader(context).load(root.node.id)
+ channel = ChannelBySlugLoader(context).load(channel_slug)
def calculate_pricing_info(discounts):
- def calculate_pricing_with_variants(variants):
- def calculate_pricing_with_collections(collections):
- availability = get_product_availability(
- product=root,
- variants=variants,
- collections=collections,
- discounts=discounts,
- country=context.country,
- local_currency=context.currency,
- plugins=context.plugins,
- )
- return ProductPricingInfo(**asdict(availability))
-
- return collections.then(calculate_pricing_with_collections)
-
- return variants.then(calculate_pricing_with_variants)
+ def calculate_pricing_with_channel(channel):
+ def calculate_pricing_with_product_channel_listings(
+ product_channel_listing,
+ ):
+ def calculate_pricing_with_variants(variants):
+ def calculate_pricing_with_variants_channel_listings(
+ variants_channel_listing,
+ ):
+ def calculate_pricing_with_collections(collections):
+ availability = get_product_availability(
+ product=root.node,
+ product_channel_listing=product_channel_listing,
+ variants=variants,
+ variants_channel_listing=variants_channel_listing,
+ collections=collections,
+ discounts=discounts,
+ channel=channel,
+ country=context.country,
+ local_currency=context.currency,
+ plugins=context.plugins,
+ )
+ return ProductPricingInfo(**asdict(availability))
+
+ return collections.then(calculate_pricing_with_collections)
+
+ return variants_channel_listing.then(
+ calculate_pricing_with_variants_channel_listings
+ )
+
+ return variants.then(calculate_pricing_with_variants)
+
+ return product_channel_listing.then(
+ calculate_pricing_with_product_channel_listings
+ )
+
+ return channel.then(calculate_pricing_with_channel)
return (
DiscountsByDateTimeLoader(context)
@@ -578,76 +638,128 @@ class Product(CountableDjangoObjectType):
)
@staticmethod
- def resolve_is_available(root: models.Product, info):
- country = info.context.country
- in_stock = is_product_in_stock(root, country)
- return root.is_visible and in_stock
+ def resolve_is_available(root: ChannelContext[models.Product], info):
+ if not root.channel_slug:
+ return None
- @staticmethod
- def resolve_attributes(root: models.Product, info):
- return SelectedAttributesByProductIdLoader(info.context).load(root.id)
+ def calculate_is_available(product_channel_listing):
+ country = info.context.country
+ in_stock = is_product_in_stock(root.node, country)
+ is_visible = False
+ if product_channel_listing:
+ is_visible = product_channel_listing.is_available_for_purchase()
+ return is_visible and in_stock
- @staticmethod
- @permission_required(ProductPermissions.MANAGE_PRODUCTS)
- def resolve_purchase_cost(root: models.Product, *_args):
- purchase_cost, _ = get_product_costs_data(root)
- return purchase_cost
+ return (
+ ProductChannelListingByProductIdAndChannelSlugLoader(info.context)
+ .load((root.node.id, root.channel_slug))
+ .then(calculate_is_available)
+ )
@staticmethod
- @permission_required(ProductPermissions.MANAGE_PRODUCTS)
- def resolve_margin(root: models.Product, *_args):
- _, margin = get_product_costs_data(root)
- return Margin(margin[0], margin[1])
+ def resolve_attributes(root: ChannelContext[models.Product], info):
+ return SelectedAttributesByProductIdLoader(info.context).load(root.node.id)
@staticmethod
- def resolve_image_by_id(root: models.Product, info, id):
+ def resolve_image_by_id(root: ChannelContext[models.Product], info, id):
pk = get_database_id(info, id, ProductImage)
try:
- return root.images.get(pk=pk)
+ return root.node.images.get(pk=pk)
except models.ProductImage.DoesNotExist:
raise GraphQLError("Product image not found.")
@staticmethod
- def resolve_images(root: models.Product, info, **_kwargs):
- return ImagesByProductIdLoader(info.context).load(root.id)
+ def resolve_images(root: ChannelContext[models.Product], info, **_kwargs):
+ return ImagesByProductIdLoader(info.context).load(root.node.id)
@staticmethod
- def resolve_variants(root: models.Product, info, **_kwargs):
- return ProductVariantsByProductIdLoader(info.context).load(root.id)
+ def resolve_variants(root: ChannelContext[models.Product], info, **_kwargs):
+ return (
+ ProductVariantsByProductIdLoader(info.context)
+ .load(root.node.id)
+ .then(
+ lambda variants: [
+ ChannelContext(node=variant, channel_slug=root.channel_slug)
+ for variant in variants
+ ]
+ )
+ )
@staticmethod
- def resolve_collections(root: models.Product, *_args):
- return root.collections.all()
+ @permission_required(ProductPermissions.MANAGE_PRODUCTS)
+ def resolve_channel_listings(root: ChannelContext[models.Product], info, **_kwargs):
+ return ProductChannelListingByProductIdLoader(info.context).load(root.node.id)
- @classmethod
- def get_node(cls, info, pk):
- if info.context:
- requestor = get_user_or_app_from_context(info.context)
- qs = cls._meta.model.objects.visible_to_user(requestor)
- return qs.filter(pk=pk).first()
- return None
+ @staticmethod
+ @permission_required(ProductPermissions.MANAGE_PRODUCTS)
+ def resolve_collections(root: ChannelContext[models.Product], info, **_kwargs):
+ return (
+ CollectionsByProductIdLoader(info.context)
+ .load(root.node.id)
+ .then(
+ lambda collections: [
+ ChannelContext(node=collection, channel_slug=root.channel_slug)
+ for collection in collections
+ ]
+ )
+ )
@staticmethod
- def __resolve_reference(root, _info, **_kwargs):
- return graphene.Node.get_node_from_global_id(_info, root.id)
+ def __resolve_reference(root: ChannelContext[models.Product], _info, **_kwargs):
+ return graphene.Node.get_node_from_global_id(_info, root.node.id)
@staticmethod
- def resolve_weight(root: models.Product, _info, **_kwargs):
- return convert_weight_to_default_weight_unit(root.weight)
+ def resolve_weight(root: ChannelContext[models.Product], _info, **_kwargs):
+ return convert_weight_to_default_weight_unit(root.node.weight)
@staticmethod
- def resolve_is_available_for_purchase(root: models.Product, _info):
- return root.is_available_for_purchase()
+ def resolve_is_available_for_purchase(root: ChannelContext[models.Product], info):
+ if not root.channel_slug:
+ return None
+
+ def calculate_is_available_for_purchase(product_channel_listing):
+ if not product_channel_listing:
+ return None
+ return product_channel_listing.is_available_for_purchase()
+
+ return (
+ ProductChannelListingByProductIdAndChannelSlugLoader(info.context)
+ .load((root.node.id, root.channel_slug))
+ .then(calculate_is_available_for_purchase)
+ )
@staticmethod
- def resolve_product_type(root: models.Product, info):
- return ProductTypeByIdLoader(info.context).load(root.product_type_id)
+ def resolve_available_for_purchase(root: ChannelContext[models.Product], info):
+ if not root.channel_slug:
+ return None
+
+ def calculate_available_for_purchase(product_channel_listing):
+ if not product_channel_listing:
+ return None
+ return product_channel_listing.available_for_purchase
+
+ return (
+ ProductChannelListingByProductIdAndChannelSlugLoader(info.context)
+ .load((root.node.id, root.channel_slug))
+ .then(calculate_available_for_purchase)
+ )
+
+ @staticmethod
+ def resolve_product_type(root: ChannelContext[models.Product], info):
+ return ProductTypeByIdLoader(info.context).load(root.node.product_type_id)
@key(fields="id")
class ProductType(CountableDjangoObjectType):
- products = PrefetchingConnectionField(
- Product, description="List of products of this type."
+ products = ChannelContextFilterConnectionField(
+ Product,
+ channel=graphene.String(
+ description="Slug of a channel for which the data should be returned."
+ ),
+ description="List of products of this type.",
+ deprecation_reason=(
+ "Use the top-level `products` query with the `productTypes` filter."
+ ),
)
tax_rate = TaxRateType(description="A type of tax rate.")
tax_type = graphene.Field(
@@ -702,8 +814,12 @@ class ProductType(CountableDjangoObjectType):
return VariantAttributesByProductTypeIdLoader(info.context).load(root.pk)
@staticmethod
- def resolve_products(root: models.ProductType, info, **_kwargs):
- return root.products.visible_to_user(info.context.user)
+ def resolve_products(root: models.ProductType, info, channel=None, **_kwargs):
+ user = info.context.user
+ if channel is None:
+ channel = get_default_channel_slug_or_graphql_error()
+ qs = root.products.visible_to_user(user, channel)
+ return ChannelQsContext(qs=qs, channel_slug=channel)
@staticmethod
@permission_required(ProductPermissions.MANAGE_PRODUCTS)
@@ -721,8 +837,8 @@ class ProductType(CountableDjangoObjectType):
@key(fields="id")
-class Collection(CountableDjangoObjectType):
- products = FilterInputConnectionField(
+class Collection(ChannelContextTypeWithMetadata, CountableDjangoObjectType):
+ products = ChannelContextFilterConnectionField(
Product,
filter=ProductFilterInput(description="Filtering options for products."),
sort_by=ProductOrder(description="Sort products."),
@@ -731,17 +847,24 @@ class Collection(CountableDjangoObjectType):
background_image = graphene.Field(
Image, size=graphene.Int(description="Size of the image.")
)
- translation = TranslationField(CollectionTranslation, type_name="collection")
+ translation = TranslationField(
+ CollectionTranslation,
+ type_name="collection",
+ resolver=ChannelContextType.resolve_translation,
+ )
+ channel_listings = graphene.List(
+ graphene.NonNull(CollectionChannelListing),
+ description="List of channels in which the collection is available.",
+ )
class Meta:
+ default_resolver = ChannelContextType.resolver_with_context
description = "Represents a collection of products."
only_fields = [
"description",
"description_json",
"id",
- "is_published",
"name",
- "publication_date",
"seo_description",
"seo_title",
"slug",
@@ -750,27 +873,31 @@ class Collection(CountableDjangoObjectType):
model = models.Collection
@staticmethod
- def resolve_background_image(root: models.Collection, info, size=None, **_kwargs):
- if root.background_image:
+ def resolve_background_image(
+ root: ChannelContext[models.Collection], info, size=None, **_kwargs
+ ):
+ if root.node.background_image:
+ node = root.node
return Image.get_adjusted(
- image=root.background_image,
- alt=root.background_image_alt,
+ image=node.background_image,
+ alt=node.background_image_alt,
size=size,
rendition_key_set="background_images",
info=info,
)
@staticmethod
- def resolve_products(root: models.Collection, info, first=None, **kwargs):
- return root.products.visible_to_user(info.context.user)
+ def resolve_products(root: ChannelContext[models.Collection], info, **kwargs):
+ user = info.context.user
+ qs = root.node.products.visible_to_user(user, root.channel_slug)
+ return ChannelQsContext(qs=qs, channel_slug=root.channel_slug)
- @classmethod
- def get_node(cls, info, id):
- if info.context:
- requestor = get_user_or_app_from_context(info.context)
- qs = cls._meta.model.objects.visible_to_user(requestor)
- return qs.filter(id=id).first()
- return None
+ @staticmethod
+ @permission_required(ProductPermissions.MANAGE_PRODUCTS)
+ def resolve_channel_listings(root: ChannelContext[models.Collection], info):
+ return CollectionChannelListingByCollectionIdLoader(info.context).load(
+ root.node.id
+ )
@staticmethod
def __resolve_reference(root, _info, **_kwargs):
@@ -782,8 +909,12 @@ class Category(CountableDjangoObjectType):
ancestors = PrefetchingConnectionField(
lambda: Category, description="List of ancestors of the category."
)
- products = PrefetchingConnectionField(
- Product, description="List of products in the category."
+ products = ChannelContextFilterConnectionField(
+ Product,
+ channel=graphene.String(
+ description="Slug of a channel for which the data should be returned."
+ ),
+ description="List of products in the category.",
)
url = graphene.String(
description="The storefront's URL for the category.",
@@ -841,13 +972,25 @@ class Category(CountableDjangoObjectType):
return ""
@staticmethod
- def resolve_products(root: models.Category, info, **_kwargs):
+ def resolve_products(root: models.Category, info, channel=None, **_kwargs):
requestor = get_user_or_app_from_context(info.context)
+ requestor_has_access_to_all = models.Product.objects.user_has_access_to_all(
+ requestor
+ )
tree = root.get_descendants(include_self=True)
- qs = models.Product.objects.published()
- if not qs.user_has_access_to_all(requestor):
- qs = qs.exclude(visible_in_listings=False)
- return qs.filter(category__in=tree)
+ if channel is None and not requestor_has_access_to_all:
+ channel = get_default_channel_slug_or_graphql_error()
+ qs = models.Product.objects.all()
+ if not requestor_has_access_to_all:
+ qs = (
+ qs.published(channel)
+ .annotate_visible_in_listings(channel)
+ .exclude(visible_in_listings=False,)
+ )
+ if channel and requestor_has_access_to_all:
+ qs = qs.filter(channel_listings__channel__slug=channel)
+ qs = qs.filter(category__in=tree)
+ return ChannelQsContext(qs=qs, channel_slug=channel)
@staticmethod
def __resolve_reference(root, _info, **_kwargs):
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index c1f3c77119..850ccb7b23 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -469,6 +469,7 @@ input AttributeFilterInput {
ids: [ID]
inCollection: ID
inCategory: ID
+ channel: String
}
input AttributeInput {
@@ -662,6 +663,7 @@ type BulkProductError {
attributes: [ID!]
index: Int
warehouses: [ID!]
+ channels: [ID!]
}
type BulkStockError {
@@ -691,7 +693,7 @@ type Category implements Node & ObjectWithMetadata {
privateMetadata: [MetadataItem]!
metadata: [MetadataItem]!
ancestors(before: String, after: String, first: Int, last: Int): CategoryCountableConnection
- products(before: String, after: String, first: Int, last: Int): ProductCountableConnection
+ products(channel: String, before: String, after: String, first: Int, last: Int): ProductCountableConnection
url: String @deprecated(reason: "This field will be removed after 2020-07-31.")
children(before: String, after: String, first: Int, last: Int): CategoryCountableConnection
backgroundImage(size: Int): Image
@@ -750,6 +752,7 @@ enum CategorySortField {
input CategorySortingInput {
direction: OrderDirection!
+ channel: String
field: CategorySortField!
}
@@ -786,14 +789,86 @@ type CategoryUpdate {
category: Category
}
+type Channel implements Node {
+ id: ID!
+ name: String!
+ isActive: Boolean!
+ slug: String!
+ currencyCode: String!
+}
+
+type ChannelActivate {
+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
+ channel: Channel
+ channelErrors: [ChannelError!]!
+}
+
+type ChannelCreate {
+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
+ channelErrors: [ChannelError!]!
+ channel: Channel
+}
+
+input ChannelCreateInput {
+ isActive: Boolean
+ name: String!
+ slug: String!
+ currencyCode: String!
+}
+
+type ChannelDeactivate {
+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
+ channel: Channel
+ channelErrors: [ChannelError!]!
+}
+
+type ChannelDelete {
+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
+ channelErrors: [ChannelError!]!
+ channel: Channel
+}
+
+input ChannelDeleteInput {
+ targetChannel: ID!
+}
+
+type ChannelError {
+ field: String
+ message: String
+ code: ChannelErrorCode!
+}
+
+enum ChannelErrorCode {
+ ALREADY_EXISTS
+ GRAPHQL_ERROR
+ INVALID
+ NOT_FOUND
+ REQUIRED
+ UNIQUE
+ CHANNEL_TARGET_ID_MUST_BE_DIFFERENT
+ CHANNELS_CURRENCY_MUST_BE_THE_SAME
+}
+
+type ChannelUpdate {
+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
+ channelErrors: [ChannelError!]!
+ channel: Channel
+}
+
+input ChannelUpdateInput {
+ isActive: Boolean
+ name: String
+ slug: String
+}
+
type Checkout implements Node & ObjectWithMetadata {
created: DateTime!
lastChange: DateTime!
user: User
quantity: Int!
+ channel: Channel!
billingAddress: Address
shippingAddress: Address
- shippingMethod: ShippingMethod
note: String!
discount: Money
discountName: String
@@ -809,6 +884,7 @@ type Checkout implements Node & ObjectWithMetadata {
isShippingRequired: Boolean!
lines: [CheckoutLine]
shippingPrice: TaxedMoney
+ shippingMethod: ShippingMethod
subtotalPrice: TaxedMoney
token: UUID!
totalPrice: TaxedMoney
@@ -853,6 +929,7 @@ type CheckoutCreate {
}
input CheckoutCreateInput {
+ channel: String
lines: [CheckoutLineInput]!
email: String
shippingAddress: AddressInput
@@ -905,6 +982,8 @@ enum CheckoutErrorCode {
UNIQUE
VOUCHER_NOT_APPLICABLE
ZERO_QUANTITY
+ MISSING_CHANNEL_SLUG
+ CHANNEL_INACTIVE
}
type CheckoutLine implements Node {
@@ -986,20 +1065,19 @@ type Collection implements Node & ObjectWithMetadata {
name: String!
description: String!
descriptionJson: JSONString!
- publicationDate: Date
- isPublished: Boolean!
slug: String!
privateMetadata: [MetadataItem]!
metadata: [MetadataItem]!
products(filter: ProductFilterInput, sortBy: ProductOrder, before: String, after: String, first: Int, last: Int): ProductCountableConnection
backgroundImage(size: Int): Image
translation(languageCode: LanguageCodeEnum!): CollectionTranslation
+ channelListings: [CollectionChannelListing!]
}
type CollectionAddProducts {
errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
collection: Collection
- productErrors: [ProductError!]!
+ collectionErrors: [CollectionError!]!
}
type CollectionBulkDelete {
@@ -1008,10 +1086,30 @@ type CollectionBulkDelete {
productErrors: [ProductError!]!
}
-type CollectionBulkPublish {
+type CollectionChannelListing implements Node {
+ publicationDate: Date
+ isPublished: Boolean!
+ id: ID!
+ channel: Channel!
+}
+
+type CollectionChannelListingError {
+ field: String
+ message: String
+ code: ProductErrorCode!
+ attributes: [ID!]
+ channels: [ID!]
+}
+
+type CollectionChannelListingUpdate {
errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
- count: Int!
- productErrors: [ProductError!]!
+ collection: Collection
+ collectionChannelListingErrors: [CollectionChannelListingError!]!
+}
+
+input CollectionChannelListingUpdateInput {
+ addChannels: [PublishableChannelListingInput!]
+ removeChannels: [ID!]
}
type CollectionCountableConnection {
@@ -1027,7 +1125,7 @@ type CollectionCountableEdge {
type CollectionCreate {
errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
- productErrors: [ProductError!]!
+ collectionErrors: [CollectionError!]!
collection: Collection
}
@@ -1046,14 +1144,32 @@ input CollectionCreateInput {
type CollectionDelete {
errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
- productErrors: [ProductError!]!
+ collectionErrors: [CollectionError!]!
collection: Collection
}
+type CollectionError {
+ field: String
+ message: String
+ products: [ID!]
+ code: CollectionErrorCode!
+}
+
+enum CollectionErrorCode {
+ DUPLICATED_INPUT_ITEM
+ GRAPHQL_ERROR
+ INVALID
+ NOT_FOUND
+ REQUIRED
+ UNIQUE
+ CANNOT_MANAGE_PRODUCT_WITHOUT_VARIANT
+}
+
input CollectionFilterInput {
published: CollectionPublished
search: String
ids: [ID]
+ channel: String
}
input CollectionInput {
@@ -1076,13 +1192,13 @@ enum CollectionPublished {
type CollectionRemoveProducts {
errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
collection: Collection
- productErrors: [ProductError!]!
+ collectionErrors: [CollectionError!]!
}
type CollectionReorderProducts {
errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
collection: Collection
- productErrors: [ProductError!]!
+ collectionErrors: [CollectionError!]!
}
enum CollectionSortField {
@@ -1094,6 +1210,7 @@ enum CollectionSortField {
input CollectionSortingInput {
direction: OrderDirection!
+ channel: String
field: CollectionSortField!
}
@@ -1126,7 +1243,7 @@ type CollectionTranslation implements Node {
type CollectionUpdate {
errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
- productErrors: [ProductError!]!
+ collectionErrors: [CollectionError!]!
collection: Collection
}
@@ -1486,7 +1603,6 @@ enum CustomerEventsEnum {
input CustomerFilterInput {
dateJoined: DateRangeInput
- moneySpent: PriceRangeInput
numberOfOrders: IntRangeInput
placedOrders: DateRangeInput
search: String
@@ -1620,7 +1736,9 @@ input DigitalContentUrlCreateInput {
type DiscountError {
field: String
message: String
+ products: [ID!]
code: DiscountErrorCode!
+ channels: [ID!]
}
enum DiscountErrorCode {
@@ -1630,6 +1748,8 @@ enum DiscountErrorCode {
NOT_FOUND
REQUIRED
UNIQUE
+ CANNOT_MANAGE_PRODUCT_WITHOUT_VARIANT
+ DUPLICATED_INPUT_ITEM
}
enum DiscountStatusEnum {
@@ -1676,6 +1796,7 @@ input DraftOrderCreateInput {
shippingMethod: ID
voucher: ID
customerNote: String
+ channel: ID
lines: [OrderLineCreateInput]
}
@@ -1694,6 +1815,7 @@ input DraftOrderInput {
shippingMethod: ID
voucher: ID
customerNote: String
+ channel: ID
}
type DraftOrderLineDelete {
@@ -1809,6 +1931,7 @@ input ExportFileSortingInput {
input ExportInfoInput {
attributes: [ID!]
warehouses: [ID!]
+ channels: [ID!]
fields: [ProductFieldEnum!]
}
@@ -1999,12 +2122,6 @@ type GroupCountableEdge {
cursor: String!
}
-type HomepageCollectionUpdate {
- errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
- shop: Shop
- shopErrors: [ShopError!]!
-}
-
type Image {
url: String!
alt: String
@@ -2429,12 +2546,12 @@ type Mutation {
staffNotificationRecipientCreate(input: StaffNotificationRecipientInput!): StaffNotificationRecipientCreate
staffNotificationRecipientUpdate(id: ID!, input: StaffNotificationRecipientInput!): StaffNotificationRecipientUpdate
staffNotificationRecipientDelete(id: ID!): StaffNotificationRecipientDelete
- homepageCollectionUpdate(collection: ID): HomepageCollectionUpdate
shopDomainUpdate(input: SiteDomainInput): ShopDomainUpdate
shopSettingsUpdate(input: ShopSettingsInput!): ShopSettingsUpdate
shopFetchTaxRates: ShopFetchTaxRates
shopSettingsTranslate(input: ShopSettingsTranslationInput!, languageCode: LanguageCodeEnum!): ShopSettingsTranslate
shopAddressUpdate(input: AddressInput): ShopAddressUpdate
+ shippingMethodChannelListingUpdate(id: ID!, input: ShippingMethodChannelListingInput!): ShippingMethodChannelListingUpdate
shippingPriceCreate(input: ShippingPriceInput!): ShippingPriceCreate
shippingPriceDelete(id: ID!): ShippingPriceDelete
shippingPriceBulkDelete(ids: [ID]!): ShippingPriceBulkDelete
@@ -2467,17 +2584,16 @@ type Mutation {
collectionDelete(id: ID!): CollectionDelete
collectionReorderProducts(collectionId: ID!, moves: [MoveProductInput]!): CollectionReorderProducts
collectionBulkDelete(ids: [ID]!): CollectionBulkDelete
- collectionBulkPublish(ids: [ID]!, isPublished: Boolean!): CollectionBulkPublish
collectionRemoveProducts(collectionId: ID!, products: [ID]!): CollectionRemoveProducts
collectionUpdate(id: ID!, input: CollectionInput!): CollectionUpdate
collectionTranslate(id: ID!, input: TranslationInput!, languageCode: LanguageCodeEnum!): CollectionTranslate
+ collectionChannelListingUpdate(id: ID!, input: CollectionChannelListingUpdateInput!): CollectionChannelListingUpdate
productCreate(input: ProductCreateInput!): ProductCreate
productDelete(id: ID!): ProductDelete
productBulkDelete(ids: [ID]!): ProductBulkDelete
- productBulkPublish(ids: [ID]!, isPublished: Boolean!): ProductBulkPublish
productUpdate(id: ID!, input: ProductInput!): ProductUpdate
productTranslate(id: ID!, input: TranslationInput!, languageCode: LanguageCodeEnum!): ProductTranslate
- productSetAvailabilityForPurchase(isAvailable: Boolean!, productId: ID!, startDate: Date): ProductSetAvailabilityForPurchase
+ productChannelListingUpdate(id: ID!, input: ProductChannelListingUpdateInput!): ProductChannelListingUpdate
productImageCreate(input: ProductImageCreateInput!): ProductImageCreate
productVariantReorder(moves: [ReorderInput]!, productId: ID!): ProductVariantReorder
productImageDelete(id: ID!): ProductImageDelete
@@ -2503,6 +2619,7 @@ type Mutation {
productVariantUpdate(id: ID!, input: ProductVariantInput!): ProductVariantUpdate
productVariantSetDefault(productId: ID!, variantId: ID!): ProductVariantSetDefault
productVariantTranslate(id: ID!, input: NameTranslationInput!, languageCode: LanguageCodeEnum!): ProductVariantTranslate
+ productVariantChannelListingUpdate(id: ID!, input: [ProductVariantChannelListingAddInput!]!): ProductVariantChannelListingUpdate
variantImageAssign(imageId: ID!, variantId: ID!): VariantImageAssign
variantImageUnassign(imageId: ID!, variantId: ID!): VariantImageUnassign
paymentCapture(amount: PositiveDecimal, paymentId: ID!): PaymentCapture
@@ -2569,6 +2686,7 @@ type Mutation {
saleCataloguesAdd(id: ID!, input: CatalogueInput!): SaleAddCatalogues
saleCataloguesRemove(id: ID!, input: CatalogueInput!): SaleRemoveCatalogues
saleTranslate(id: ID!, input: NameTranslationInput!, languageCode: LanguageCodeEnum!): SaleTranslate
+ saleChannelListingUpdate(id: ID!, input: SaleChannelListingInput!): SaleChannelListingUpdate
voucherCreate(input: VoucherInput!): VoucherCreate
voucherDelete(id: ID!): VoucherDelete
voucherBulkDelete(ids: [ID]!): VoucherBulkDelete
@@ -2576,6 +2694,7 @@ type Mutation {
voucherCataloguesAdd(id: ID!, input: CatalogueInput!): VoucherAddCatalogues
voucherCataloguesRemove(id: ID!, input: CatalogueInput!): VoucherRemoveCatalogues
voucherTranslate(id: ID!, input: NameTranslationInput!, languageCode: LanguageCodeEnum!): VoucherTranslate
+ voucherChannelListingUpdate(id: ID!, input: VoucherChannelListingInput!): VoucherChannelListingUpdate
exportProducts(input: ExportProductsInput!): ExportProducts
fileUpload(file: Upload!): FileUpload
checkoutAddPromoCode(checkoutId: ID!, promoCode: String!): CheckoutAddPromoCode
@@ -2592,6 +2711,11 @@ type Mutation {
checkoutPaymentCreate(checkoutId: ID!, input: PaymentInput!): CheckoutPaymentCreate
checkoutShippingAddressUpdate(checkoutId: ID!, shippingAddress: AddressInput!): CheckoutShippingAddressUpdate
checkoutShippingMethodUpdate(checkoutId: ID, shippingMethodId: ID!): CheckoutShippingMethodUpdate
+ channelCreate(input: ChannelCreateInput!): ChannelCreate
+ channelUpdate(id: ID!, input: ChannelUpdateInput!): ChannelUpdate
+ channelDelete(id: ID!, input: ChannelDeleteInput!): ChannelDelete
+ channelActivate(id: ID!): ChannelActivate
+ channelDeactivate(id: ID!): ChannelDeactivate
appCreate(input: AppInput!): AppCreate
appUpdate(id: ID!, input: AppInput!): AppUpdate
appDelete(id: ID!): AppDelete
@@ -2676,6 +2800,7 @@ type Order implements Node & ObjectWithMetadata {
shippingAddress: Address
shippingMethod: ShippingMethod
shippingMethodName: String
+ channel: Channel!
shippingPrice: TaxedMoney
token: String!
voucher: Voucher
@@ -2774,6 +2899,7 @@ type OrderError {
code: OrderErrorCode!
warehouse: ID
orderLine: ID
+ variants: [ID!]
}
enum OrderErrorCode {
@@ -2802,6 +2928,8 @@ enum OrderErrorCode {
ZERO_QUANTITY
INSUFFICIENT_STOCK
DUPLICATED_INPUT_ITEM
+ NOT_AVAILABLE_IN_CHANNEL
+ CHANNEL_INACTIVE
}
type OrderEvent implements Node {
@@ -2959,7 +3087,6 @@ enum OrderSortField {
CUSTOMER
PAYMENT
FULFILLMENT_STATUS
- TOTAL
}
input OrderSortingInput {
@@ -3280,6 +3407,7 @@ enum PermissionEnum {
MANAGE_USERS
MANAGE_STAFF
MANAGE_APPS
+ MANAGE_CHANNELS
MANAGE_DISCOUNTS
MANAGE_PLUGINS
MANAGE_GIFT_CARD
@@ -3432,16 +3560,12 @@ type Product implements Node & ObjectWithMetadata {
name: String!
description: String!
descriptionJson: JSONString!
- publicationDate: Date
- isPublished: Boolean!
productType: ProductType!
slug: String!
category: Category
updatedAt: DateTime
chargeTaxes: Boolean!
weight: Weight
- availableForPurchase: Date
- visibleInListings: Boolean!
defaultVariant: ProductVariant
rating: Float
privateMetadata: [MetadataItem]!
@@ -3450,16 +3574,15 @@ type Product implements Node & ObjectWithMetadata {
thumbnail(size: Int): Image
pricing: ProductPricingInfo
isAvailable: Boolean
- minimalVariantPrice: Money
taxType: TaxType
attributes: [SelectedAttribute!]!
- purchaseCost: MoneyRange
- margin: Margin
+ channelListings: [ProductChannelListing!]
imageById(id: ID): ProductImage
variants: [ProductVariant]
images: [ProductImage]
collections: [Collection]
translation(languageCode: LanguageCodeEnum!): ProductTranslation
+ availableForPurchase: Date
isAvailableForPurchase: Boolean
}
@@ -3469,10 +3592,45 @@ type ProductBulkDelete {
productErrors: [ProductError!]!
}
-type ProductBulkPublish {
+type ProductChannelListing implements Node {
+ id: ID!
+ publicationDate: Date
+ isPublished: Boolean!
+ channel: Channel!
+ visibleInListings: Boolean!
+ availableForPurchase: Date
+ discountedPrice: Money
+ purchaseCost: MoneyRange
+ margin: Margin
+ isAvailableForPurchase: Boolean
+}
+
+input ProductChannelListingAddInput {
+ channelId: ID!
+ isPublished: Boolean
+ publicationDate: Date
+ visibleInListings: Boolean
+ isAvailableForPurchase: Boolean
+ availableForPurchaseDate: Date
+}
+
+type ProductChannelListingError {
+ field: String
+ message: String
+ code: ProductErrorCode!
+ attributes: [ID!]
+ channels: [ID!]
+}
+
+type ProductChannelListingUpdate {
errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
- count: Int!
- productErrors: [ProductError!]!
+ product: Product
+ productChannelListingErrors: [ProductChannelListingError!]!
+}
+
+input ProductChannelListingUpdateInput {
+ addChannels: [ProductChannelListingAddInput!]
+ removeChannels: [ID!]
}
type ProductCountableConnection {
@@ -3494,25 +3652,18 @@ type ProductCreate {
input ProductCreateInput {
attributes: [AttributeValueInput]
- publicationDate: Date
category: ID
chargeTaxes: Boolean
collections: [ID]
description: String
descriptionJson: JSONString
- isPublished: Boolean
name: String
slug: String
taxCode: String
seo: SeoInput
weight: WeightScalar
- sku: String
- trackInventory: Boolean
- basePrice: PositiveDecimal
- visibleInListings: Boolean
rating: Float
productType: ID!
- stocks: [StockInput!]
}
type ProductDelete {
@@ -3536,12 +3687,15 @@ enum ProductErrorCode {
DUPLICATED_INPUT_ITEM
GRAPHQL_ERROR
INVALID
+ PRODUCT_WITHOUT_CATEGORY
NOT_PRODUCTS_IMAGE
NOT_PRODUCTS_VARIANT
NOT_FOUND
REQUIRED
UNIQUE
VARIANT_NO_DIGITAL_CONTENT
+ CANNOT_MANAGE_PRODUCT_WITHOUT_VARIANT
+ PRODUCT_NOT_ASSIGNED_TO_CHANNEL
}
enum ProductFieldEnum {
@@ -3550,15 +3704,11 @@ enum ProductFieldEnum {
PRODUCT_TYPE
CATEGORY
VISIBLE
- AVAILABLE_FOR_PURCHASE
- SEARCHABLE
PRODUCT_WEIGHT
COLLECTIONS
CHARGE_TAXES
PRODUCT_IMAGES
VARIANT_SKU
- VARIANT_PRICE
- COST_PRICE
VARIANT_WEIGHT
VARIANT_IMAGES
}
@@ -3577,6 +3727,7 @@ input ProductFilterInput {
minimalPrice: PriceRangeInput
productTypes: [ID]
ids: [ID]
+ channel: String
}
type ProductImage implements Node {
@@ -3632,27 +3783,22 @@ input ProductImageUpdateInput {
input ProductInput {
attributes: [AttributeValueInput]
- publicationDate: Date
category: ID
chargeTaxes: Boolean
collections: [ID]
description: String
descriptionJson: JSONString
- isPublished: Boolean
name: String
slug: String
taxCode: String
seo: SeoInput
weight: WeightScalar
- sku: String
- trackInventory: Boolean
- basePrice: PositiveDecimal
- visibleInListings: Boolean
rating: Float
}
input ProductOrder {
direction: OrderDirection!
+ channel: String
attributeId: ID
field: ProductOrderField
}
@@ -3678,12 +3824,6 @@ type ProductPricingInfo {
priceRangeLocalCurrency: TaxedMoneyRange
}
-type ProductSetAvailabilityForPurchase {
- errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
- product: Product
- productErrors: [ProductError!]!
-}
-
input ProductStockFilterInput {
warehouseIds: [ID!]
quantity: IntRangeInput
@@ -3726,7 +3866,7 @@ type ProductType implements Node & ObjectWithMetadata {
weight: Weight
privateMetadata: [MetadataItem]!
metadata: [MetadataItem]!
- products(before: String, after: String, first: Int, last: Int): ProductCountableConnection
+ products(channel: String, before: String, after: String, first: Int, last: Int): ProductCountableConnection @deprecated(reason: "Use the top-level `products` query with the `productTypes` filter.")
taxRate: TaxRateType
taxType: TaxType
variantAttributes: [Attribute]
@@ -3833,7 +3973,7 @@ type ProductVariant implements Node & ObjectWithMetadata {
quantity: Int! @deprecated(reason: "Use the stock field instead. This field will be removed after 2020-07-31.")
quantityAllocated: Int @deprecated(reason: "Use the stock field instead. This field will be removed after 2020-07-31.")
stockQuantity: Int! @deprecated(reason: "Use the quantityAvailable field instead. This field will be removed after 2020-07-31.")
- price: Money
+ channelListings: [ProductVariantChannelListing!]
pricing: VariantPricingInfo
isAvailable: Boolean @deprecated(reason: "Use the stock field instead. This field will be removed after 2020-07-31.")
attributes: [SelectedAttribute!]!
@@ -3857,12 +3997,11 @@ type ProductVariantBulkCreate {
input ProductVariantBulkCreateInput {
attributes: [AttributeValueInput]!
- costPrice: PositiveDecimal
- price: PositiveDecimal
sku: String!
trackInventory: Boolean
weight: WeightScalar
stocks: [StockInput!]
+ channelListings: [ProductVariantChannelListingAddInput!]
}
type ProductVariantBulkDelete {
@@ -3871,6 +4010,26 @@ type ProductVariantBulkDelete {
productErrors: [ProductError!]!
}
+type ProductVariantChannelListing implements Node {
+ id: ID!
+ channel: Channel!
+ price: Money
+ costPrice: Money
+ margin: Int
+}
+
+input ProductVariantChannelListingAddInput {
+ channelId: ID!
+ price: PositiveDecimal!
+ costPrice: PositiveDecimal
+}
+
+type ProductVariantChannelListingUpdate {
+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
+ variant: ProductVariant
+ productChannelListingErrors: [ProductChannelListingError!]!
+}
+
type ProductVariantCountableConnection {
pageInfo: PageInfo!
edges: [ProductVariantCountableEdge!]!
@@ -3890,8 +4049,6 @@ type ProductVariantCreate {
input ProductVariantCreateInput {
attributes: [AttributeValueInput]!
- costPrice: PositiveDecimal
- price: PositiveDecimal
sku: String
trackInventory: Boolean
weight: WeightScalar
@@ -3912,8 +4069,6 @@ input ProductVariantFilterInput {
input ProductVariantInput {
attributes: [AttributeValueInput]
- costPrice: PositiveDecimal
- price: PositiveDecimal
sku: String
trackInventory: Boolean
weight: WeightScalar
@@ -3974,6 +4129,12 @@ type ProductVariantUpdate {
productVariant: ProductVariant
}
+input PublishableChannelListingInput {
+ channelId: ID!
+ isPublished: Boolean
+ publicationDate: Date
+}
+
type Query {
webhook(id: ID!): Webhook
webhookEvents: [WebhookEvent]
@@ -3985,52 +4146,54 @@ type Query {
stock(id: ID!): Stock
stocks(filter: StockFilterInput, before: String, after: String, first: Int, last: Int): StockCountableConnection
shop: Shop!
- shippingZone(id: ID!): ShippingZone
- shippingZones(before: String, after: String, first: Int, last: Int): ShippingZoneCountableConnection
+ shippingZone(id: ID!, channel: String): ShippingZone
+ shippingZones(channel: String, before: String, after: String, first: Int, last: Int): ShippingZoneCountableConnection
digitalContent(id: ID!): DigitalContent
digitalContents(before: String, after: String, first: Int, last: Int): DigitalContentCountableConnection
attributes(filter: AttributeFilterInput, sortBy: AttributeSortingInput, before: String, after: String, first: Int, last: Int): AttributeCountableConnection
attribute(id: ID!): Attribute
categories(filter: CategoryFilterInput, sortBy: CategorySortingInput, level: Int, before: String, after: String, first: Int, last: Int): CategoryCountableConnection
category(id: ID, slug: String): Category
- collection(id: ID, slug: String): Collection
- collections(filter: CollectionFilterInput, sortBy: CollectionSortingInput, before: String, after: String, first: Int, last: Int): CollectionCountableConnection
- product(id: ID, slug: String): Product
- products(filter: ProductFilterInput, sortBy: ProductOrder, stockAvailability: StockAvailability, before: String, after: String, first: Int, last: Int): ProductCountableConnection
+ collection(id: ID, slug: String, channel: String): Collection
+ collections(filter: CollectionFilterInput, sortBy: CollectionSortingInput, channel: String, before: String, after: String, first: Int, last: Int): CollectionCountableConnection
+ product(id: ID, slug: String, channel: String): Product
+ products(filter: ProductFilterInput, sortBy: ProductOrder, stockAvailability: StockAvailability, channel: String, before: String, after: String, first: Int, last: Int): ProductCountableConnection
productType(id: ID!): ProductType
productTypes(filter: ProductTypeFilterInput, sortBy: ProductTypeSortingInput, before: String, after: String, first: Int, last: Int): ProductTypeCountableConnection
- productVariant(id: ID, sku: String): ProductVariant
- productVariants(ids: [ID], filter: ProductVariantFilterInput, before: String, after: String, first: Int, last: Int): ProductVariantCountableConnection
- reportProductSales(period: ReportingPeriod!, before: String, after: String, first: Int, last: Int): ProductVariantCountableConnection
+ productVariant(id: ID, sku: String, channel: String): ProductVariant
+ productVariants(ids: [ID], channel: String, filter: ProductVariantFilterInput, before: String, after: String, first: Int, last: Int): ProductVariantCountableConnection
+ reportProductSales(period: ReportingPeriod!, channel: String!, before: String, after: String, first: Int, last: Int): ProductVariantCountableConnection
payment(id: ID!): Payment
payments(before: String, after: String, first: Int, last: Int): PaymentCountableConnection
page(id: ID, slug: String): Page
pages(sortBy: PageSortingInput, filter: PageFilterInput, before: String, after: String, first: Int, last: Int): PageCountableConnection
homepageEvents(before: String, after: String, first: Int, last: Int): OrderEventCountableConnection
order(id: ID!): Order
- orders(sortBy: OrderSortingInput, filter: OrderFilterInput, created: ReportingPeriod, status: OrderStatusFilter, before: String, after: String, first: Int, last: Int): OrderCountableConnection
+ orders(sortBy: OrderSortingInput, filter: OrderFilterInput, created: ReportingPeriod, status: OrderStatusFilter, channel: String, before: String, after: String, first: Int, last: Int): OrderCountableConnection
draftOrders(sortBy: OrderSortingInput, filter: OrderDraftFilterInput, created: ReportingPeriod, before: String, after: String, first: Int, last: Int): OrderCountableConnection
- ordersTotal(period: ReportingPeriod): TaxedMoney
+ ordersTotal(period: ReportingPeriod, channel: String): TaxedMoney
orderByToken(token: UUID!): Order
- menu(id: ID, name: String, slug: String): Menu
- menus(sortBy: MenuSortingInput, filter: MenuFilterInput, before: String, after: String, first: Int, last: Int): MenuCountableConnection
- menuItem(id: ID!): MenuItem
- menuItems(sortBy: MenuItemSortingInput, filter: MenuItemFilterInput, before: String, after: String, first: Int, last: Int): MenuItemCountableConnection
+ menu(channel: String, id: ID, name: String, slug: String): Menu
+ menus(channel: String, sortBy: MenuSortingInput, filter: MenuFilterInput, before: String, after: String, first: Int, last: Int): MenuCountableConnection
+ menuItem(id: ID!, channel: String): MenuItem
+ menuItems(channel: String, sortBy: MenuItemSortingInput, filter: MenuItemFilterInput, before: String, after: String, first: Int, last: Int): MenuItemCountableConnection
giftCard(id: ID!): GiftCard
giftCards(before: String, after: String, first: Int, last: Int): GiftCardCountableConnection
plugin(id: ID!): Plugin
plugins(filter: PluginFilterInput, sortBy: PluginSortingInput, before: String, after: String, first: Int, last: Int): PluginCountableConnection
- sale(id: ID!): Sale
- sales(filter: SaleFilterInput, sortBy: SaleSortingInput, query: String, before: String, after: String, first: Int, last: Int): SaleCountableConnection
- voucher(id: ID!): Voucher
- vouchers(filter: VoucherFilterInput, sortBy: VoucherSortingInput, query: String, before: String, after: String, first: Int, last: Int): VoucherCountableConnection
+ sale(id: ID!, channel: String): Sale
+ sales(filter: SaleFilterInput, sortBy: SaleSortingInput, query: String, channel: String, before: String, after: String, first: Int, last: Int): SaleCountableConnection
+ voucher(id: ID!, channel: String): Voucher
+ vouchers(filter: VoucherFilterInput, sortBy: VoucherSortingInput, query: String, channel: String, before: String, after: String, first: Int, last: Int): VoucherCountableConnection
exportFile(id: ID!): ExportFile
exportFiles(filter: ExportFileFilterInput, sortBy: ExportFileSortingInput, before: String, after: String, first: Int, last: Int): ExportFileCountableConnection
taxTypes: [TaxType]
- checkout(token: UUID): Checkout
- checkouts(before: String, after: String, first: Int, last: Int): CheckoutCountableConnection
+ checkout(token: UUID, channel: String): Checkout
+ checkouts(channel: String, before: String, after: String, first: Int, last: Int): CheckoutCountableConnection
checkoutLine(id: ID): CheckoutLine
checkoutLines(before: String, after: String, first: Int, last: Int): CheckoutLineCountableConnection
+ channel(id: ID): Channel
+ channels: [Channel!]
appsInstallations: [AppInstallation!]!
apps(filter: AppFilterInput, sortBy: AppSortingInput, before: String, after: String, first: Int, last: Int): AppCountableConnection
app(id: ID!): App
@@ -4083,13 +4246,15 @@ type Sale implements Node {
id: ID!
name: String!
type: SaleType!
- value: Float!
startDate: DateTime!
endDate: DateTime
categories(before: String, after: String, first: Int, last: Int): CategoryCountableConnection
collections(before: String, after: String, first: Int, last: Int): CollectionCountableConnection
products(before: String, after: String, first: Int, last: Int): ProductCountableConnection
translation(languageCode: LanguageCodeEnum!): SaleTranslation
+ channelListings: [SaleChannelListing!]
+ discountValue: Float
+ currency: String
}
type SaleAddCatalogues {
@@ -4104,6 +4269,29 @@ type SaleBulkDelete {
discountErrors: [DiscountError!]!
}
+type SaleChannelListing implements Node {
+ id: ID!
+ channel: Channel!
+ discountValue: Float!
+ currency: String!
+}
+
+input SaleChannelListingAddInput {
+ channelId: ID!
+ discountValue: PositiveDecimal!
+}
+
+input SaleChannelListingInput {
+ addChannels: [SaleChannelListingAddInput!]
+ removeChannels: [ID!]
+}
+
+type SaleChannelListingUpdate {
+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
+ sale: Sale
+ discountErrors: [DiscountError!]!
+}
+
type SaleCountableConnection {
pageInfo: PageInfo!
edges: [SaleCountableEdge!]!
@@ -4161,6 +4349,7 @@ enum SaleSortField {
input SaleSortingInput {
direction: OrderDirection!
+ channel: String
field: SaleSortField!
}
@@ -4218,6 +4407,7 @@ type ShippingError {
message: String
code: ShippingErrorCode!
warehouses: [ID!]
+ channels: [ID!]
}
enum ShippingErrorCode {
@@ -4234,15 +4424,42 @@ enum ShippingErrorCode {
type ShippingMethod implements Node & ObjectWithMetadata {
id: ID!
name: String!
- price: Money
- minimumOrderPrice: Money
- maximumOrderPrice: Money
minimumOrderWeight: Weight
maximumOrderWeight: Weight
privateMetadata: [MetadataItem]!
metadata: [MetadataItem]!
type: ShippingMethodTypeEnum
translation(languageCode: LanguageCodeEnum!): ShippingMethodTranslation
+ channelListings: [ShippingMethodChannelListing!]
+ price: Money
+ maximumOrderPrice: Money
+ minimumOrderPrice: Money
+}
+
+type ShippingMethodChannelListing implements Node {
+ id: ID!
+ channel: Channel!
+ minimumOrderPrice: Money
+ maximumOrderPrice: Money
+ price: Money
+}
+
+input ShippingMethodChannelListingAddInput {
+ channelId: ID!
+ price: PositiveDecimal
+ minimumOrderPrice: PositiveDecimal
+ maximumOrderPrice: PositiveDecimal
+}
+
+input ShippingMethodChannelListingInput {
+ addChannels: [ShippingMethodChannelListingAddInput!]
+ removeChannels: [ID!]
+}
+
+type ShippingMethodChannelListingUpdate {
+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
+ shippingMethod: ShippingMethod
+ shippingErrors: [ShippingError!]!
}
type ShippingMethodTranslatableContent implements Node {
@@ -4272,8 +4489,8 @@ type ShippingPriceBulkDelete {
type ShippingPriceCreate {
errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
shippingZone: ShippingZone
- shippingErrors: [ShippingError!]!
shippingMethod: ShippingMethod
+ shippingErrors: [ShippingError!]!
}
type ShippingPriceDelete {
@@ -4285,9 +4502,6 @@ type ShippingPriceDelete {
input ShippingPriceInput {
name: String
- price: PositiveDecimal
- minimumOrderPrice: PositiveDecimal
- maximumOrderPrice: PositiveDecimal
minimumOrderWeight: WeightScalar
maximumOrderWeight: WeightScalar
type: ShippingMethodTypeEnum
@@ -4303,8 +4517,8 @@ type ShippingPriceTranslate {
type ShippingPriceUpdate {
errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
shippingZone: ShippingZone
- shippingErrors: [ShippingError!]!
shippingMethod: ShippingMethod
+ shippingErrors: [ShippingError!]!
}
type ShippingZone implements Node & ObjectWithMetadata {
@@ -4381,7 +4595,6 @@ type Shop {
defaultMailSenderAddress: String
description: String
domain: Domain!
- homepageCollection: Collection @deprecated(reason: "Use the `collection` query with the `slug` parameter. This field will be removed in Saleor 3.0")
languages: [LanguageDisplay]!
name: String!
navigation: Navigation @deprecated(reason: "Fetch menus using the `menu` query with `slug` parameter.")
@@ -4922,14 +5135,16 @@ type Voucher implements Node {
applyOncePerOrder: Boolean!
applyOncePerCustomer: Boolean!
discountValueType: DiscountValueTypeEnum!
- discountValue: Float!
- minSpent: Money
minCheckoutItemsQuantity: Int
categories(before: String, after: String, first: Int, last: Int): CategoryCountableConnection
collections(before: String, after: String, first: Int, last: Int): CollectionCountableConnection
products(before: String, after: String, first: Int, last: Int): ProductCountableConnection
countries: [CountryDisplay]
translation(languageCode: LanguageCodeEnum!): VoucherTranslation
+ discountValue: Float
+ currency: String
+ minSpent: Money
+ channelListings: [VoucherChannelListing!]
}
type VoucherAddCatalogues {
@@ -4944,6 +5159,31 @@ type VoucherBulkDelete {
discountErrors: [DiscountError!]!
}
+type VoucherChannelListing implements Node {
+ id: ID!
+ channel: Channel!
+ discountValue: Float!
+ currency: String!
+ minSpent: Money
+}
+
+input VoucherChannelListingAddInput {
+ channelId: ID!
+ discountValue: PositiveDecimal
+ minAmountSpent: PositiveDecimal
+}
+
+input VoucherChannelListingInput {
+ addChannels: [VoucherChannelListingAddInput!]
+ removeChannels: [ID!]
+}
+
+type VoucherChannelListingUpdate {
+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
+ voucher: Voucher
+ discountErrors: [DiscountError!]!
+}
+
type VoucherCountableConnection {
pageInfo: PageInfo!
edges: [VoucherCountableEdge!]!
@@ -4988,11 +5228,9 @@ input VoucherInput {
startDate: DateTime
endDate: DateTime
discountValueType: DiscountValueTypeEnum
- discountValue: PositiveDecimal
products: [ID]
collections: [ID]
categories: [ID]
- minAmountSpent: PositiveDecimal
minCheckoutItemsQuantity: Int
countries: [String]
applyOncePerOrder: Boolean
@@ -5018,6 +5256,7 @@ enum VoucherSortField {
input VoucherSortingInput {
direction: OrderDirection!
+ channel: String
field: VoucherSortField!
}
diff --git a/saleor/graphql/shipping/dataloaders.py b/saleor/graphql/shipping/dataloaders.py
new file mode 100644
index 0000000000..9fbccc59ca
--- /dev/null
+++ b/saleor/graphql/shipping/dataloaders.py
@@ -0,0 +1,89 @@
+from collections import defaultdict
+
+from django.db.models import F
+
+from ...shipping.models import ShippingMethod, ShippingMethodChannelListing
+from ..core.dataloaders import DataLoader
+
+
+class ShippingMethodByIdLoader(DataLoader):
+ context_key = "shippingmethod_by_id"
+
+ def batch_load(self, keys):
+ shipping_methods = ShippingMethod.objects.in_bulk(keys)
+ return [shipping_methods.get(shipping_method_id) for shipping_method_id in keys]
+
+
+class ShippingMethodsByShippingZoneIdLoader(DataLoader):
+ context_key = "shippingmethod_by_shippingzone"
+
+ def batch_load(self, keys):
+ shipping_methods = ShippingMethod.objects.filter(shipping_zone_id__in=keys)
+ shipping_methods_by_shipping_zone_map = defaultdict(list)
+ for shipping_method in shipping_methods:
+ shipping_methods_by_shipping_zone_map[
+ shipping_method.shipping_zone_id
+ ].append(shipping_method)
+ return [
+ shipping_methods_by_shipping_zone_map[shipping_zone_id]
+ for shipping_zone_id in keys
+ ]
+
+
+class ShippingMethodsByShippingZoneIdAndChannelSlugLoader(DataLoader):
+ context_key = "shippingmethod_by_shippingzone_and_channel"
+
+ def batch_load(self, keys):
+ shipping_methods = ShippingMethod.objects.filter(
+ shipping_zone_id__in=keys
+ ).annotate(channel_slug=F("channel_listings__channel__slug"))
+
+ shipping_methods_by_shipping_zone_and_channel_map = defaultdict(list)
+ for shipping_method in shipping_methods:
+ key = (shipping_method.shipping_zone_id, shipping_method.channel_slug)
+ shipping_methods_by_shipping_zone_and_channel_map[key].append(
+ shipping_method
+ )
+ return [shipping_methods_by_shipping_zone_and_channel_map[key] for key in keys]
+
+
+class ShippingMethodChannelListingByShippingMethodIdLoader(DataLoader):
+ context_key = "shippingmethodchannellisting_by_shippingmethod"
+
+ def batch_load(self, keys):
+ shipping_method_channel_listings = ShippingMethodChannelListing.objects.filter(
+ shipping_method_id__in=keys
+ )
+ shipping_method_channel_listings_by_shipping_method_map = defaultdict(list)
+ for shipping_method_channel_listing in shipping_method_channel_listings:
+ shipping_method_channel_listings_by_shipping_method_map[
+ shipping_method_channel_listing.shipping_method_id
+ ].append(shipping_method_channel_listing)
+ return [
+ shipping_method_channel_listings_by_shipping_method_map[shipping_method_id]
+ for shipping_method_id in keys
+ ]
+
+
+class ShippingMethodChannelListingByShippingMethodIdAndChannelSlugLoader(DataLoader):
+ context_key = "shippingmethodchannellisting_by_shippingmethod_and_channel"
+
+ def batch_load(self, keys):
+ shipping_method_ids = [key[0] for key in keys]
+ channel_slugs = [key[1] for key in keys]
+ shipping_method_channel_listings = ShippingMethodChannelListing.objects.filter(
+ shipping_method_id__in=shipping_method_ids, channel__slug__in=channel_slugs
+ ).annotate(channel_slug=F("channel__slug"))
+ shipping_method_channel_listings_by_shipping_method_and_channel_map = {}
+ for shipping_method_channel_listing in shipping_method_channel_listings:
+ key = (
+ shipping_method_channel_listing.shipping_method_id,
+ shipping_method_channel_listing.channel_slug,
+ )
+ shipping_method_channel_listings_by_shipping_method_and_channel_map[
+ key
+ ] = shipping_method_channel_listing
+ return [
+ shipping_method_channel_listings_by_shipping_method_and_channel_map[key]
+ for key in keys
+ ]
diff --git a/saleor/graphql/shipping/mutations/__init__.py b/saleor/graphql/shipping/mutations/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/graphql/shipping/mutations/channels.py b/saleor/graphql/shipping/mutations/channels.py
new file mode 100644
index 0000000000..7552161938
--- /dev/null
+++ b/saleor/graphql/shipping/mutations/channels.py
@@ -0,0 +1,218 @@
+from collections import defaultdict
+from typing import TYPE_CHECKING, DefaultDict, Dict, List
+
+import graphene
+from django.core.exceptions import ValidationError
+from django.db import transaction
+
+from ....core.permissions import ShippingPermissions
+from ....shipping.error_codes import ShippingErrorCode
+from ....shipping.models import ShippingMethodChannelListing
+from ...channel import ChannelContext
+from ...channel.mutations import BaseChannelListingMutation
+from ...core.scalars import PositiveDecimal
+from ...core.types.common import ShippingError
+from ...core.validators import validate_price_precision
+from ..types import ShippingMethod
+
+if TYPE_CHECKING:
+ from ....shipping.models import ShippingMethod as ShippingMethodModel
+
+ErrorType = DefaultDict[str, List[ValidationError]]
+
+
+class ShippingMethodChannelListingAddInput(graphene.InputObjectType):
+ channel_id = graphene.ID(required=True, description="ID of a channel.")
+ price = PositiveDecimal(
+ description="Shipping price of the shipping method in this channel."
+ )
+ minimum_order_price = PositiveDecimal(
+ description=("Minimum order price to use this shipping method.")
+ )
+ maximum_order_price = PositiveDecimal(
+ description=("Maximum order price to use this shipping method.")
+ )
+
+
+class ShippingMethodChannelListingInput(graphene.InputObjectType):
+ add_channels = graphene.List(
+ graphene.NonNull(ShippingMethodChannelListingAddInput),
+ description="List of channels to which the shipping method should be assigned.",
+ required=False,
+ )
+ remove_channels = graphene.List(
+ graphene.NonNull(graphene.ID),
+ description=(
+ "List of channels from which the shipping method should be unassigned."
+ ),
+ required=False,
+ )
+
+
+class ShippingMethodChannelListingUpdate(BaseChannelListingMutation):
+ shipping_method = graphene.Field(
+ ShippingMethod, description="An updated shipping method instance."
+ )
+
+ class Arguments:
+ id = graphene.ID(
+ required=True, description="ID of a shipping method to update."
+ )
+ input = ShippingMethodChannelListingInput(
+ required=True,
+ description="Fields required to update shipping method channel listings.",
+ )
+
+ class Meta:
+ description = "Manage shipping method's availability in channels."
+ permissions = (ShippingPermissions.MANAGE_SHIPPING,)
+ error_type_class = ShippingError
+ error_type_field = "shipping_errors"
+
+ @classmethod
+ def add_channels(
+ cls, shipping_method: "ShippingMethodModel", add_channels: List[Dict]
+ ):
+ for add_channel in add_channels:
+ channel = add_channel["channel"]
+ defaults = {"currency": channel.currency_code}
+ if "minimum_order_price_amount" in add_channel.keys():
+ defaults["minimum_order_price_amount"] = add_channel.get(
+ "minimum_order_price_amount", None
+ )
+ if "maximum_order_price_amount" in add_channel.keys():
+ defaults["maximum_order_price_amount"] = add_channel.get(
+ "maximum_order_price_amount", None
+ )
+ if "price_amount" in add_channel.keys():
+ defaults["price_amount"] = add_channel.get("price_amount")
+ ShippingMethodChannelListing.objects.update_or_create(
+ shipping_method=shipping_method,
+ channel=add_channel["channel"],
+ defaults=defaults,
+ )
+
+ @classmethod
+ def remove_channels(
+ cls, shipping_method: "ShippingMethodModel", remove_channels: List[int]
+ ):
+ ShippingMethodChannelListing.objects.filter(
+ shipping_method=shipping_method, channel_id__in=remove_channels
+ ).delete()
+
+ @classmethod
+ @transaction.atomic()
+ def save(cls, info, shipping_method: "ShippingMethodModel", cleaned_input: Dict):
+ cls.add_channels(shipping_method, cleaned_input.get("add_channels", []))
+ cls.remove_channels(shipping_method, cleaned_input.get("remove_channels", []))
+
+ @classmethod
+ def get_shipping_method_channel_listing_to_create(
+ cls, shipping_method_id, input,
+ ):
+ channels = [data.get("channel") for data in input]
+ channel_listings = ShippingMethodChannelListing.objects.filter(
+ shipping_method_id=shipping_method_id, channel_id__in=channels
+ ).values_list("channel_id", flat=True)
+ return [
+ data["channel_id"]
+ for data in input
+ if data["channel"].id in channel_listings
+ ]
+
+ @classmethod
+ def clean_input(cls, data, shipping_method_id, errors):
+ cleaned_input = data.get("add_channels")
+ channel_listing_to_update = cls.get_shipping_method_channel_listing_to_create(
+ shipping_method_id, cleaned_input
+ )
+ for channel_input in cleaned_input:
+ channel_id = channel_input.get("channel_id")
+ price_amount = channel_input.pop("price", None)
+ if price_amount is not None:
+ try:
+ validate_price_precision(
+ price_amount, channel_input["channel"].currency_code
+ )
+ channel_input["price_amount"] = price_amount
+ except ValidationError as error:
+ error.code = ShippingErrorCode.INVALID.value
+ error.params = {
+ "channels": [channel_id],
+ }
+ errors["price"].append(error)
+ else:
+ if channel_id not in channel_listing_to_update:
+ errors["price"].append(
+ ValidationError(
+ "This field is required.",
+ code=ShippingErrorCode.REQUIRED,
+ params={"channels": [channel_id]},
+ )
+ )
+
+ min_price = channel_input.pop("minimum_order_price", None)
+ max_price = channel_input.pop("maximum_order_price", None)
+
+ if min_price is not None:
+ channel_input["minimum_order_price_amount"] = min_price
+ try:
+ validate_price_precision(
+ min_price, channel_input["channel"].currency_code
+ )
+ except ValidationError as error:
+ error.code = ShippingErrorCode.INVALID.value
+ error.params = {
+ "channels": [channel_id],
+ }
+ errors["minimum_order_price"].append(error)
+
+ if max_price is not None:
+ channel_input["maximum_order_price_amount"] = max_price
+ try:
+ validate_price_precision(
+ max_price, channel_input["channel"].currency_code
+ )
+ except ValidationError as error:
+ error.code = ShippingErrorCode.INVALID.value
+ error.params = {
+ "channels": [channel_id],
+ }
+ errors["maximum_order_price"].append(error)
+
+ if (
+ min_price is not None
+ and max_price is not None
+ and max_price <= min_price
+ ):
+ errors["maximum_order_price"].append(
+ ValidationError(
+ (
+ "Maximum order price should be larger than "
+ "the minimum order price."
+ ),
+ code=ShippingErrorCode.MAX_LESS_THAN_MIN,
+ params={"channels": [channel_id]},
+ )
+ )
+
+ return data
+
+ @classmethod
+ def perform_mutation(cls, _root, info, id, input):
+ shipping_method = cls.get_node_or_error(
+ info, id, only_type=ShippingMethod, field="id"
+ )
+ errors = defaultdict(list)
+ clean_channels = cls.clean_channels(
+ info, input, errors, ShippingErrorCode.DUPLICATED_INPUT_ITEM.value
+ )
+ cleaned_input = cls.clean_input(clean_channels, shipping_method.id, errors)
+
+ if errors:
+ raise ValidationError(errors)
+
+ cls.save(info, shipping_method, cleaned_input)
+ return ShippingMethodChannelListingUpdate(
+ shipping_method=ChannelContext(node=shipping_method, channel_slug=None)
+ )
diff --git a/saleor/graphql/shipping/mutations.py b/saleor/graphql/shipping/mutations/shippings.py
similarity index 62%
rename from saleor/graphql/shipping/mutations.py
rename to saleor/graphql/shipping/mutations/shippings.py
index eb4fe696f0..73e86a8f70 100644
--- a/saleor/graphql/shipping/mutations.py
+++ b/saleor/graphql/shipping/mutations/shippings.py
@@ -2,31 +2,24 @@ import graphene
from django.core.exceptions import ValidationError
from django.db import transaction
-from ...core.permissions import ShippingPermissions
-from ...shipping import models
-from ...shipping.error_codes import ShippingErrorCode
-from ...shipping.utils import (
+from ....core.permissions import ShippingPermissions
+from ....shipping import models
+from ....shipping.error_codes import ShippingErrorCode
+from ....shipping.utils import (
default_shipping_zone_exists,
get_countries_without_shipping_zone,
)
-from ..core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation
-from ..core.scalars import PositiveDecimal, WeightScalar
-from ..core.types.common import ShippingError
-from ..core.utils import get_duplicates_ids
-from ..core.validators import validate_price_precision
-from .enums import ShippingMethodTypeEnum
-from .types import ShippingMethod, ShippingZone
+from ...channel.types import ChannelContext
+from ...core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation
+from ...core.scalars import WeightScalar
+from ...core.types.common import ShippingError
+from ...core.utils import get_duplicates_ids
+from ..enums import ShippingMethodTypeEnum
+from ..types import ShippingMethod, ShippingZone
class ShippingPriceInput(graphene.InputObjectType):
name = graphene.String(description="Name of the shipping method.")
- price = PositiveDecimal(description="Shipping price of the shipping method.")
- minimum_order_price = PositiveDecimal(
- description="Minimum order price to use this shipping method."
- )
- maximum_order_price = PositiveDecimal(
- description="Maximum order price to use this shipping method."
- )
minimum_order_weight = WeightScalar(
description="Minimum order weight to use this shipping method."
)
@@ -135,6 +128,13 @@ class ShippingZoneCreate(ShippingZoneMixin, ModelMutation):
error_type_class = ShippingError
error_type_field = "shipping_errors"
+ @classmethod
+ def success_response(cls, instance):
+ instance = ChannelContext(node=instance, channel_slug=None)
+ response = super().success_response(instance)
+
+ return response
+
class ShippingZoneUpdate(ShippingZoneMixin, ModelMutation):
class Arguments:
@@ -150,6 +150,13 @@ class ShippingZoneUpdate(ShippingZoneMixin, ModelMutation):
error_type_class = ShippingError
error_type_field = "shipping_errors"
+ @classmethod
+ def success_response(cls, instance):
+ instance = ChannelContext(node=instance, channel_slug=None)
+ response = super().success_response(instance)
+
+ return response
+
class ShippingZoneDelete(ModelDeleteMutation):
class Arguments:
@@ -162,100 +169,58 @@ class ShippingZoneDelete(ModelDeleteMutation):
error_type_class = ShippingError
error_type_field = "shipping_errors"
+ @classmethod
+ def success_response(cls, instance):
+ instance = ChannelContext(node=instance, channel_slug=None)
+ response = super().success_response(instance)
+
+ return response
+
class ShippingPriceMixin:
@classmethod
def clean_input(cls, info, instance, data, input_cls=None):
cleaned_input = super().clean_input(info, instance, data)
- # Rename the price field to price_amount (the model's)
- price_amount = cleaned_input.pop("price", None)
- if price_amount is not None:
- try:
- validate_price_precision(price_amount, instance.currency)
- except ValidationError as error:
- error.code = ShippingErrorCode.INVALID.value
- raise ValidationError({"price": error})
- cleaned_input["price_amount"] = price_amount
-
- cleaned_type = cleaned_input.get("type")
- if cleaned_type:
- if cleaned_type == ShippingMethodTypeEnum.PRICE.value:
- min_price = cleaned_input.pop("minimum_order_price", None)
- max_price = cleaned_input.pop("maximum_order_price", None)
-
- if min_price is not None:
- try:
- validate_price_precision(min_price, instance.currency)
- except ValidationError as error:
- error.code = ShippingErrorCode.INVALID.value
- raise ValidationError({"minimum_order_price": error})
- cleaned_input["minimum_order_price_amount"] = min_price
-
- if max_price is not None:
- try:
- validate_price_precision(max_price, instance.currency)
- except ValidationError as error:
- error.code = ShippingErrorCode.INVALID.value
- raise ValidationError({"maximum_order_price": error})
- cleaned_input["maximum_order_price_amount"] = max_price
-
- if (
- min_price is not None
- and max_price is not None
- and max_price <= min_price
- ):
- raise ValidationError(
- {
- "maximum_order_price": ValidationError(
- (
- "Maximum order price should be larger than "
- "the minimum order price."
- ),
- code=ShippingErrorCode.MAX_LESS_THAN_MIN,
- )
- }
- )
- else:
- min_weight = cleaned_input.get("minimum_order_weight")
- max_weight = cleaned_input.get("maximum_order_weight")
-
- if min_weight and min_weight.value < 0:
- raise ValidationError(
- {
- "minimum_order_weight": ValidationError(
- "Shipping can't have negative weight.",
- code=ShippingErrorCode.INVALID,
- )
- }
+ min_weight = cleaned_input.get("minimum_order_weight")
+ max_weight = cleaned_input.get("maximum_order_weight")
+
+ if min_weight and min_weight.value < 0:
+ raise ValidationError(
+ {
+ "minimum_order_weight": ValidationError(
+ "Shipping can't have negative weight.",
+ code=ShippingErrorCode.INVALID,
)
+ }
+ )
- if max_weight and max_weight.value < 0:
- raise ValidationError(
- {
- "maximum_order_weight": ValidationError(
- "Shipping can't have negative weight.",
- code=ShippingErrorCode.INVALID,
- )
- }
+ if max_weight and max_weight.value < 0:
+ raise ValidationError(
+ {
+ "maximum_order_weight": ValidationError(
+ "Shipping can't have negative weight.",
+ code=ShippingErrorCode.INVALID,
)
+ }
+ )
- if (
- min_weight is not None
- and max_weight is not None
- and max_weight <= min_weight
- ):
- raise ValidationError(
- {
- "maximum_order_weight": ValidationError(
- (
- "Maximum order weight should be larger than the "
- "minimum order weight."
- ),
- code=ShippingErrorCode.MAX_LESS_THAN_MIN,
- )
- }
+ if (
+ min_weight is not None
+ and max_weight is not None
+ and max_weight <= min_weight
+ ):
+ raise ValidationError(
+ {
+ "maximum_order_weight": ValidationError(
+ (
+ "Maximum order weight should be larger than the "
+ "minimum order weight."
+ ),
+ code=ShippingErrorCode.MAX_LESS_THAN_MIN,
)
+ }
+ )
return cleaned_input
@@ -264,6 +229,9 @@ class ShippingPriceCreate(ShippingPriceMixin, ModelMutation):
ShippingZone,
description="A shipping zone to which the shipping method belongs.",
)
+ shipping_method = graphene.Field(
+ ShippingMethod, description="A shipping method to create."
+ )
class Arguments:
input = ShippingPriceInput(
@@ -280,8 +248,11 @@ class ShippingPriceCreate(ShippingPriceMixin, ModelMutation):
@classmethod
def success_response(cls, instance):
- response = super().success_response(instance)
- response.shipping_zone = instance.shipping_zone
+ shipping_method = ChannelContext(node=instance, channel_slug=None)
+ response = super().success_response(shipping_method)
+ response.shipping_zone = ChannelContext(
+ node=instance.shipping_zone, channel_slug=None
+ )
return response
@@ -290,6 +261,7 @@ class ShippingPriceUpdate(ShippingPriceMixin, ModelMutation):
ShippingZone,
description="A shipping zone to which the shipping method belongs.",
)
+ shipping_method = graphene.Field(ShippingMethod, description="A shipping method.")
class Arguments:
id = graphene.ID(description="ID of a shipping price to update.", required=True)
@@ -307,8 +279,12 @@ class ShippingPriceUpdate(ShippingPriceMixin, ModelMutation):
@classmethod
def success_response(cls, instance):
- response = super().success_response(instance)
- response.shipping_zone = instance.shipping_zone
+ shipping_method = ChannelContext(node=instance, channel_slug=None)
+ response = super().success_response(shipping_method)
+
+ response.shipping_zone = ChannelContext(
+ node=instance.shipping_zone, channel_slug=None
+ )
return response
@@ -340,5 +316,6 @@ class ShippingPriceDelete(BaseMutation):
shipping_method.delete()
shipping_method.id = shipping_method_id
return ShippingPriceDelete(
- shipping_method=shipping_method, shipping_zone=shipping_zone
+ shipping_method=ChannelContext(node=shipping_method, channel_slug=None),
+ shipping_zone=ChannelContext(node=shipping_zone, channel_slug=None),
)
diff --git a/saleor/graphql/shipping/resolvers.py b/saleor/graphql/shipping/resolvers.py
index 9723d5099a..1846302890 100644
--- a/saleor/graphql/shipping/resolvers.py
+++ b/saleor/graphql/shipping/resolvers.py
@@ -1,5 +1,23 @@
+from prices import MoneyRange
+
from ...shipping import models
+from ..channel.types import ChannelContext
+
+
+def resolve_shipping_zones(channel_slug):
+ instances = models.ShippingZone.objects.all()
+ shipping_zones = [
+ ChannelContext(node=shipping_zone, channel_slug=channel_slug)
+ for shipping_zone in instances
+ ]
+ return shipping_zones
+
+def resolve_price_range(channel_slug):
+ # TODO: Add dataloader.
+ channel_listing = models.ShippingMethodChannelListing.objects.filter(
+ channel__slug=str(channel_slug)
+ )
+ prices = [shipping.get_total() for shipping in channel_listing]
-def resolve_shipping_zones(info):
- return models.ShippingZone.objects.all()
+ return MoneyRange(min(prices), max(prices)) if prices else None
diff --git a/saleor/graphql/shipping/schema.py b/saleor/graphql/shipping/schema.py
index 0a275bfc56..aad318435d 100644
--- a/saleor/graphql/shipping/schema.py
+++ b/saleor/graphql/shipping/schema.py
@@ -1,11 +1,13 @@
import graphene
from ...core.permissions import ShippingPermissions
+from ..channel.types import ChannelContext
from ..core.fields import PrefetchingConnectionField
from ..decorators import permission_required
from ..translations.mutations import ShippingPriceTranslate
from .bulk_mutations import ShippingPriceBulkDelete, ShippingZoneBulkDelete
-from .mutations import (
+from .mutations.channels import ShippingMethodChannelListingUpdate
+from .mutations.shippings import (
ShippingPriceCreate,
ShippingPriceDelete,
ShippingPriceUpdate,
@@ -23,22 +25,31 @@ class ShippingQueries(graphene.ObjectType):
id=graphene.Argument(
graphene.ID, description="ID of the shipping zone.", required=True
),
+ channel=graphene.String(
+ description="Slug of a channel for which the data should be returned."
+ ),
description="Look up a shipping zone by ID.",
)
shipping_zones = PrefetchingConnectionField(
- ShippingZone, description="List of the shop's shipping zones."
+ ShippingZone,
+ channel=graphene.String(
+ description="Slug of a channel for which the data should be returned."
+ ),
+ description="List of the shop's shipping zones.",
)
@permission_required(ShippingPermissions.MANAGE_SHIPPING)
- def resolve_shipping_zone(self, info, id):
- return graphene.Node.get_node_from_global_id(info, id, ShippingZone)
+ def resolve_shipping_zone(self, info, id, channel=None):
+ instance = graphene.Node.get_node_from_global_id(info, id, ShippingZone)
+ return ChannelContext(node=instance, channel_slug=channel) if instance else None
@permission_required(ShippingPermissions.MANAGE_SHIPPING)
- def resolve_shipping_zones(self, info, **_kwargs):
- return resolve_shipping_zones(info)
+ def resolve_shipping_zones(self, info, channel=None, **_kwargs):
+ return resolve_shipping_zones(channel)
class ShippingMutations(graphene.ObjectType):
+ shipping_method_channel_listing_update = ShippingMethodChannelListingUpdate.Field()
shipping_price_create = ShippingPriceCreate.Field()
shipping_price_delete = ShippingPriceDelete.Field()
shipping_price_bulk_delete = ShippingPriceBulkDelete.Field()
diff --git a/saleor/graphql/shipping/tests/benchmark/__init__.py b/saleor/graphql/shipping/tests/benchmark/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/graphql/shipping/tests/benchmark/test_shipping_methods.py b/saleor/graphql/shipping/tests/benchmark/test_shipping_methods.py
new file mode 100644
index 0000000000..b0124f9753
--- /dev/null
+++ b/saleor/graphql/shipping/tests/benchmark/test_shipping_methods.py
@@ -0,0 +1,81 @@
+import pytest
+
+from ....tests.utils import get_graphql_content
+
+SHIPPING_METHODS_QUERY = """
+query GetShippingMethods($channel: String) {
+ shippingZones(first: 10, channel: $channel) {
+ edges {
+ node {
+ shippingMethods {
+ id
+ name
+ minimumOrderWeight {
+ unit
+ value
+ }
+ maximumOrderWeight {
+ unit
+ value
+ }
+ type
+ channelListings {
+ id
+ channel {
+ id
+ name
+ }
+ }
+ price {
+ amount
+ currency
+ }
+ maximumOrderPrice {
+ currency
+ amount
+ }
+ minimumOrderPrice {
+ currency
+ amount
+ }
+ }
+ }
+ }
+ }
+}
+"""
+
+
[email protected]_queries(autouse=False)
+def test_vouchers_query_with_channel_slug(
+ staff_api_client,
+ shipping_zones,
+ channel_USD,
+ permission_manage_shipping,
+ count_queries,
+):
+ variables = {"channel": channel_USD.slug}
+ get_graphql_content(
+ staff_api_client.post_graphql(
+ SHIPPING_METHODS_QUERY,
+ variables,
+ permissions=[permission_manage_shipping],
+ check_no_permissions=False,
+ )
+ )
+
+
[email protected]_queries(autouse=False)
+def test_vouchers_query_without_channel_slug(
+ staff_api_client, shipping_zones, permission_manage_shipping, count_queries,
+):
+ get_graphql_content(
+ staff_api_client.post_graphql(
+ SHIPPING_METHODS_QUERY,
+ {},
+ permissions=[permission_manage_shipping],
+ check_no_permissions=False,
+ )
+ )
diff --git a/saleor/graphql/shipping/tests/test_shipping_method.py b/saleor/graphql/shipping/tests/test_shipping_method.py
index 3bb57d95c5..29293be5ab 100644
--- a/saleor/graphql/shipping/tests/test_shipping_method.py
+++ b/saleor/graphql/shipping/tests/test_shipping_method.py
@@ -6,16 +6,26 @@ from ....core.weight import WeightUnits
from ....shipping.error_codes import ShippingErrorCode
from ....shipping.utils import get_countries_without_shipping_zone
from ...core.enums import WeightUnitsEnum
-from ...tests.utils import assert_negative_positive_decimal_value, get_graphql_content
+from ...shipping.resolvers import resolve_price_range
+from ...tests.utils import get_graphql_content
from ..types import ShippingMethodTypeEnum
SHIPPING_ZONE_QUERY = """
- query ShippingQuery($id: ID!) {
- shippingZone(id: $id) {
+ query ShippingQuery($id: ID!, $channel: String,) {
+ shippingZone(id: $id, channel:$channel) {
name
shippingMethods {
- price {
- amount
+ channelListings {
+ id
+ price {
+ amount
+ }
+ maximumOrderPrice {
+ amount
+ }
+ minimumOrderPrice {
+ amount
+ }
}
minimumOrderWeight {
value
@@ -40,13 +50,13 @@ SHIPPING_ZONE_QUERY = """
def test_shipping_zone_query(
- staff_api_client, shipping_zone, permission_manage_shipping
+ staff_api_client, shipping_zone, permission_manage_shipping, channel_USD
):
# given
shipping = shipping_zone
query = SHIPPING_ZONE_QUERY
ID = graphene.Node.to_global_id("ShippingZone", shipping.id)
- variables = {"id": ID}
+ variables = {"id": ID, "channel": channel_USD.slug}
# when
response = staff_api_client.post_graphql(
@@ -55,19 +65,22 @@ def test_shipping_zone_query(
# then
content = get_graphql_content(response)
-
shipping_data = content["data"]["shippingZone"]
assert shipping_data["name"] == shipping.name
num_of_shipping_methods = shipping_zone.shipping_methods.count()
assert len(shipping_data["shippingMethods"]) == num_of_shipping_methods
- price_range = shipping.price_range
+ price_range = resolve_price_range(channel_slug=channel_USD.slug)
data_price_range = shipping_data["priceRange"]
assert data_price_range["start"]["amount"] == price_range.start.amount
assert data_price_range["stop"]["amount"] == price_range.stop.amount
def test_shipping_zone_query_weights_returned_in_default_unit(
- staff_api_client, shipping_zone, permission_manage_shipping, site_settings
+ staff_api_client,
+ shipping_zone,
+ permission_manage_shipping,
+ site_settings,
+ channel_USD,
):
# given
shipping = shipping_zone
@@ -81,7 +94,7 @@ def test_shipping_zone_query_weights_returned_in_default_unit(
query = SHIPPING_ZONE_QUERY
ID = graphene.Node.to_global_id("ShippingZone", shipping.id)
- variables = {"id": ID}
+ variables = {"id": ID, "channel": channel_USD.slug}
# when
response = staff_api_client.post_graphql(
@@ -95,7 +108,7 @@ def test_shipping_zone_query_weights_returned_in_default_unit(
assert shipping_data["name"] == shipping.name
num_of_shipping_methods = shipping_zone.shipping_methods.count()
assert len(shipping_data["shippingMethods"]) == num_of_shipping_methods
- price_range = shipping.price_range
+ price_range = resolve_price_range(channel_slug=channel_USD.slug)
data_price_range = shipping_data["priceRange"]
assert data_price_range["start"]["amount"] == price_range.start.amount
assert data_price_range["stop"]["amount"] == price_range.stop.amount
@@ -116,32 +129,126 @@ def test_shipping_zones_query(
shipping_zone,
permission_manage_shipping,
permission_manage_products,
+ channel_USD,
):
query = """
- query MultipleShippings {
- shippingZones(first: 100) {
+ query MultipleShippings($channel: String) {
+ shippingZones(first: 100, channel: $channel) {
edges {
- node {
- id
- name
- warehouses {
- id
- name
+ node {
+ id
+ name
+ priceRange {
+ start {
+ amount
+ }
+ stop {
+ amount
+ }
+ }
+ shippingMethods {
+ channelListings {
+ price {
+ amount
+ }
+ }
+ }
+ warehouses {
+ id
+ name
+ }
}
- }
}
totalCount
}
}
"""
num_of_shippings = shipping_zone._meta.model.objects.count()
+ variables = {"channel": channel_USD.slug}
response = staff_api_client.post_graphql(
- query, permissions=[permission_manage_shipping, permission_manage_products]
+ query,
+ variables,
+ permissions=[permission_manage_shipping, permission_manage_products],
)
content = get_graphql_content(response)
assert content["data"]["shippingZones"]["totalCount"] == num_of_shippings
+def test_shipping_methods_query_with_channel(
+ staff_api_client,
+ shipping_zone,
+ shipping_method_channel_PLN,
+ permission_manage_shipping,
+ permission_manage_products,
+ channel_USD,
+):
+ query = """
+ query MultipleShippings($channel: String) {
+ shippingZones(first: 100, channel: $channel) {
+ edges {
+ node {
+ shippingMethods {
+ channelListings {
+ price {
+ amount
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ """
+ shipping_zone.shipping_methods.add(shipping_method_channel_PLN)
+ variables = {"channel": channel_USD.slug}
+ response = staff_api_client.post_graphql(
+ query,
+ variables,
+ permissions=[permission_manage_shipping, permission_manage_products],
+ )
+ content = get_graphql_content(response)
+ assert (
+ len(content["data"]["shippingZones"]["edges"][0]["node"]["shippingMethods"])
+ == 1
+ )
+
+
+def test_shipping_methods_query(
+ staff_api_client,
+ shipping_zone,
+ shipping_method_channel_PLN,
+ permission_manage_shipping,
+ permission_manage_products,
+ channel_USD,
+):
+ query = """
+ query MultipleShippings {
+ shippingZones(first: 100) {
+ edges {
+ node {
+ shippingMethods {
+ channelListings {
+ price {
+ amount
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ """
+ shipping_zone.shipping_methods.add(shipping_method_channel_PLN)
+ response = staff_api_client.post_graphql(
+ query, permissions=[permission_manage_shipping, permission_manage_products],
+ )
+ content = get_graphql_content(response)
+ assert (
+ len(content["data"]["shippingZones"]["edges"][0]["node"]["shippingMethods"])
+ == 2
+ )
+
+
CREATE_SHIPPING_ZONE_QUERY = """
mutation createShipping(
$name: String, $default: Boolean, $countries: [String], $addWarehouses: [ID] ){
@@ -523,13 +630,14 @@ def test_delete_shipping_zone(
PRICE_BASED_SHIPPING_QUERY = """
mutation createShippingPrice(
- $type: ShippingMethodTypeEnum, $name: String!, $price: PositiveDecimal,
- $shippingZone: ID!, $minimumOrderPrice: PositiveDecimal,
- $maximumOrderPrice: PositiveDecimal) {
- shippingPriceCreate(input: {
- name: $name, price: $price, shippingZone: $shippingZone,
- minimumOrderPrice: $minimumOrderPrice,
- maximumOrderPrice: $maximumOrderPrice, type: $type}) {
+ $type: ShippingMethodTypeEnum,
+ $name: String!,
+ $shippingZone: ID!
+ ) {
+ shippingPriceCreate(
+ input: {
+ name: $name, shippingZone: $shippingZone, type: $type
+ }) {
shippingErrors {
field
code
@@ -542,7 +650,9 @@ PRICE_BASED_SHIPPING_QUERY = """
id
}
shippingMethod {
+ id
name
+ channelListings {
price {
amount
}
@@ -552,6 +662,7 @@ PRICE_BASED_SHIPPING_QUERY = """
maximumOrderPrice {
amount
}
+ }
type
}
}
@@ -576,14 +687,10 @@ def test_create_shipping_method(
permission_manage_shipping,
):
name = "DHL"
- price = 12.34
shipping_zone_id = graphene.Node.to_global_id("ShippingZone", shipping_zone.pk)
variables = {
"shippingZone": shipping_zone_id,
"name": name,
- "price": price,
- "minimumOrderPrice": min_price,
- "maximumOrderPrice": max_price,
"type": ShippingMethodTypeEnum.PRICE.name,
}
response = staff_api_client.post_graphql(
@@ -593,169 +700,18 @@ def test_create_shipping_method(
data = content["data"]["shippingPriceCreate"]
assert "errors" not in data["shippingMethod"]
assert data["shippingMethod"]["name"] == name
- assert data["shippingMethod"]["price"]["amount"] == float(price)
- assert data["shippingMethod"]["minimumOrderPrice"] == expected_min_price
- assert data["shippingMethod"]["maximumOrderPrice"] == expected_max_price
assert data["shippingMethod"]["type"] == ShippingMethodTypeEnum.PRICE.name
assert data["shippingZone"]["id"] == shipping_zone_id
-def test_create_shipping_method_with_negative_price(
- staff_api_client, shipping_zone, permission_manage_shipping,
-):
- query = PRICE_BASED_SHIPPING_QUERY
- staff_api_client.user.user_permissions.add(permission_manage_shipping)
- name = "DHL"
- price = -12.34
- shipping_zone_id = graphene.Node.to_global_id("ShippingZone", shipping_zone.pk)
- variables = {
- "shippingZone": shipping_zone_id,
- "name": name,
- "price": price,
- "minimumOrderPrice": 0,
- "maximumOrderPrice": 20,
- "type": ShippingMethodTypeEnum.PRICE.name,
- }
-
- response = staff_api_client.post_graphql(query, variables)
-
- assert_negative_positive_decimal_value(response)
-
-
-def test_create_shipping_price_invalid_price(
- staff_api_client, shipping_zone, permission_manage_shipping,
-):
- query = PRICE_BASED_SHIPPING_QUERY
- staff_api_client.user.user_permissions.add(permission_manage_shipping)
- shipping_zone_id = graphene.Node.to_global_id("ShippingZone", shipping_zone.pk)
- variables = {
- "shippingZone": shipping_zone_id,
- "name": "DHL",
- "price": 1234567891234,
- "minimumOrderPrice": 0,
- "maximumOrderPrice": 20,
- "type": ShippingMethodTypeEnum.PRICE.name,
- }
-
- response = staff_api_client.post_graphql(query, variables)
- content = get_graphql_content(response)
- error = content["data"]["shippingPriceCreate"]["shippingErrors"][0]
- assert error["field"] == "price"
- assert error["code"] == ShippingErrorCode.INVALID.name
-
-
-def test_create_shipping_method_with_to_many_decimal_places_in_price(
- staff_api_client, shipping_zone, permission_manage_shipping,
-): # given
- query = PRICE_BASED_SHIPPING_QUERY
- staff_api_client.user.user_permissions.add(permission_manage_shipping)
- name = "DHL"
- price = 12.345
- shipping_zone_id = graphene.Node.to_global_id("ShippingZone", shipping_zone.pk)
- variables = {
- "shippingZone": shipping_zone_id,
- "name": name,
- "price": price,
- "minimumOrderPrice": 0,
- "maximumOrderPrice": 20,
- "type": ShippingMethodTypeEnum.PRICE.name,
- }
-
- # when
- response = staff_api_client.post_graphql(query, variables)
-
- # then
- content = get_graphql_content(response)
- data = content["data"]["shippingPriceCreate"]
- error = data["shippingErrors"][0]
- assert error["field"] == "price"
- assert error["code"] == ShippingErrorCode.INVALID.name
-
-
-def test_create_shipping_method_with_to_many_decimal_places_in_minimum_order_price(
- staff_api_client, shipping_zone, permission_manage_shipping,
-): # given
- query = PRICE_BASED_SHIPPING_QUERY
- staff_api_client.user.user_permissions.add(permission_manage_shipping)
- name = "DHL"
- price = 12.34
- shipping_zone_id = graphene.Node.to_global_id("ShippingZone", shipping_zone.pk)
- variables = {
- "shippingZone": shipping_zone_id,
- "name": name,
- "price": price,
- "minimumOrderPrice": 1.2001,
- "maximumOrderPrice": 20,
- "type": ShippingMethodTypeEnum.PRICE.name,
- }
-
- # when
- response = staff_api_client.post_graphql(query, variables)
-
- # then
- content = get_graphql_content(response)
- data = content["data"]["shippingPriceCreate"]
- error = data["shippingErrors"][0]
- assert error["field"] == "minimumOrderPrice"
- assert error["code"] == ShippingErrorCode.INVALID.name
-
-
-def test_create_shipping_method_with_to_many_decimal_places_in_maximum_order_price(
- staff_api_client, shipping_zone, permission_manage_shipping,
-): # given
- query = PRICE_BASED_SHIPPING_QUERY
- staff_api_client.user.user_permissions.add(permission_manage_shipping)
- name = "DHL"
- price = 12.34
- shipping_zone_id = graphene.Node.to_global_id("ShippingZone", shipping_zone.pk)
- variables = {
- "shippingZone": shipping_zone_id,
- "name": name,
- "price": price,
- "minimumOrderPrice": 0,
- "maximumOrderPrice": 20.00001,
- "type": ShippingMethodTypeEnum.PRICE.name,
- }
-
- # when
- response = staff_api_client.post_graphql(query, variables)
-
- # then
- content = get_graphql_content(response)
- data = content["data"]["shippingPriceCreate"]
- error = data["shippingErrors"][0]
- assert error["field"] == "maximumOrderPrice"
- assert error["code"] == ShippingErrorCode.INVALID.name
-
-
-def test_create_price_shipping_method_errors(
- shipping_zone, staff_api_client, permission_manage_shipping
-):
- shipping_zone_id = graphene.Node.to_global_id("ShippingZone", shipping_zone.pk)
- variables = {
- "shippingZone": shipping_zone_id,
- "name": "DHL",
- "price": 12.34,
- "minimumOrderPrice": 20,
- "maximumOrderPrice": 10,
- "type": ShippingMethodTypeEnum.PRICE.name,
- }
- response = staff_api_client.post_graphql(
- PRICE_BASED_SHIPPING_QUERY, variables, permissions=[permission_manage_shipping]
- )
- content = get_graphql_content(response)
- data = content["data"]["shippingPriceCreate"]
- assert data["shippingErrors"][0]["code"] == ShippingErrorCode.MAX_LESS_THAN_MIN.name
-
-
WEIGHT_BASED_SHIPPING_QUERY = """
mutation createShippingPrice(
- $type: ShippingMethodTypeEnum, $name: String!, $price: PositiveDecimal,
+ $type: ShippingMethodTypeEnum, $name: String!,
$shippingZone: ID!, $maximumOrderWeight: WeightScalar,
$minimumOrderWeight: WeightScalar) {
shippingPriceCreate(
input: {
- name: $name, price: $price, shippingZone: $shippingZone,
+ name: $name,shippingZone: $shippingZone,
minimumOrderWeight:$minimumOrderWeight,
maximumOrderWeight: $maximumOrderWeight, type: $type}) {
shippingErrors {
@@ -805,7 +761,6 @@ def test_create_weight_based_shipping_method(
variables = {
"shippingZone": shipping_zone_id,
"name": "DHL",
- "price": 12.34,
"minimumOrderWeight": min_weight,
"maximumOrderWeight": max_weight,
"type": ShippingMethodTypeEnum.WEIGHT.name,
@@ -827,7 +782,6 @@ def test_create_weight_shipping_method_errors(
variables = {
"shippingZone": shipping_zone_id,
"name": "DHL",
- "price": 12.34,
"minimumOrderWeight": 20,
"maximumOrderWeight": 15,
"type": ShippingMethodTypeEnum.WEIGHT.name,
@@ -847,7 +801,6 @@ def test_create_shipping_method_with_negative_min_weight(
variables = {
"shippingZone": shipping_zone_id,
"name": "DHL",
- "price": 12.34,
"minimumOrderWeight": -20,
"type": ShippingMethodTypeEnum.WEIGHT.name,
}
@@ -868,7 +821,6 @@ def test_create_shipping_method_with_negative_max_weight(
variables = {
"shippingZone": shipping_zone_id,
"name": "DHL",
- "price": 12.34,
"maximumOrderWeight": -15,
"type": ShippingMethodTypeEnum.WEIGHT.name,
}
@@ -887,12 +839,12 @@ def test_update_shipping_method(
):
query = """
mutation updateShippingPrice(
- $id: ID!, $price: PositiveDecimal, $shippingZone: ID!,
- $type: ShippingMethodTypeEnum!, $minimumOrderPrice: PositiveDecimal) {
+ $id: ID!, $shippingZone: ID!,
+ $type: ShippingMethodTypeEnum!) {
shippingPriceUpdate(
id: $id, input: {
- price: $price, shippingZone: $shippingZone,
- type: $type, minimumOrderPrice: $minimumOrderPrice}) {
+ shippingZone: $shippingZone,
+ type: $type}) {
shippingErrors {
field
code
@@ -901,29 +853,19 @@ def test_update_shipping_method(
id
}
shippingMethod {
- price {
- amount
- }
- minimumOrderPrice {
- amount
- }
type
}
}
}
"""
shipping_method = shipping_zone.shipping_methods.first()
- price = 12.34
- assert not str(shipping_method.price) == price
shipping_zone_id = graphene.Node.to_global_id("ShippingZone", shipping_zone.pk)
shipping_method_id = graphene.Node.to_global_id(
"ShippingMethod", shipping_method.pk
)
variables = {
"shippingZone": shipping_zone_id,
- "price": price,
"id": shipping_method_id,
- "minimumOrderPrice": 12.00,
"type": ShippingMethodTypeEnum.PRICE.name,
}
response = staff_api_client.post_graphql(
@@ -931,7 +873,6 @@ def test_update_shipping_method(
)
content = get_graphql_content(response)
data = content["data"]["shippingPriceUpdate"]
- assert data["shippingMethod"]["price"]["amount"] == float(price)
assert data["shippingZone"]["id"] == shipping_zone_id
diff --git a/saleor/graphql/shipping/tests/test_shipping_method_channel_listing_update.py b/saleor/graphql/shipping/tests/test_shipping_method_channel_listing_update.py
new file mode 100644
index 0000000000..d023435758
--- /dev/null
+++ b/saleor/graphql/shipping/tests/test_shipping_method_channel_listing_update.py
@@ -0,0 +1,468 @@
+import graphene
+
+from ....shipping.error_codes import ShippingErrorCode
+from ....shipping.models import ShippingMethodChannelListing
+from ...tests.utils import assert_negative_positive_decimal_value, get_graphql_content
+
+SHIPPING_METHOD_CHANNEL_LISTING_UPDATE_MUTATION = """
+mutation UpdateShippingMethodChannelListing(
+ $id: ID!
+ $input: ShippingMethodChannelListingInput!
+) {
+ shippingMethodChannelListingUpdate(id: $id, input: $input) {
+ shippingErrors {
+ field
+ message
+ code
+ channels
+ }
+ shippingMethod {
+ name
+ channelListings {
+ price {
+ amount
+ }
+ maximumOrderPrice {
+ amount
+ }
+ minimumOrderPrice {
+ amount
+ }
+ channel {
+ slug
+ }
+ }
+ }
+ }
+}
+"""
+
+
+def test_shipping_method_channel_listing_create_as_staff_user(
+ staff_api_client, shipping_method, permission_manage_shipping, channel_PLN,
+):
+ # given
+ shipping_method_id = graphene.Node.to_global_id(
+ "ShippingMethod", shipping_method.pk
+ )
+ channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ price = 1
+ min_value = 2
+ max_value = 3
+
+ variables = {
+ "id": shipping_method_id,
+ "input": {
+ "addChannels": [
+ {
+ "channelId": channel_id,
+ "price": price,
+ "minimumOrderPrice": min_value,
+ "maximumOrderPrice": max_value,
+ }
+ ]
+ },
+ }
+
+ # when
+
+ response = staff_api_client.post_graphql(
+ SHIPPING_METHOD_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_shipping,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["shippingMethodChannelListingUpdate"]
+ shipping_method_data = data["shippingMethod"]
+ assert not data["shippingErrors"]
+ assert shipping_method_data["name"] == shipping_method.name
+
+ assert shipping_method_data["channelListings"][1]["price"]["amount"] == price
+ assert (
+ shipping_method_data["channelListings"][1]["maximumOrderPrice"]["amount"]
+ == max_value
+ )
+ assert (
+ shipping_method_data["channelListings"][1]["minimumOrderPrice"]["amount"]
+ == min_value
+ )
+ assert (
+ shipping_method_data["channelListings"][1]["channel"]["slug"]
+ == channel_PLN.slug
+ )
+
+
+def test_shipping_method_channel_listing_update_as_staff_user(
+ staff_api_client, shipping_method, permission_manage_shipping, channel_USD,
+):
+ # given
+ shipping_method_id = graphene.Node.to_global_id(
+ "ShippingMethod", shipping_method.pk
+ )
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ min_value = 20
+ max_value = 30
+
+ variables = {
+ "id": shipping_method_id,
+ "input": {
+ "addChannels": [
+ {
+ "channelId": channel_id,
+ "minimumOrderPrice": min_value,
+ "maximumOrderPrice": max_value,
+ }
+ ]
+ },
+ }
+ channel_listing = ShippingMethodChannelListing.objects.get(
+ shipping_method_id=shipping_method.pk, channel_id=channel_USD.id
+ )
+
+ assert channel_listing.price.amount == 10
+ assert channel_listing.minimum_order_price.amount == 0
+ assert channel_listing.maximum_order_price is None
+
+ # when
+ response = staff_api_client.post_graphql(
+ SHIPPING_METHOD_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_shipping,),
+ )
+ content = get_graphql_content(response)
+
+ data = content["data"]["shippingMethodChannelListingUpdate"]
+ shipping_method_data = data["shippingMethod"]
+ assert not data["shippingErrors"]
+ assert shipping_method_data["name"] == shipping_method.name
+
+ # then
+ assert (
+ shipping_method_data["channelListings"][0]["maximumOrderPrice"]["amount"]
+ == max_value
+ )
+ assert (
+ shipping_method_data["channelListings"][0]["minimumOrderPrice"]["amount"]
+ == min_value
+ )
+ assert (
+ shipping_method_data["channelListings"][0]["channel"]["slug"]
+ == channel_USD.slug
+ )
+
+ channel_listing.refresh_from_db()
+
+ assert channel_listing.price.amount == 10
+ assert channel_listing.minimum_order_price.amount == min_value
+ assert channel_listing.maximum_order_price.amount == max_value
+
+
+def test_shipping_method_channel_listing_update_with_negative_price(
+ staff_api_client, shipping_method, permission_manage_shipping, channel_PLN,
+):
+ # given
+ staff_api_client.user.user_permissions.add(permission_manage_shipping)
+ shipping_method_id = graphene.Node.to_global_id(
+ "ShippingMethod", shipping_method.pk
+ )
+ channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ price = -10
+ min_value = 2
+ max_value = 3
+
+ variables = {
+ "id": shipping_method_id,
+ "input": {
+ "addChannels": [
+ {
+ "channelId": channel_id,
+ "price": price,
+ "minimumOrderPrice": min_value,
+ "maximumOrderPrice": max_value,
+ }
+ ]
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ SHIPPING_METHOD_CHANNEL_LISTING_UPDATE_MUTATION, variables=variables,
+ )
+
+ # then
+ assert_negative_positive_decimal_value(response)
+
+
+def test_shipping_method_channel_listing_update_with_negative_min_value(
+ staff_api_client, shipping_method, permission_manage_shipping, channel_PLN,
+):
+ # given
+ staff_api_client.user.user_permissions.add(permission_manage_shipping)
+ shipping_method_id = graphene.Node.to_global_id(
+ "ShippingMethod", shipping_method.pk
+ )
+ channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ price = 10
+ min_value = -2
+ max_value = 3
+
+ variables = {
+ "id": shipping_method_id,
+ "input": {
+ "addChannels": [
+ {
+ "channelId": channel_id,
+ "price": price,
+ "minimumOrderPrice": min_value,
+ "maximumOrderPrice": max_value,
+ }
+ ]
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ SHIPPING_METHOD_CHANNEL_LISTING_UPDATE_MUTATION, variables=variables,
+ )
+
+ # then
+ assert_negative_positive_decimal_value(response)
+
+
+def test_shipping_method_channel_listing_update_with_negative_max_value(
+ staff_api_client, shipping_method, permission_manage_shipping, channel_PLN,
+):
+ # given
+ staff_api_client.user.user_permissions.add(permission_manage_shipping)
+ shipping_method_id = graphene.Node.to_global_id(
+ "ShippingMethod", shipping_method.pk
+ )
+ channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ price = 10
+ max_value = -3
+
+ variables = {
+ "id": shipping_method_id,
+ "input": {
+ "addChannels": [
+ {
+ "channelId": channel_id,
+ "price": price,
+ "maximumOrderPrice": max_value,
+ }
+ ]
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ SHIPPING_METHOD_CHANNEL_LISTING_UPDATE_MUTATION, variables=variables,
+ )
+
+ # then
+ assert_negative_positive_decimal_value(response)
+
+
+def test_shipping_method_channel_listing_update_with_max_less_than_min(
+ staff_api_client, shipping_method, permission_manage_shipping, channel_PLN,
+):
+ # given
+ shipping_method_id = graphene.Node.to_global_id(
+ "ShippingMethod", shipping_method.pk
+ )
+ channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ price = 1
+ min_value = 20
+ max_value = 15
+
+ variables = {
+ "id": shipping_method_id,
+ "input": {
+ "addChannels": [
+ {
+ "channelId": channel_id,
+ "price": price,
+ "minimumOrderPrice": min_value,
+ "maximumOrderPrice": max_value,
+ }
+ ]
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ SHIPPING_METHOD_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_shipping,),
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["shippingMethodChannelListingUpdate"]
+
+ # then
+ assert data["shippingErrors"][0]["field"] == "maximumOrderPrice"
+ assert data["shippingErrors"][0]["code"] == ShippingErrorCode.MAX_LESS_THAN_MIN.name
+ assert data["shippingErrors"][0]["channels"] == [channel_id]
+
+
+def test_shipping_method_channel_listing_create_without_price(
+ staff_api_client, shipping_method, permission_manage_shipping, channel_PLN,
+):
+ # given
+ shipping_method_id = graphene.Node.to_global_id(
+ "ShippingMethod", shipping_method.pk
+ )
+ channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ min_value = 10
+ max_value = 15
+
+ variables = {
+ "id": shipping_method_id,
+ "input": {
+ "addChannels": [
+ {
+ "channelId": channel_id,
+ "minimumOrderPrice": min_value,
+ "maximumOrderPrice": max_value,
+ }
+ ]
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ SHIPPING_METHOD_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_shipping,),
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["shippingMethodChannelListingUpdate"]
+
+ # then
+ assert data["shippingErrors"][0]["field"] == "price"
+ assert data["shippingErrors"][0]["code"] == ShippingErrorCode.REQUIRED.name
+ assert data["shippingErrors"][0]["channels"] == [channel_id]
+
+
+def test_shipping_method_channel_listing_update_with_to_many_decimal_places_in_price(
+ staff_api_client, shipping_method, permission_manage_shipping, channel_PLN,
+):
+ # given
+ shipping_method_id = graphene.Node.to_global_id(
+ "ShippingMethod", shipping_method.pk
+ )
+ channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ price = 10.1234
+ min_value = 2
+ max_value = 3
+
+ variables = {
+ "id": shipping_method_id,
+ "input": {
+ "addChannels": [
+ {
+ "channelId": channel_id,
+ "price": price,
+ "minimumOrderPrice": min_value,
+ "maximumOrderPrice": max_value,
+ }
+ ]
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ SHIPPING_METHOD_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_shipping,),
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["shippingMethodChannelListingUpdate"]
+
+ # then
+ assert data["shippingErrors"][0]["field"] == "price"
+ assert data["shippingErrors"][0]["code"] == ShippingErrorCode.INVALID.name
+ assert data["shippingErrors"][0]["channels"] == [channel_id]
+
+
+def test_shipping_method_channel_listing_update_with_to_many_decimal_places_in_min_val(
+ staff_api_client, shipping_method, permission_manage_shipping, channel_PLN,
+):
+ # given
+ shipping_method_id = graphene.Node.to_global_id(
+ "ShippingMethod", shipping_method.pk
+ )
+ channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ price = 10
+ min_value = 2.1234
+ max_value = 3
+
+ variables = {
+ "id": shipping_method_id,
+ "input": {
+ "addChannels": [
+ {
+ "channelId": channel_id,
+ "price": price,
+ "minimumOrderPrice": min_value,
+ "maximumOrderPrice": max_value,
+ }
+ ]
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ SHIPPING_METHOD_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_shipping,),
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["shippingMethodChannelListingUpdate"]
+
+ # then
+ assert data["shippingErrors"][0]["field"] == "minimumOrderPrice"
+ assert data["shippingErrors"][0]["code"] == ShippingErrorCode.INVALID.name
+ assert data["shippingErrors"][0]["channels"] == [channel_id]
+
+
+def test_shipping_method_channel_listing_update_with_to_many_decimal_places_in_max_val(
+ staff_api_client, shipping_method, permission_manage_shipping, channel_PLN,
+):
+ # given
+ shipping_method_id = graphene.Node.to_global_id(
+ "ShippingMethod", shipping_method.pk
+ )
+ channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+ price = 10
+ min_value = 2
+ max_value = 3.1234
+
+ variables = {
+ "id": shipping_method_id,
+ "input": {
+ "addChannels": [
+ {
+ "channelId": channel_id,
+ "price": price,
+ "minimumOrderPrice": min_value,
+ "maximumOrderPrice": max_value,
+ }
+ ]
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ SHIPPING_METHOD_CHANNEL_LISTING_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_shipping,),
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["shippingMethodChannelListingUpdate"]
+
+ # then
+ assert data["shippingErrors"][0]["field"] == "maximumOrderPrice"
+ assert data["shippingErrors"][0]["code"] == ShippingErrorCode.INVALID.name
+ assert data["shippingErrors"][0]["channels"] == [channel_id]
diff --git a/saleor/graphql/shipping/types.py b/saleor/graphql/shipping/types.py
index 0a657f2dbb..9a4d8f90fb 100644
--- a/saleor/graphql/shipping/types.py
+++ b/saleor/graphql/shipping/types.py
@@ -1,24 +1,73 @@
import graphene
from graphene import relay
+from ...core.permissions import ShippingPermissions
from ...core.weight import convert_weight_to_default_weight_unit
from ...shipping import models
+from ..channel.dataloaders import ChannelByIdLoader
+from ..channel.types import (
+ ChannelContext,
+ ChannelContextType,
+ ChannelContextTypeWithMetadata,
+)
from ..core.connection import CountableDjangoObjectType
-from ..core.types import CountryDisplay, MoneyRange
+from ..core.types import CountryDisplay, Money, MoneyRange
+from ..decorators import permission_required
from ..meta.types import ObjectWithMetadata
+from ..shipping.resolvers import resolve_price_range
from ..translations.fields import TranslationField
from ..translations.types import ShippingMethodTranslation
from ..warehouse.types import Warehouse
+from .dataloaders import (
+ ShippingMethodChannelListingByShippingMethodIdAndChannelSlugLoader,
+ ShippingMethodChannelListingByShippingMethodIdLoader,
+ ShippingMethodsByShippingZoneIdAndChannelSlugLoader,
+ ShippingMethodsByShippingZoneIdLoader,
+)
from .enums import ShippingMethodTypeEnum
-class ShippingMethod(CountableDjangoObjectType):
+class ShippingMethodChannelListing(CountableDjangoObjectType):
+ class Meta:
+ description = "Represents shipping method channel listing."
+ model = models.ShippingMethodChannelListing
+ interfaces = [relay.Node]
+ only_fields = [
+ "id",
+ "channel",
+ "price",
+ "maximum_order_price",
+ "minimum_order_price",
+ ]
+
+ @staticmethod
+ def resolve_channel(root: models.ShippingMethodChannelListing, info, **_kwargs):
+ return ChannelByIdLoader(info.context).load(root.channel_id)
+
+
+class ShippingMethod(ChannelContextTypeWithMetadata, CountableDjangoObjectType):
type = ShippingMethodTypeEnum(description="Type of the shipping method.")
translation = TranslationField(
- ShippingMethodTranslation, type_name="shipping method"
+ ShippingMethodTranslation,
+ type_name="shipping method",
+ resolver=ChannelContextType.resolve_translation,
+ )
+ channel_listings = graphene.List(
+ graphene.NonNull(ShippingMethodChannelListing),
+ description="List of channels available for the method.",
+ )
+ price = graphene.Field(
+ Money, description="The price of the cheapest variant (including discounts)."
+ )
+ maximum_order_price = graphene.Field(
+ Money, description="The price of the cheapest variant (including discounts)."
+ )
+ minimum_order_price = graphene.Field(
+ Money, description="The price of the cheapest variant (including discounts)."
)
class Meta:
+ default_resolver = ChannelContextType.resolver_with_context
description = (
"Shipping method are the methods you'll use to get customer's orders to "
"them. They are directly exposed to the customers."
@@ -27,24 +76,82 @@ class ShippingMethod(CountableDjangoObjectType):
interfaces = [relay.Node, ObjectWithMetadata]
only_fields = [
"id",
- "maximum_order_price",
"maximum_order_weight",
- "minimum_order_price",
"minimum_order_weight",
"name",
- "price",
]
@staticmethod
- def resolve_maximum_order_weight(root: models.ShippingMethod, *_args):
- return convert_weight_to_default_weight_unit(root.maximum_order_weight)
+ def resolve_price(root: ChannelContext[models.ShippingMethod], info, **_kwargs):
+ # Price field are dynamically generated in available_shipping_methods resolver
+ price = getattr(root.node, "price", None)
+ if price:
+ return price
+
+ if not root.channel_slug:
+ return None
+
+ return (
+ ShippingMethodChannelListingByShippingMethodIdAndChannelSlugLoader(
+ info.context
+ )
+ .load((root.node.id, root.channel_slug))
+ .then(lambda channel_listing: channel_listing.price)
+ )
+
+ @staticmethod
+ def resolve_maximum_order_price(
+ root: ChannelContext[models.ShippingMethod], info, **_kwargs
+ ):
+ if not root.channel_slug:
+ return None
+
+ return (
+ ShippingMethodChannelListingByShippingMethodIdAndChannelSlugLoader(
+ info.context
+ )
+ .load((root.node.id, root.channel_slug))
+ .then(lambda channel_listing: channel_listing.maximum_order_price)
+ )
+
+ @staticmethod
+ def resolve_minimum_order_price(
+ root: ChannelContext[models.ShippingMethod], info, **_kwargs
+ ):
+ if not root.channel_slug:
+ return None
+
+ return (
+ ShippingMethodChannelListingByShippingMethodIdAndChannelSlugLoader(
+ info.context
+ )
+ .load((root.node.id, root.channel_slug))
+ .then(lambda channel_listing: channel_listing.minimum_order_price)
+ )
+
+ @staticmethod
+ def resolve_maximum_order_weight(
+ root: ChannelContext[models.ShippingMethod], *_args
+ ):
+ return convert_weight_to_default_weight_unit(root.node.maximum_order_weight)
@staticmethod
- def resolve_minimum_order_weight(root: models.ShippingMethod, *_args):
- return convert_weight_to_default_weight_unit(root.minimum_order_weight)
+ def resolve_minimum_order_weight(
+ root: ChannelContext[models.ShippingMethod], *_args
+ ):
+ return convert_weight_to_default_weight_unit(root.node.minimum_order_weight)
+ @staticmethod
+ @permission_required(ShippingPermissions.MANAGE_SHIPPING)
+ def resolve_channel_listings(
+ root: ChannelContext[models.ShippingMethod], info, **_kwargs
+ ):
+ return ShippingMethodChannelListingByShippingMethodIdLoader(info.context).load(
+ root.node.id
+ )
-class ShippingZone(CountableDjangoObjectType):
+
+class ShippingZone(ChannelContextTypeWithMetadata, CountableDjangoObjectType):
price_range = graphene.Field(
MoneyRange, description="Lowest and highest prices for the shipping."
)
@@ -63,6 +170,7 @@ class ShippingZone(CountableDjangoObjectType):
)
class Meta:
+ default_resolver = ChannelContextType.resolver_with_context
description = (
"Represents a shipping zone in the shop. Zones are the concept used only "
"for grouping shipping methods in the dashboard, and are never exposed to "
@@ -73,20 +181,41 @@ class ShippingZone(CountableDjangoObjectType):
only_fields = ["default", "id", "name"]
@staticmethod
- def resolve_price_range(root: models.ShippingZone, *_args):
- return root.price_range
+ def resolve_price_range(root: ChannelContext[models.ShippingZone], *_args):
+ return resolve_price_range(root.channel_slug)
@staticmethod
- def resolve_countries(root: models.ShippingZone, *_args):
+ def resolve_countries(root: ChannelContext[models.ShippingZone], *_args):
return [
CountryDisplay(code=country.code, country=country.name)
- for country in root.countries
+ for country in root.node.countries
]
@staticmethod
- def resolve_shipping_methods(root: models.ShippingZone, *_args):
- return root.shipping_methods.all()
+ def resolve_shipping_methods(
+ root: ChannelContext[models.ShippingZone], info, **_kwargs
+ ):
+ def wrap_shipping_method_with_channel_context(shipping_methods):
+ shipping_methods = [
+ ChannelContext(node=shipping, channel_slug=root.channel_slug)
+ for shipping in shipping_methods
+ ]
+ return shipping_methods
+
+ channel_slug = root.channel_slug
+ if channel_slug:
+ return (
+ ShippingMethodsByShippingZoneIdAndChannelSlugLoader(info.context)
+ .load((root.node.id, channel_slug))
+ .then(wrap_shipping_method_with_channel_context)
+ )
+
+ return (
+ ShippingMethodsByShippingZoneIdLoader(info.context)
+ .load(root.node.id)
+ .then(wrap_shipping_method_with_channel_context)
+ )
@staticmethod
- def resolve_warehouses(root: models.ShippingZone, *_args):
- return root.warehouses.all()
+ def resolve_warehouses(root: ChannelContext[models.ShippingZone], *_args):
+ return root.node.warehouses.all()
diff --git a/saleor/graphql/shop/mutations.py b/saleor/graphql/shop/mutations.py
index 1a412b3563..89b23ae177 100644
--- a/saleor/graphql/shop/mutations.py
+++ b/saleor/graphql/shop/mutations.py
@@ -11,7 +11,6 @@ from ..account.types import AddressInput
from ..core.enums import WeightUnitsEnum
from ..core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation
from ..core.types.common import ShopError
-from ..product.types import Collection
from .types import AuthorizationKey, AuthorizationKeyType, Shop
@@ -178,30 +177,6 @@ class ShopFetchTaxRates(BaseMutation):
return ShopFetchTaxRates(shop=Shop())
-class HomepageCollectionUpdate(BaseMutation):
- shop = graphene.Field(Shop, description="Updated shop.")
-
- class Arguments:
- collection = graphene.ID(description="Collection displayed on homepage.")
-
- class Meta:
- description = "Updates homepage collection of the shop."
- permissions = (SitePermissions.MANAGE_SETTINGS,)
- error_type_class = ShopError
- error_type_field = "shop_errors"
-
- @classmethod
- def perform_mutation(cls, _root, info, collection=None):
- new_collection = cls.get_node_or_error(
- info, collection, field="collection", only_type=Collection
- )
- site_settings = info.context.site.settings
- site_settings.homepage_collection = new_collection
- cls.clean_instance(info, site_settings)
- site_settings.save(update_fields=["homepage_collection"])
- return HomepageCollectionUpdate(shop=Shop())
-
-
class AuthorizationKeyInput(graphene.InputObjectType):
key = graphene.String(
required=True, description="Client authorization key (client ID)."
diff --git a/saleor/graphql/shop/schema.py b/saleor/graphql/shop/schema.py
index 4bfa9b96e9..616a278c32 100644
--- a/saleor/graphql/shop/schema.py
+++ b/saleor/graphql/shop/schema.py
@@ -4,7 +4,6 @@ from ..translations.mutations import ShopSettingsTranslate
from .mutations import (
AuthorizationKeyAdd,
AuthorizationKeyDelete,
- HomepageCollectionUpdate,
ShopAddressUpdate,
ShopDomainUpdate,
ShopFetchTaxRates,
@@ -18,7 +17,7 @@ from .types import Shop
class ShopQueries(graphene.ObjectType):
shop = graphene.Field(
- Shop, description="Return information about the shop.", required=True
+ Shop, description="Return information about the shop.", required=True,
)
def resolve_shop(self, _info):
@@ -33,7 +32,6 @@ class ShopMutations(graphene.ObjectType):
staff_notification_recipient_update = StaffNotificationRecipientUpdate.Field()
staff_notification_recipient_delete = StaffNotificationRecipientDelete.Field()
- homepage_collection_update = HomepageCollectionUpdate.Field()
shop_domain_update = ShopDomainUpdate.Field()
shop_settings_update = ShopSettingsUpdate.Field()
shop_fetch_tax_rates = ShopFetchTaxRates.Field()
diff --git a/saleor/graphql/shop/tests/test_shop.py b/saleor/graphql/shop/tests/test_shop.py
index b031e862c2..432ad928aa 100644
--- a/saleor/graphql/shop/tests/test_shop.py
+++ b/saleor/graphql/shop/tests/test_shop.py
@@ -76,22 +76,6 @@ def test_query_countries_with_translation(
assert data["countries"][0]["country"] == expected_value
-def test_query_currencies(user_api_client, settings):
- query = """
- query {
- shop {
- currencies
- defaultCurrency
- }
- }
- """
- response = user_api_client.post_graphql(query)
- content = get_graphql_content(response)
- data = content["data"]["shop"]
- assert len(data["currencies"]) == len(settings.AVAILABLE_CURRENCIES)
- assert data["defaultCurrency"] == settings.DEFAULT_CURRENCY
-
-
def test_query_name(user_api_client, site_settings):
query = """
query {
@@ -584,61 +568,6 @@ def test_shop_customer_set_password_url_update_invalid_url(
assert not site_settings.customer_set_password_url
-def test_homepage_collection_update(
- staff_api_client, collection, permission_manage_settings
-):
- query = """
- mutation homepageCollectionUpdate($collection: ID!) {
- homepageCollectionUpdate(collection: $collection) {
- shop {
- homepageCollection {
- id,
- name
- }
- }
- }
- }
- """
- collection_id = graphene.Node.to_global_id("Collection", collection.id)
- variables = {"collection": collection_id}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_settings]
- )
- content = get_graphql_content(response)
- data = content["data"]["homepageCollectionUpdate"]["shop"]
- assert data["homepageCollection"]["id"] == collection_id
- assert data["homepageCollection"]["name"] == collection.name
- site = Site.objects.get_current()
- assert site.settings.homepage_collection == collection
-
-
-def test_homepage_collection_update_set_null(
- staff_api_client, collection, site_settings, permission_manage_settings
-):
- query = """
- mutation homepageCollectionUpdate($collection: ID) {
- homepageCollectionUpdate(collection: $collection) {
- shop {
- homepageCollection {
- id
- }
- }
- }
- }
- """
- site_settings.homepage_collection = collection
- site_settings.save()
- variables = {"collection": None}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_settings]
- )
- content = get_graphql_content(response)
- data = content["data"]["homepageCollectionUpdate"]["shop"]
- assert data["homepageCollection"] is None
- site_settings.refresh_from_db()
- assert site_settings.homepage_collection is None
-
-
def test_query_default_country(user_api_client, settings):
settings.DEFAULT_COUNTRY = "US"
query = """
@@ -726,11 +655,11 @@ def test_query_available_payment_gateways_specified_currency_USD(
}
-def test_query_available_payment_gateways_specified_currency_PLN(
+def test_query_available_payment_gateways_specified_currency_EUR(
user_api_client, sample_gateway
):
query = AVAILABLE_PAYMENT_GATEWAYS_QUERY
- response = user_api_client.post_graphql(query, {"currency": "PLN"})
+ response = user_api_client.post_graphql(query, {"currency": "EUR"})
content = get_graphql_content(response)
data = content["data"]["shop"]["availablePaymentGateways"]
assert data[0]["id"] == "sampleDummy.active"
diff --git a/saleor/graphql/shop/types.py b/saleor/graphql/shop/types.py
index 78bc05880a..794c8c54ad 100644
--- a/saleor/graphql/shop/types.py
+++ b/saleor/graphql/shop/types.py
@@ -11,9 +11,9 @@ from ...account import models as account_models
from ...core.permissions import SitePermissions, get_permissions
from ...core.utils import get_client_ip, get_country_by_ip
from ...plugins.manager import get_plugins_manager
-from ...product import models as product_models
from ...site import models as site_models
from ..account.types import Address, StaffNotificationRecipient
+from ..channel import ChannelContext
from ..checkout.types import PaymentGateway
from ..core.enums import WeightUnitsEnum
from ..core.types.common import CountryDisplay, LanguageDisplay, Permission
@@ -21,7 +21,6 @@ from ..core.utils import str_to_enum
from ..decorators import permission_required
from ..menu.dataloaders import MenuByIdLoader
from ..menu.types import Menu
-from ..product.types import Collection
from ..translations.enums import LanguageCodeEnum
from ..translations.fields import TranslationField
from ..translations.resolvers import resolve_translation
@@ -118,14 +117,6 @@ class Shop(graphene.ObjectType):
)
description = graphene.String(description="Shop's description.")
domain = graphene.Field(Domain, required=True, description="Shop's domain data.")
- homepage_collection = graphene.Field(
- Collection,
- description="Collection displayed on homepage.",
- deprecation_reason=(
- "Use the `collection` query with the `slug` parameter. "
- "This field will be removed in Saleor 3.0"
- ),
- )
languages = graphene.List(
LanguageDisplay,
description="List of the shops's supported languages.",
@@ -206,10 +197,6 @@ class Shop(graphene.ObjectType):
for country in countries
]
- @staticmethod
- def resolve_currencies(_, _info):
- return settings.AVAILABLE_CURRENCIES
-
@staticmethod
def resolve_domain(_, info):
site = info.context.site
@@ -229,20 +216,10 @@ class Shop(graphene.ObjectType):
)
return Geolocalization(country=None)
- @staticmethod
- def resolve_default_currency(_, _info):
- return settings.DEFAULT_CURRENCY
-
@staticmethod
def resolve_description(_, info):
return info.context.site.settings.description
- @staticmethod
- def resolve_homepage_collection(_, info):
- collection_pk = info.context.site.settings.homepage_collection_id
- qs = product_models.Collection.objects.all()
- return qs.filter(pk=collection_pk).first()
-
@staticmethod
def resolve_languages(_, _info):
return [
@@ -259,16 +236,21 @@ class Shop(graphene.ObjectType):
@staticmethod
def resolve_navigation(_, info):
site_settings = info.context.site.settings
- main = (
- MenuByIdLoader(info.context).load(site_settings.top_menu_id)
- if site_settings.top_menu_id
- else None
- )
- secondary = (
- MenuByIdLoader(info.context).load(site_settings.bottom_menu_id)
- if site_settings.bottom_menu_id
- else None
- )
+ main = None
+ if site_settings.top_menu_id:
+ main = (
+ MenuByIdLoader(info.context)
+ .load(site_settings.top_menu_id)
+ .then(lambda menu: ChannelContext(node=menu, channel_slug=None))
+ )
+ secondary = None
+ if site_settings.bottom_menu_id:
+ secondary = (
+ MenuByIdLoader(info.context)
+ .load(site_settings.bottom_menu_id)
+ .then(lambda menu: ChannelContext(node=menu, channel_slug=None))
+ )
+
return Navigation(main=main, secondary=secondary)
@staticmethod
diff --git a/saleor/graphql/translations/mutations.py b/saleor/graphql/translations/mutations.py
index 2d3e31cccc..2724b30ef2 100644
--- a/saleor/graphql/translations/mutations.py
+++ b/saleor/graphql/translations/mutations.py
@@ -7,8 +7,11 @@ from ...menu import models as menu_models
from ...page import models as page_models
from ...product import models as product_models
from ...shipping import models as shipping_models
+from ..channel import ChannelContext
from ..core.mutations import BaseMutation, ModelMutation, registry
from ..core.types.common import TranslationError
+from ..core.utils import from_global_id_strict_type
+from ..product.types import Product, ProductVariant
from ..shop.types import Shop
from .enums import LanguageCodeEnum
@@ -82,6 +85,21 @@ class ProductTranslate(BaseTranslateMutation):
error_type_class = TranslationError
error_type_field = "translation_errors"
+ @classmethod
+ def perform_mutation(cls, _root, info, **data):
+ if "id" in data and not data["id"]:
+ raise ValidationError(
+ {"id": ValidationError("This field is required", code="required")}
+ )
+
+ product_pk = from_global_id_strict_type(data["id"], Product, field="id")
+ product = product_models.Product.objects.get(pk=product_pk)
+ product.translations.update_or_create(
+ language_code=data["language_code"], defaults=data["input"]
+ )
+ product = ChannelContext(node=product, channel_slug=None)
+ return cls(**{cls._meta.return_field_name: product})
+
class CollectionTranslate(BaseTranslateMutation):
class Arguments:
@@ -97,6 +115,12 @@ class CollectionTranslate(BaseTranslateMutation):
error_type_class = TranslationError
error_type_field = "translation_errors"
+ @classmethod
+ def perform_mutation(cls, _root, info, **data):
+ response = super().perform_mutation(_root, info, **data)
+ instance = ChannelContext(node=response.collection, channel_slug=None)
+ return cls(**{cls._meta.return_field_name: instance})
+
class ProductVariantTranslate(BaseTranslateMutation):
class Arguments:
@@ -112,6 +136,21 @@ class ProductVariantTranslate(BaseTranslateMutation):
error_type_class = TranslationError
error_type_field = "translation_errors"
+ @classmethod
+ def perform_mutation(cls, _root, info, **data):
+ if "id" in data and not data["id"]:
+ raise ValidationError(
+ {"id": ValidationError("This field is required", code="required")}
+ )
+
+ variant_pk = from_global_id_strict_type(data["id"], ProductVariant, field="id")
+ variant = product_models.ProductVariant.objects.get(pk=variant_pk)
+ variant.translations.update_or_create(
+ language_code=data["language_code"], defaults=data["input"]
+ )
+ variant = ChannelContext(node=variant, channel_slug=None)
+ return cls(**{cls._meta.return_field_name: variant})
+
class AttributeTranslate(BaseTranslateMutation):
class Arguments:
@@ -157,6 +196,12 @@ class SaleTranslate(BaseTranslateMutation):
error_type_class = TranslationError
error_type_field = "translation_errors"
+ @classmethod
+ def perform_mutation(cls, _root, info, **data):
+ response = super().perform_mutation(_root, info, **data)
+ instance = ChannelContext(node=response.sale, channel_slug=None)
+ return cls(**{cls._meta.return_field_name: instance})
+
class VoucherTranslate(BaseTranslateMutation):
class Arguments:
@@ -172,6 +217,12 @@ class VoucherTranslate(BaseTranslateMutation):
error_type_class = TranslationError
error_type_field = "translation_errors"
+ @classmethod
+ def perform_mutation(cls, _root, info, **data):
+ response = super().perform_mutation(_root, info, **data)
+ instance = ChannelContext(node=response.voucher, channel_slug=None)
+ return cls(**{cls._meta.return_field_name: instance})
+
class ShippingPriceTranslate(BaseTranslateMutation):
class Arguments:
@@ -187,6 +238,12 @@ class ShippingPriceTranslate(BaseTranslateMutation):
error_type_class = TranslationError
error_type_field = "translation_errors"
+ @classmethod
+ def perform_mutation(cls, _root, info, **data):
+ response = super().perform_mutation(_root, info, **data)
+ instance = ChannelContext(node=response.shippingMethod, channel_slug=None)
+ return cls(**{cls._meta.return_field_name: instance})
+
class MenuItemTranslate(BaseTranslateMutation):
class Arguments:
@@ -202,6 +259,12 @@ class MenuItemTranslate(BaseTranslateMutation):
error_type_class = TranslationError
error_type_field = "translation_errors"
+ @classmethod
+ def perform_mutation(cls, _root, info, **data):
+ response = super().perform_mutation(_root, info, **data)
+ instance = ChannelContext(node=response.menuItem, channel_slug=None)
+ return cls(**{cls._meta.return_field_name: instance})
+
class PageTranslationInput(SeoTranslationInput):
title = graphene.String()
diff --git a/saleor/graphql/translations/resolvers.py b/saleor/graphql/translations/resolvers.py
index 775cb31eb0..ace7c4e0d6 100644
--- a/saleor/graphql/translations/resolvers.py
+++ b/saleor/graphql/translations/resolvers.py
@@ -1,3 +1,4 @@
+from ...discount import models as discount_models
from ...product import models as product_models
from ...shipping import models as shipping_models
@@ -13,3 +14,23 @@ def resolve_shipping_methods(info):
def resolve_attribute_values(info):
return product_models.AttributeValue.objects.all()
+
+
+def resolve_products(_info):
+ return product_models.Product.objects.all()
+
+
+def resolve_product_variants(_info):
+ return product_models.ProductVariant.objects.all()
+
+
+def resolve_sales(_info):
+ return discount_models.Sale.objects.all()
+
+
+def resolve_vouchers(_info):
+ return discount_models.Voucher.objects.all()
+
+
+def resolve_collections(_info):
+ return product_models.Collection.objects.all()
diff --git a/saleor/graphql/translations/schema.py b/saleor/graphql/translations/schema.py
index 8debed4cac..aef7d20ff3 100644
--- a/saleor/graphql/translations/schema.py
+++ b/saleor/graphql/translations/schema.py
@@ -16,18 +16,19 @@ from ...shipping.models import ShippingMethod
from ..core.connection import CountableConnection
from ..core.fields import BaseConnectionField
from ..decorators import permission_required
-from ..discount.resolvers import resolve_sales, resolve_vouchers
from ..menu.resolvers import resolve_menu_items
from ..page.resolvers import resolve_pages
-from ..product.resolvers import (
- resolve_attributes,
- resolve_categories,
+from ..product.resolvers import resolve_attributes, resolve_categories
+from ..translations import types as translation_types
+from .resolvers import (
+ resolve_attribute_values,
resolve_collections,
resolve_product_variants,
resolve_products,
+ resolve_sales,
+ resolve_shipping_methods,
+ resolve_vouchers,
)
-from ..translations import types as translation_types
-from .resolvers import resolve_attribute_values, resolve_shipping_methods
class TranslatableItem(graphene.Union):
@@ -86,11 +87,12 @@ class TranslationQueries(graphene.ObjectType):
),
)
+ @permission_required(SitePermissions.MANAGE_TRANSLATIONS)
def resolve_translations(self, info, kind, **_kwargs):
if kind == TranslatableKinds.PRODUCT:
return resolve_products(info)
elif kind == TranslatableKinds.COLLECTION:
- return resolve_collections(info, query=None)
+ return resolve_collections(info)
elif kind == TranslatableKinds.CATEGORY:
return resolve_categories(info, query=None)
elif kind == TranslatableKinds.PAGE:
@@ -98,7 +100,7 @@ class TranslationQueries(graphene.ObjectType):
elif kind == TranslatableKinds.SHIPPING_METHOD:
return resolve_shipping_methods(info)
elif kind == TranslatableKinds.VOUCHER:
- return resolve_vouchers(info, query=None)
+ return resolve_vouchers(info)
elif kind == TranslatableKinds.ATTRIBUTE:
return resolve_attributes(info)
elif kind == TranslatableKinds.ATTRIBUTE_VALUE:
@@ -108,7 +110,7 @@ class TranslationQueries(graphene.ObjectType):
elif kind == TranslatableKinds.MENU_ITEM:
return resolve_menu_items(info, query=None)
elif kind == TranslatableKinds.SALE:
- return resolve_sales(info, query=None)
+ return resolve_sales(info)
@permission_required(SitePermissions.MANAGE_TRANSLATIONS)
def resolve_translation(self, info, id, kind, **_kwargs):
diff --git a/saleor/graphql/translations/tests/test_translations.py b/saleor/graphql/translations/tests/test_translations.py
index c32fa52fbb..ca3f98489b 100644
--- a/saleor/graphql/translations/tests/test_translations.py
+++ b/saleor/graphql/translations/tests/test_translations.py
@@ -7,12 +7,12 @@ from ..schema import TranslatableKinds
from ..types import LanguageCodeEnum
-def test_product_translation(user_api_client, product):
+def test_product_translation(user_api_client, product, channel_USD):
product.translations.create(language_code="pl", name="Produkt")
query = """
- query productById($productId: ID!) {
- product(id: $productId) {
+ query productById($productId: ID!, $channel: String) {
+ product(id: $productId, channel: $channel) {
translation(languageCode: PL) {
name
language {
@@ -24,19 +24,21 @@ def test_product_translation(user_api_client, product):
"""
product_id = graphene.Node.to_global_id("Product", product.id)
- response = user_api_client.post_graphql(query, {"productId": product_id})
+ response = user_api_client.post_graphql(
+ query, {"productId": product_id, "channel": channel_USD.slug}
+ )
data = get_graphql_content(response)["data"]
assert data["product"]["translation"]["name"] == "Produkt"
assert data["product"]["translation"]["language"]["code"] == "PL"
-def test_product_variant_translation(user_api_client, variant):
+def test_product_variant_translation(user_api_client, variant, channel_USD):
variant.translations.create(language_code="pl", name="Wariant")
query = """
- query productVariantById($productVariantId: ID!) {
- productVariant(id: $productVariantId) {
+ query productVariantById($productVariantId: ID!, $channel: String) {
+ productVariant(id: $productVariantId, channel: $channel) {
translation(languageCode: PL) {
name
language {
@@ -49,7 +51,7 @@ def test_product_variant_translation(user_api_client, variant):
product_variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
response = user_api_client.post_graphql(
- query, {"productVariantId": product_variant_id}
+ query, {"productVariantId": product_variant_id, "channel": channel_USD.slug}
)
data = get_graphql_content(response)["data"]
@@ -57,12 +59,12 @@ def test_product_variant_translation(user_api_client, variant):
assert data["productVariant"]["translation"]["language"]["code"] == "PL"
-def test_collection_translation(user_api_client, collection):
- collection.translations.create(language_code="pl", name="Kolekcja")
+def test_collection_translation(user_api_client, published_collection, channel_USD):
+ published_collection.translations.create(language_code="pl", name="Kolekcja")
query = """
- query collectionById($collectionId: ID!) {
- collection(id: $collectionId) {
+ query collectionById($collectionId: ID!, $channel: String) {
+ collection(id: $collectionId, channel: $channel) {
translation(languageCode: PL) {
name
language {
@@ -73,8 +75,9 @@ def test_collection_translation(user_api_client, collection):
}
"""
- collection_id = graphene.Node.to_global_id("Collection", collection.id)
- response = user_api_client.post_graphql(query, {"collectionId": collection_id})
+ collection_id = graphene.Node.to_global_id("Collection", published_collection.id)
+ variables = {"collectionId": collection_id, "channel": channel_USD.slug}
+ response = user_api_client.post_graphql(query, variables)
data = get_graphql_content(response)["data"]
assert data["collection"]["translation"]["name"] == "Kolekcja"
@@ -326,10 +329,10 @@ def test_shop_translation(user_api_client, site_settings):
assert data["shop"]["translation"]["language"]["code"] == "PL"
-def test_product_no_translation(user_api_client, product):
+def test_product_no_translation(user_api_client, product, channel_USD):
query = """
- query productById($productId: ID!) {
- product(id: $productId) {
+ query productById($productId: ID!, $channel: String) {
+ product(id: $productId, channel: $channel) {
translation(languageCode: PL) {
name
language {
@@ -341,16 +344,18 @@ def test_product_no_translation(user_api_client, product):
"""
product_id = graphene.Node.to_global_id("Product", product.id)
- response = user_api_client.post_graphql(query, {"productId": product_id})
+ response = user_api_client.post_graphql(
+ query, {"productId": product_id, "channel": channel_USD.slug}
+ )
data = get_graphql_content(response)["data"]
assert data["product"]["translation"] is None
-def test_product_variant_no_translation(user_api_client, variant):
+def test_product_variant_no_translation(user_api_client, variant, channel_USD):
query = """
- query productVariantById($productVariantId: ID!) {
- productVariant(id: $productVariantId) {
+ query productVariantById($productVariantId: ID!, $channel: String) {
+ productVariant(id: $productVariantId, channel: $channel) {
translation(languageCode: PL) {
name
language {
@@ -363,17 +368,17 @@ def test_product_variant_no_translation(user_api_client, variant):
product_variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
response = user_api_client.post_graphql(
- query, {"productVariantId": product_variant_id}
+ query, {"productVariantId": product_variant_id, "channel": channel_USD.slug}
)
data = get_graphql_content(response)["data"]
assert data["productVariant"]["translation"] is None
-def test_collection_no_translation(user_api_client, collection):
+def test_collection_no_translation(user_api_client, published_collection, channel_USD):
query = """
- query collectionById($collectionId: ID!) {
- collection(id: $collectionId) {
+ query collectionById($collectionId: ID!, $channel: String) {
+ collection(id: $collectionId, channel: $channel) {
translation(languageCode: PL) {
name
language {
@@ -384,8 +389,9 @@ def test_collection_no_translation(user_api_client, collection):
}
"""
- collection_id = graphene.Node.to_global_id("Collection", collection.id)
- response = user_api_client.post_graphql(query, {"collectionId": collection_id})
+ collection_id = graphene.Node.to_global_id("Collection", published_collection.id)
+ variables = {"collectionId": collection_id, "channel": channel_USD.slug}
+ response = user_api_client.post_graphql(query, variables)
data = get_graphql_content(response)["data"]
assert data["collection"]["translation"] is None
@@ -715,7 +721,7 @@ def test_product_variant_update_translation(
def test_collection_create_translation(
- staff_api_client, collection, permission_manage_translations
+ staff_api_client, published_collection, permission_manage_translations
):
query = """
mutation collectionTranslate($collectionId: ID!) {
@@ -734,7 +740,7 @@ def test_collection_create_translation(
}
"""
- collection_id = graphene.Node.to_global_id("Collection", collection.id)
+ collection_id = graphene.Node.to_global_id("Collection", published_collection.id)
response = staff_api_client.post_graphql(
query,
{"collectionId": collection_id},
@@ -747,9 +753,9 @@ def test_collection_create_translation(
def test_collection_update_translation(
- staff_api_client, collection, permission_manage_translations
+ staff_api_client, published_collection, permission_manage_translations
):
- collection.translations.create(language_code="pl", name="Kolekcja")
+ published_collection.translations.create(language_code="pl", name="Kolekcja")
query = """
mutation collectionTranslate($collectionId: ID!) {
@@ -768,7 +774,7 @@ def test_collection_update_translation(
}
"""
- collection_id = graphene.Node.to_global_id("Collection", collection.id)
+ collection_id = graphene.Node.to_global_id("Collection", published_collection.id)
response = staff_api_client.post_graphql(
query,
{"collectionId": collection_id},
@@ -1309,9 +1315,10 @@ def test_shop_update_translation(
],
)
def test_translations_query(
- user_api_client,
+ staff_api_client,
+ permission_manage_translations,
product,
- collection,
+ published_collection,
voucher,
sale,
shipping_method,
@@ -1332,13 +1339,17 @@ def test_translations_query(
}
"""
- response = user_api_client.post_graphql(query, {"kind": kind.name})
+ response = staff_api_client.post_graphql(
+ query, {"kind": kind.name}, permissions=[permission_manage_translations]
+ )
data = get_graphql_content(response)["data"]["translations"]
assert data["edges"][0]["node"]["__typename"] == expected_typename
-def test_translations_query_inline_fragment(user_api_client, product):
+def test_translations_query_inline_fragment(
+ staff_api_client, permission_manage_translations, product
+):
product.translations.create(language_code="pl", name="Produkt testowy")
query = """
@@ -1358,7 +1369,9 @@ def test_translations_query_inline_fragment(user_api_client, product):
}
"""
- response = user_api_client.post_graphql(query)
+ response = staff_api_client.post_graphql(
+ query, permissions=[permission_manage_translations]
+ )
data = get_graphql_content(response)["data"]["translations"]["edges"][0]
assert data["node"]["name"] == "Test product"
@@ -1387,27 +1400,11 @@ QUERY_TRANSLATION_PRODUCT = """
"""
- "is_published, perm_codenames, return_product",
- [
- (True, ["manage_translations"], True),
- (False, ["manage_translations"], False),
- (False, ["manage_translations", "manage_products"], True),
- ],
-)
def test_translation_query_product(
- staff_api_client,
- product,
- product_translation_fr,
- is_published,
- perm_codenames,
- return_product,
+ staff_api_client, permission_manage_translations, product, product_translation_fr,
):
- product.is_published = is_published
- product.save()
product_id = graphene.Node.to_global_id("Product", product.id)
- perms = list(Permission.objects.filter(codename__in=perm_codenames))
variables = {
"id": product_id,
@@ -1415,16 +1412,15 @@ def test_translation_query_product(
"languageCode": LanguageCodeEnum.FR.name,
}
response = staff_api_client.post_graphql(
- QUERY_TRANSLATION_PRODUCT, variables, permissions=perms
+ QUERY_TRANSLATION_PRODUCT,
+ variables,
+ permissions=[permission_manage_translations],
)
content = get_graphql_content(response)
data = content["data"]["translation"]
assert data["name"] == product.name
assert data["translation"]["name"] == product_translation_fr.name
- if return_product:
- assert data["product"]["name"] == product.name
- else:
- assert not data["product"]
+ assert data["product"]["name"] == product.name
QUERY_TRANSLATION_COLLECTION = """
@@ -1449,27 +1445,17 @@ QUERY_TRANSLATION_COLLECTION = """
"""
- "is_published, perm_codenames, return_collection",
- [
- (True, ["manage_translations"], True),
- (False, ["manage_translations"], False),
- (False, ["manage_translations", "manage_products"], True),
- ],
-)
def test_translation_query_collection(
staff_api_client,
- collection,
+ published_collection,
collection_translation_fr,
- is_published,
- perm_codenames,
- return_collection,
+ permission_manage_translations,
+ channel_USD,
):
- collection.is_published = is_published
- collection.save()
- collection_id = graphene.Node.to_global_id("Collection", collection.id)
- perms = list(Permission.objects.filter(codename__in=perm_codenames))
+ channel_listing = published_collection.channel_listings.get()
+ channel_listing.save()
+ collection_id = graphene.Node.to_global_id("Collection", published_collection.id)
variables = {
"id": collection_id,
@@ -1477,16 +1463,15 @@ def test_translation_query_collection(
"languageCode": LanguageCodeEnum.FR.name,
}
response = staff_api_client.post_graphql(
- QUERY_TRANSLATION_COLLECTION, variables, permissions=perms
+ QUERY_TRANSLATION_COLLECTION,
+ variables,
+ permissions=[permission_manage_translations],
)
content = get_graphql_content(response)
data = content["data"]["translation"]
- assert data["name"] == collection.name
+ assert data["name"] == published_collection.name
assert data["translation"]["name"] == collection_translation_fr.name
- if return_collection:
- assert data["collection"]["name"] == collection.name
- else:
- assert not data["collection"]
+ assert data["collection"]["name"] == published_collection.name
QUERY_TRANSLATION_CATEGORY = """
@@ -1649,45 +1634,29 @@ QUERY_TRANSLATION_VARIANT = """
"""
- "is_published, perm_codenames, return_variant",
- [
- (True, ["manage_translations"], True),
- (False, ["manage_translations"], False),
- (False, ["manage_translations", "manage_products"], True),
- ],
-)
def test_translation_query_variant(
staff_api_client,
+ permission_manage_translations,
product,
variant,
variant_translation_fr,
- is_published,
- perm_codenames,
- return_variant,
):
- product.is_published = is_published
- product.save()
-
variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
- perms = list(Permission.objects.filter(codename__in=perm_codenames))
-
variables = {
"id": variant_id,
"kind": TranslatableKinds.VARIANT.name,
"languageCode": LanguageCodeEnum.FR.name,
}
response = staff_api_client.post_graphql(
- QUERY_TRANSLATION_VARIANT, variables, permissions=perms
+ QUERY_TRANSLATION_VARIANT,
+ variables,
+ permissions=[permission_manage_translations],
)
content = get_graphql_content(response)
data = content["data"]["translation"]
assert data["name"] == variant.name
assert data["translation"]["name"] == variant_translation_fr.name
- if return_variant:
- assert data["productVariant"]["name"] == variant.name
- else:
- assert not data["productVariant"]
+ assert data["productVariant"]["name"] == variant.name
QUERY_TRANSLATION_PAGE = """
diff --git a/saleor/graphql/translations/types.py b/saleor/graphql/translations/types.py
index b35b0eed60..423fbc472a 100644
--- a/saleor/graphql/translations/types.py
+++ b/saleor/graphql/translations/types.py
@@ -8,6 +8,7 @@ from ...page import models as page_models
from ...product import models as product_models
from ...shipping import models as shipping_models
from ...site import models as site_models
+from ..channel import ChannelContext
from ..core.connection import CountableDjangoObjectType
from ..core.types import LanguageDisplay
from ..core.utils import str_to_enum
@@ -124,12 +125,7 @@ class ProductVariantTranslatableContent(CountableDjangoObjectType):
@staticmethod
def resolve_product_variant(root: product_models.ProductVariant, info):
- visible_products = product_models.Product.objects.visible_to_user(
- info.context.user
- ).values_list("pk", flat=True)
- return product_models.ProductVariant.objects.filter(
- product__id__in=visible_products, pk=root.id
- ).first()
+ return ChannelContext(node=root, channel_slug=None)
class ProductTranslation(BaseTranslationType):
@@ -153,11 +149,7 @@ class ProductTranslatableContent(CountableDjangoObjectType):
@staticmethod
def resolve_product(root: product_models.Product, info):
- return (
- product_models.Product.objects.visible_to_user(info.context.user)
- .filter(pk=root.id)
- .first()
- )
+ return ChannelContext(node=root, channel_slug=None)
class CollectionTranslation(BaseTranslationType):
@@ -181,10 +173,9 @@ class CollectionTranslatableContent(CountableDjangoObjectType):
@staticmethod
def resolve_collection(root: product_models.Collection, info):
+ collection = product_models.Collection.objects.all().filter(pk=root.id).first()
return (
- product_models.Collection.objects.visible_to_user(info.context.user)
- .filter(pk=root.id)
- .first()
+ ChannelContext(node=collection, channel_slug=None) if collection else None
)
@@ -283,7 +274,7 @@ class VoucherTranslatableContent(CountableDjangoObjectType):
@staticmethod
@permission_required(DiscountPermissions.MANAGE_DISCOUNTS)
def resolve_voucher(root: discount_models.Voucher, _info):
- return root
+ return ChannelContext(node=root, channel_slug=None)
class SaleTranslation(BaseTranslationType):
@@ -311,7 +302,7 @@ class SaleTranslatableContent(CountableDjangoObjectType):
@staticmethod
@permission_required(DiscountPermissions.MANAGE_DISCOUNTS)
def resolve_sale(root: discount_models.Sale, _info):
- return root
+ return ChannelContext(node=root, channel_slug=None)
class ShopTranslation(BaseTranslationType):
@@ -345,7 +336,7 @@ class MenuItemTranslatableContent(CountableDjangoObjectType):
@staticmethod
def resolve_menu_item(root: menu_models.MenuItem, _info):
- return root
+ return ChannelContext(node=root, channel_slug=None)
class ShippingMethodTranslation(BaseTranslationType):
@@ -375,4 +366,4 @@ class ShippingMethodTranslatableContent(CountableDjangoObjectType):
@staticmethod
@permission_required(ShippingPermissions.MANAGE_SHIPPING)
def resolve_shipping_method(root: shipping_models.ShippingMethod, _info):
- return root
+ return ChannelContext(node=root, channel_slug=None)
diff --git a/saleor/graphql/utils/sorting.py b/saleor/graphql/utils/sorting.py
index 412221c2c1..97ddfd2f09 100644
--- a/saleor/graphql/utils/sorting.py
+++ b/saleor/graphql/utils/sorting.py
@@ -71,9 +71,10 @@ def sort_queryset(
sorting_fields = sort_enum.get(sorting_field)
sorting_field_name = sorting_fields.name.lower()
+ channel_slug = getattr(sort_by, "channel", None)
custom_sort_by = getattr(sort_enum, f"qs_with_{sorting_field_name}", None)
if custom_sort_by:
- queryset = custom_sort_by(queryset)
+ queryset = custom_sort_by(queryset, channel_slug=channel_slug)
sorting_field_value = sorting_fields.value
sorting_list = [f"{sorting_direction}{field}" for field in sorting_field_value]
diff --git a/saleor/graphql/warehouse/types.py b/saleor/graphql/warehouse/types.py
index 6274be2c65..008044e624 100644
--- a/saleor/graphql/warehouse/types.py
+++ b/saleor/graphql/warehouse/types.py
@@ -5,6 +5,7 @@ from django.db.models.functions import Coalesce
from ...core.permissions import OrderPermissions, ProductPermissions
from ...warehouse import models
from ..account.enums import CountryCodeEnum
+from ..channel import ChannelContext
from ..core.connection import CountableDjangoObjectType
from ..decorators import one_of_permissions_required
@@ -58,6 +59,15 @@ class Warehouse(CountableDjangoObjectType):
"email",
]
+ @staticmethod
+ def resolve_shipping_zones(root, *_args, **_kwargs):
+ instances = root.shipping_zones.all()
+ shipping_zones = [
+ ChannelContext(node=shipping_zone, channel_slug=None)
+ for shipping_zone in instances
+ ]
+ return shipping_zones
+
class Stock(CountableDjangoObjectType):
quantity = graphene.Int(
@@ -91,6 +101,10 @@ class Stock(CountableDjangoObjectType):
quantity_allocated=Coalesce(Sum("quantity_allocated"), 0)
)["quantity_allocated"]
+ @staticmethod
+ def resolve_product_variant(root, *_args):
+ return ChannelContext(node=root.product_variant, channel_slug=None)
+
class Allocation(CountableDjangoObjectType):
quantity = graphene.Int(required=True, description="Quantity allocated for orders.")
diff --git a/saleor/graphql/wishlist/mutations.py b/saleor/graphql/wishlist/mutations.py
index bc0da9b19c..0815de6c3c 100644
--- a/saleor/graphql/wishlist/mutations.py
+++ b/saleor/graphql/wishlist/mutations.py
@@ -1,5 +1,8 @@
import graphene
+from django.core.exceptions import ValidationError
+from ...product.error_codes import ProductErrorCode
+from ...product.utils import get_products_ids_without_variants
from ..core.mutations import BaseMutation
from ..core.types.common import WishlistError
from ..product.types import Product, ProductVariant
@@ -40,10 +43,25 @@ class WishlistAddProductMutation(_BaseWishlistProductMutation):
product = cls.get_node_or_error(
info, product_id, only_type=Product, field="product_id"
)
+ cls.clean_products([product])
wishlist.add_product(product)
wishlist_items = wishlist.items.all()
return WishlistAddProductMutation(wishlist=wishlist_items)
+ @classmethod
+ def clean_products(cls, products):
+ products_ids_without_variants = get_products_ids_without_variants(products)
+ if products_ids_without_variants:
+ raise ValidationError(
+ {
+ "products": ValidationError(
+ "Cannot manage products without variants.",
+ code=ProductErrorCode.CANNOT_MANAGE_PRODUCT_WITHOUT_VARIANT,
+ params={"products": products_ids_without_variants},
+ )
+ }
+ )
+
class WishlistRemoveProductMutation(_BaseWishlistProductMutation):
class Meta:
diff --git a/saleor/menu/models.py b/saleor/menu/models.py
index 988c41aee5..200633a12a 100644
--- a/saleor/menu/models.py
+++ b/saleor/menu/models.py
@@ -56,11 +56,6 @@ class MenuItem(MPTTModel, SortableModel):
def linked_object(self):
return self.category or self.collection or self.page
- def is_public(self):
- return not self.linked_object or getattr(
- self.linked_object, "is_published", True
- )
-
class MenuItemTranslation(models.Model):
language_code = models.CharField(max_length=10)
diff --git a/saleor/menu/tests/test_menu.py b/saleor/menu/tests/test_menu.py
deleted file mode 100644
index b88f9b7c23..0000000000
--- a/saleor/menu/tests/test_menu.py
+++ /dev/null
@@ -1,23 +0,0 @@
-from ..models import MenuItem
-
-
-def test_menu_item_status(menu, category, collection, page):
- item = MenuItem.objects.create(name="Name", menu=menu)
- assert item.is_public()
-
- item = MenuItem.objects.create(name="Name", menu=menu, collection=collection)
- assert item.is_public()
- collection.is_published = False
- collection.save()
- item.refresh_from_db()
- assert not item.is_public()
-
- item = MenuItem.objects.create(name="Name", menu=menu, category=category)
- assert item.is_public()
-
- item = MenuItem.objects.create(name="Name", menu=menu, page=page)
- assert item.is_public()
- page.is_published = False
- page.save()
- item.refresh_from_db()
- assert not item.is_public()
diff --git a/saleor/order/error_codes.py b/saleor/order/error_codes.py
index 4e90b8f971..120c04c265 100644
--- a/saleor/order/error_codes.py
+++ b/saleor/order/error_codes.py
@@ -27,3 +27,5 @@ class OrderErrorCode(Enum):
ZERO_QUANTITY = "zero_quantity"
INSUFFICIENT_STOCK = "insufficient_stock"
DUPLICATED_INPUT_ITEM = "duplicated_input_item"
+ NOT_AVAILABLE_IN_CHANNEL = "not_available_in_channel"
+ CHANNEL_INACTIVE = "channel_inactive"
diff --git a/saleor/order/migrations/0072_django_price_2.py b/saleor/order/migrations/0072_django_price_2.py
index 7dfb15185b..3f9b82d5ab 100644
--- a/saleor/order/migrations/0072_django_price_2.py
+++ b/saleor/order/migrations/0072_django_price_2.py
@@ -1,5 +1,7 @@
# Generated by Django 2.2.4 on 2019-08-14 09:13
+import os
+
from django.conf import settings
from django.db import migrations, models
@@ -39,7 +41,7 @@ class Migration(migrations.Migration):
model_name="order",
name="currency",
field=models.CharField(
- default=settings.DEFAULT_CURRENCY,
+ default=os.environ.get("DEFAULT_CURRENCY", "USD"),
max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH,
),
),
@@ -47,7 +49,7 @@ class Migration(migrations.Migration):
model_name="orderline",
name="currency",
field=models.CharField(
- default=settings.DEFAULT_CURRENCY,
+ default=os.environ.get("DEFAULT_CURRENCY", "USD"),
max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH,
),
),
diff --git a/saleor/order/migrations/0090_order_channel_listing.py b/saleor/order/migrations/0090_order_channel_listing.py
new file mode 100644
index 0000000000..25964daeb2
--- /dev/null
+++ b/saleor/order/migrations/0090_order_channel_listing.py
@@ -0,0 +1,66 @@
+# Generated by Django 3.1 on 2020-08-19 07:58
+
+import django.db.models.deletion
+from django.db import migrations, models
+from django.utils.text import slugify
+
+
+def add_channel_slug(apps, schema_editor):
+ Channel = apps.get_model("channel", "Channel")
+ Order = apps.get_model("order", "Order")
+
+ channels_dict = {}
+
+ for order in Order.objects.iterator():
+ currency = order.currency
+ channel = channels_dict.get(currency)
+
+ if not channel:
+ name = f"Channel {currency}"
+ channel, _ = Channel.objects.get_or_create(
+ currency_code=currency, defaults={"name": name, "slug": slugify(name)},
+ )
+ channels_dict[currency] = channel
+
+ order.channel = channel
+
+ order.save(update_fields=["channel"])
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("channel", "0001_initial"),
+ ("order", "0089_auto_20200902_1249"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="order",
+ name="channel",
+ field=models.ForeignKey(
+ null=True,
+ on_delete=django.db.models.deletion.PROTECT,
+ related_name="orders",
+ to="channel.channel",
+ ),
+ ),
+ migrations.RunPython(add_channel_slug),
+ migrations.AlterField(
+ model_name="order",
+ name="channel",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.PROTECT,
+ related_name="orders",
+ to="channel.channel",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="order", name="currency", field=models.CharField(max_length=3),
+ ),
+ migrations.AlterField(
+ model_name="orderline",
+ name="currency",
+ field=models.CharField(max_length=3),
+ ),
+ ]
diff --git a/saleor/order/models.py b/saleor/order/models.py
index e97184c840..664c795c05 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -16,6 +16,7 @@ from measurement.measures import Weight
from prices import Money
from ..account.models import Address
+from ..channel.models import Channel
from ..core.models import ModelWithMetadata
from ..core.permissions import OrderPermissions
from ..core.taxes import zero_money, zero_taxed_money
@@ -88,10 +89,7 @@ class Order(ModelWithMetadata):
)
user_email = models.EmailField(blank=True, default="")
- currency = models.CharField(
- max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH,
- default=settings.DEFAULT_CURRENCY,
- )
+ currency = models.CharField(max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH,)
shipping_method = models.ForeignKey(
ShippingMethod,
@@ -103,7 +101,9 @@ class Order(ModelWithMetadata):
shipping_method_name = models.CharField(
max_length=255, null=True, default=None, blank=True, editable=False
)
-
+ channel = models.ForeignKey(
+ Channel, related_name="orders", on_delete=models.PROTECT,
+ )
shipping_price_net_amount = models.DecimalField(
max_digits=settings.DEFAULT_MAX_DIGITS,
decimal_places=settings.DEFAULT_DECIMAL_PLACES,
@@ -206,7 +206,7 @@ class Order(ModelWithMetadata):
]
)
total_captured = [payment.get_captured_amount() for payment in payments]
- total_paid = sum(total_captured, zero_taxed_money())
+ total_paid = sum(total_captured, zero_taxed_money(currency=self.currency))
return total_paid
def _index_billing_phone(self):
@@ -270,7 +270,7 @@ class Order(ModelWithMetadata):
def get_subtotal(self):
subtotal_iterator = (line.get_total() for line in self)
- return sum(subtotal_iterator, zero_taxed_money())
+ return sum(subtotal_iterator, zero_taxed_money(currency=self.currency))
def get_total_quantity(self):
return sum([line.quantity for line in self])
@@ -317,7 +317,7 @@ class Order(ModelWithMetadata):
payment = self.get_last_payment()
if payment:
return payment.get_authorized_amount()
- return zero_money()
+ return zero_money(self.currency)
@property
def total_captured(self):
@@ -328,7 +328,7 @@ class Order(ModelWithMetadata):
ChargeStatus.PARTIALLY_REFUNDED,
):
return Money(payment.captured_amount, payment.currency)
- return zero_money()
+ return zero_money(self.currency)
@property
def total_balance(self):
@@ -375,10 +375,7 @@ class OrderLine(models.Model):
validators=[MinValueValidator(0)], default=0
)
- currency = models.CharField(
- max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH,
- default=settings.DEFAULT_CURRENCY,
- )
+ currency = models.CharField(max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH,)
unit_price_net_amount = models.DecimalField(
max_digits=settings.DEFAULT_MAX_DIGITS,
diff --git a/saleor/order/tests/test_order.py b/saleor/order/tests/test_order.py
index b0394b70c5..48efca8077 100644
--- a/saleor/order/tests/test_order.py
+++ b/saleor/order/tests/test_order.py
@@ -5,7 +5,13 @@ import pytest
from prices import Money, TaxedMoney
from ...core.weight import zero_weight
-from ...discount.models import DiscountValueType, NotApplicable, Voucher, VoucherType
+from ...discount.models import (
+ DiscountValueType,
+ NotApplicable,
+ Voucher,
+ VoucherChannelListing,
+ VoucherType,
+)
from ...discount.utils import validate_voucher_in_order
from ...payment import ChargeStatus
from ...payment.models import Payment
@@ -75,8 +81,9 @@ def test_add_variant_to_draft_order_adds_line_for_variant_with_price_0(
):
order = order_with_lines
variant = product.variants.get()
- variant.price = Money(0, "USD")
- variant.save(update_fields=["price"])
+ variant_channel_listing = variant.channel_listings.get()
+ variant_channel_listing.price = Money(0, "USD")
+ variant_channel_listing.save(update_fields=["price_amount", "currency"])
lines_before = order.lines.count()
settings.LANGUAGE_CODE = "fr"
@@ -88,8 +95,7 @@ def test_add_variant_to_draft_order_adds_line_for_variant_with_price_0(
assert line.quantity == 1
assert line.unit_price == TaxedMoney(net=Money(0, "USD"), gross=Money(0, "USD"))
assert line.translated_product_name == str(variant.product.translated)
- assert line.variant_name == str(variant)
- assert line.product_name == str(variant.product)
+ assert line.product_name == variant.product.name
def test_add_variant_to_draft_order_not_allocates_stock_for_new_variant(
@@ -280,12 +286,14 @@ def test_validate_fulfillment_tracking_number_as_url(fulfilled_order):
assert fulfillment.is_tracking_number_url
-def test_order_queryset_confirmed(draft_order):
+def test_order_queryset_confirmed(draft_order, channel_USD):
other_orders = [
- Order.objects.create(status=OrderStatus.UNFULFILLED),
- Order.objects.create(status=OrderStatus.PARTIALLY_FULFILLED),
- Order.objects.create(status=OrderStatus.FULFILLED),
- Order.objects.create(status=OrderStatus.CANCELED),
+ Order.objects.create(status=OrderStatus.UNFULFILLED, channel=channel_USD),
+ Order.objects.create(
+ status=OrderStatus.PARTIALLY_FULFILLED, channel=channel_USD
+ ),
+ Order.objects.create(status=OrderStatus.FULFILLED, channel=channel_USD),
+ Order.objects.create(status=OrderStatus.CANCELED, channel=channel_USD),
]
confirmed_orders = Order.objects.confirmed()
@@ -294,12 +302,14 @@ def test_order_queryset_confirmed(draft_order):
assert all([order in confirmed_orders for order in other_orders])
-def test_order_queryset_drafts(draft_order):
+def test_order_queryset_drafts(draft_order, channel_USD):
other_orders = [
- Order.objects.create(status=OrderStatus.UNFULFILLED),
- Order.objects.create(status=OrderStatus.PARTIALLY_FULFILLED),
- Order.objects.create(status=OrderStatus.FULFILLED),
- Order.objects.create(status=OrderStatus.CANCELED),
+ Order.objects.create(status=OrderStatus.UNFULFILLED, channel=channel_USD),
+ Order.objects.create(
+ status=OrderStatus.PARTIALLY_FULFILLED, channel=channel_USD
+ ),
+ Order.objects.create(status=OrderStatus.FULFILLED, channel=channel_USD),
+ Order.objects.create(status=OrderStatus.CANCELED, channel=channel_USD),
]
draft_orders = Order.objects.drafts()
@@ -308,11 +318,15 @@ def test_order_queryset_drafts(draft_order):
assert all([order not in draft_orders for order in other_orders])
-def test_order_queryset_to_ship(settings):
+def test_order_queryset_to_ship(settings, channel_USD):
total = TaxedMoney(net=Money(10, "USD"), gross=Money(15, "USD"))
orders_to_ship = [
- Order.objects.create(status=OrderStatus.UNFULFILLED, total=total),
- Order.objects.create(status=OrderStatus.PARTIALLY_FULFILLED, total=total),
+ Order.objects.create(
+ status=OrderStatus.UNFULFILLED, total=total, channel=channel_USD
+ ),
+ Order.objects.create(
+ status=OrderStatus.PARTIALLY_FULFILLED, total=total, channel=channel_USD
+ ),
]
for order in orders_to_ship:
order.payments.create(
@@ -324,11 +338,21 @@ def test_order_queryset_to_ship(settings):
)
orders_not_to_ship = [
- Order.objects.create(status=OrderStatus.DRAFT, total=total),
- Order.objects.create(status=OrderStatus.UNFULFILLED, total=total),
- Order.objects.create(status=OrderStatus.PARTIALLY_FULFILLED, total=total),
- Order.objects.create(status=OrderStatus.FULFILLED, total=total),
- Order.objects.create(status=OrderStatus.CANCELED, total=total),
+ Order.objects.create(
+ status=OrderStatus.DRAFT, total=total, channel=channel_USD
+ ),
+ Order.objects.create(
+ status=OrderStatus.UNFULFILLED, total=total, channel=channel_USD
+ ),
+ Order.objects.create(
+ status=OrderStatus.PARTIALLY_FULFILLED, total=total, channel=channel_USD
+ ),
+ Order.objects.create(
+ status=OrderStatus.FULFILLED, total=total, channel=channel_USD
+ ),
+ Order.objects.create(
+ status=OrderStatus.CANCELED, total=total, channel=channel_USD
+ ),
]
orders = Order.objects.ready_to_fulfill()
@@ -337,17 +361,21 @@ def test_order_queryset_to_ship(settings):
assert all([order not in orders for order in orders_not_to_ship])
-def test_queryset_ready_to_capture():
+def test_queryset_ready_to_capture(channel_USD):
total = TaxedMoney(net=Money(10, "USD"), gross=Money(15, "USD"))
- preauth_order = Order.objects.create(status=OrderStatus.UNFULFILLED, total=total)
+ preauth_order = Order.objects.create(
+ status=OrderStatus.UNFULFILLED, total=total, channel=channel_USD
+ )
Payment.objects.create(
order=preauth_order, charge_status=ChargeStatus.NOT_CHARGED, is_active=True
)
- Order.objects.create(status=OrderStatus.DRAFT, total=total)
- Order.objects.create(status=OrderStatus.UNFULFILLED, total=total)
- Order.objects.create(status=OrderStatus.CANCELED, total=total)
+ Order.objects.create(status=OrderStatus.DRAFT, total=total, channel=channel_USD)
+ Order.objects.create(
+ status=OrderStatus.UNFULFILLED, total=total, channel=channel_USD
+ )
+ Order.objects.create(status=OrderStatus.CANCELED, total=total, channel=channel_USD)
qs = Order.objects.ready_to_capture()
assert preauth_order in qs
@@ -357,17 +385,21 @@ def test_queryset_ready_to_capture():
def test_update_order_prices(order_with_lines):
+ channel_slug = order_with_lines.channel.slug
address = order_with_lines.shipping_address
address.country = "DE"
address.save()
line_1 = order_with_lines.lines.first()
line_2 = order_with_lines.lines.last()
- price_1 = line_1.variant.get_price()
+ price_1 = line_1.variant.get_price(channel_slug)
price_1 = TaxedMoney(net=price_1, gross=price_1)
- price_2 = line_2.variant.get_price()
+ price_2 = line_2.variant.get_price(channel_slug)
price_2 = TaxedMoney(net=price_2, gross=price_2)
- shipping_price = order_with_lines.shipping_method.get_total()
+
+ shipping_price = order_with_lines.shipping_method.channel_listings.get(
+ channel_id=order_with_lines.channel_id
+ ).price
shipping_price = TaxedMoney(net=shipping_price, gross=shipping_price)
update_order_prices(order_with_lines, None)
@@ -458,7 +490,7 @@ def test_get_voucher_discount_for_order_voucher_validation(
validate_voucher_in_order(order_with_lines)
mock_validate_voucher.assert_called_once_with(
- voucher, subtotal.gross, quantity, customer_email
+ voucher, subtotal.gross, quantity, customer_email, order_with_lines.channel
)
@@ -512,20 +544,27 @@ def test_display_translated_order_line_name(
],
)
def test_value_voucher_order_discount(
- subtotal, discount_value, discount_type, min_spent_amount, expected_value
+ subtotal,
+ discount_value,
+ discount_type,
+ min_spent_amount,
+ expected_value,
+ channel_USD,
):
- voucher = Voucher(
- code="unique",
- type=VoucherType.ENTIRE_ORDER,
- discount_value_type=discount_type,
- discount_value=discount_value,
- min_spent=Money(min_spent_amount, "USD")
- if min_spent_amount is not None
- else None,
+ voucher = Voucher.objects.create(
+ code="unique", type=VoucherType.ENTIRE_ORDER, discount_value_type=discount_type,
+ )
+ VoucherChannelListing.objects.create(
+ voucher=voucher,
+ channel=channel_USD,
+ discount=Money(discount_value, channel_USD.currency_code),
+ min_spent_amount=(min_spent_amount if min_spent_amount is not None else None),
)
subtotal = Money(subtotal, "USD")
subtotal = TaxedMoney(net=subtotal, gross=subtotal)
- order = Mock(get_subtotal=Mock(return_value=subtotal), voucher=voucher)
+ order = Mock(
+ get_subtotal=Mock(return_value=subtotal), voucher=voucher, channel=channel_USD
+ )
discount = get_voucher_discount_for_order(order)
assert discount == Money(expected_value, "USD")
@@ -535,14 +574,15 @@ def test_value_voucher_order_discount(
[(10, 50, DiscountValueType.PERCENTAGE, 5), (10, 20, DiscountValueType.FIXED, 10)],
)
def test_shipping_voucher_order_discount(
- shipping_cost, discount_value, discount_type, expected_value
+ shipping_cost, discount_value, discount_type, expected_value, channel_USD
):
- voucher = Voucher(
- code="unique",
- type=VoucherType.SHIPPING,
- discount_value_type=discount_type,
- discount_value=discount_value,
- min_spent_amount=None,
+ voucher = Voucher.objects.create(
+ code="unique", type=VoucherType.SHIPPING, discount_value_type=discount_type,
+ )
+ VoucherChannelListing.objects.create(
+ voucher=voucher,
+ channel=channel_USD,
+ discount=Money(discount_value, channel_USD.currency_code),
)
subtotal = Money(100, "USD")
subtotal = TaxedMoney(net=subtotal, gross=subtotal)
@@ -551,6 +591,7 @@ def test_shipping_voucher_order_discount(
get_subtotal=Mock(return_value=subtotal),
shipping_price=shipping_total,
voucher=voucher,
+ channel=channel_USD,
)
discount = get_voucher_discount_for_order(order)
assert discount == Money(expected_value, "USD")
@@ -572,18 +613,25 @@ def test_shipping_voucher_order_discount(
],
)
def test_shipping_voucher_checkout_discount_not_applicable_returns_zero(
- total, total_quantity, min_spent_amount, min_checkout_items_quantity, voucher_type
+ total,
+ total_quantity,
+ min_spent_amount,
+ min_checkout_items_quantity,
+ voucher_type,
+ channel_USD,
):
- voucher = Voucher(
+ voucher = Voucher.objects.create(
code="unique",
type=voucher_type,
discount_value_type=DiscountValueType.FIXED,
- discount_value=10,
- min_spent=(
- Money(min_spent_amount, "USD") if min_spent_amount is not None else None
- ),
min_checkout_items_quantity=min_checkout_items_quantity,
)
+ VoucherChannelListing.objects.create(
+ voucher=voucher,
+ channel=channel_USD,
+ discount=Money(10, channel_USD.currency_code),
+ min_spent_amount=(min_spent_amount if min_spent_amount is not None else None),
+ )
price = Money(total, "USD")
price = TaxedMoney(net=price, gross=price)
order = Mock(
@@ -591,6 +639,7 @@ def test_shipping_voucher_checkout_discount_not_applicable_returns_zero(
get_total_quantity=Mock(return_value=total_quantity),
shipping_price=price,
voucher=voucher,
+ channel=channel_USD,
)
with pytest.raises(NotApplicable):
get_voucher_discount_for_order(order)
@@ -613,14 +662,19 @@ def test_get_discount_for_order_specific_products_voucher(
discount_type,
apply_once_per_order,
discount_amount,
+ channel_USD,
):
voucher = Voucher.objects.create(
code="unique",
type=VoucherType.SPECIFIC_PRODUCT,
discount_value_type=discount_type,
- discount_value=discount_value,
apply_once_per_order=apply_once_per_order,
)
+ VoucherChannelListing.objects.create(
+ voucher=voucher,
+ channel=channel_USD,
+ discount=Money(discount_value, channel_USD.currency_code),
+ )
voucher.products.add(order_with_lines.lines.first().variant.product)
voucher.products.add(order_with_lines.lines.last().variant.product)
order_with_lines.voucher = voucher
@@ -630,14 +684,18 @@ def test_get_discount_for_order_specific_products_voucher(
def test_product_voucher_checkout_discount_raises_not_applicable(
- order_with_lines, product_with_images
+ order_with_lines, product_with_images, channel_USD
):
discounted_product = product_with_images
- voucher = Voucher(
+ voucher = Voucher.objects.create(
code="unique",
type=VoucherType.SPECIFIC_PRODUCT,
discount_value_type=DiscountValueType.FIXED,
- discount_value=10,
+ )
+ VoucherChannelListing.objects.create(
+ voucher=voucher,
+ channel=channel_USD,
+ discount=Money(10, channel_USD.currency_code),
)
voucher.save()
voucher.products.add(discounted_product)
@@ -648,15 +706,21 @@ def test_product_voucher_checkout_discount_raises_not_applicable(
get_voucher_discount_for_order(order_with_lines)
-def test_category_voucher_checkout_discount_raises_not_applicable(order_with_lines):
+def test_category_voucher_checkout_discount_raises_not_applicable(
+ order_with_lines, channel_USD
+):
discounted_collection = Collection.objects.create(
name="Discounted", slug="discount"
)
- voucher = Voucher(
+ voucher = Voucher.objects.create(
code="unique",
type=VoucherType.SPECIFIC_PRODUCT,
discount_value_type=DiscountValueType.FIXED,
- discount_value=10,
+ )
+ VoucherChannelListing.objects.create(
+ voucher=voucher,
+ channel=channel_USD,
+ discount=Money(10, channel_USD.currency_code),
)
voucher.save()
voucher.collections.add(discounted_collection)
diff --git a/saleor/order/tests/test_order_actions.py b/saleor/order/tests/test_order_actions.py
index cea446f927..2b57aab2b1 100644
--- a/saleor/order/tests/test_order_actions.py
+++ b/saleor/order/tests/test_order_actions.py
@@ -38,7 +38,7 @@ def order_with_digital_line(order, digital_content, stock, site_settings):
product_type.save()
quantity = 3
- net = variant.get_price()
+ net = variant.get_price(order.channel.slug)
gross = Money(amount=net.amount * Decimal(1.23), currency=net.currency)
line = order.lines.create(
product_name=str(variant.product),
diff --git a/saleor/order/tests/test_order_utils.py b/saleor/order/tests/test_order_utils.py
index 759b6028d3..ae2e0f48d1 100644
--- a/saleor/order/tests/test_order_utils.py
+++ b/saleor/order/tests/test_order_utils.py
@@ -47,10 +47,13 @@ def test_change_quantity_generates_proper_event(
}
-def test_match_orders_with_new_user(customer_user):
+def test_match_orders_with_new_user(customer_user, channel_USD):
address = customer_user.default_billing_address.get_copy()
order = Order.objects.create(
- billing_address=address, user=None, user_email=customer_user.email,
+ billing_address=address,
+ user=None,
+ user_email=customer_user.email,
+ channel=channel_USD,
)
match_orders_with_new_user(customer_user)
@@ -58,13 +61,14 @@ def test_match_orders_with_new_user(customer_user):
assert order.user == customer_user
-def test_match_draft_order_with_new_user(customer_user):
+def test_match_draft_order_with_new_user(customer_user, channel_USD):
address = customer_user.default_billing_address.get_copy()
order = Order.objects.create(
billing_address=address,
user=None,
user_email=customer_user.email,
status=OrderStatus.DRAFT,
+ channel=channel_USD,
)
match_orders_with_new_user(customer_user)
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index 6be285e8a2..219e1c8992 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -117,9 +117,10 @@ def recalculate_order_weight(order):
def update_order_prices(order, discounts):
"""Update prices in order with given discounts and proper taxes."""
manager = get_plugins_manager()
+ channel = order.channel
for line in order: # type: OrderLine
if line.variant:
- unit_price = line.variant.get_price(discounts)
+ unit_price = line.variant.get_price(channel.slug, discounts)
unit_price = TaxedMoney(unit_price, unit_price)
line.unit_price = unit_price
line.save(
@@ -173,13 +174,12 @@ def add_variant_to_draft_order(order, variant, quantity, discounts=None):
Returns an order line the variant was added to.
"""
-
try:
line = order.lines.get(variant=variant)
line.quantity += quantity
line.save(update_fields=["quantity"])
except OrderLine.DoesNotExist:
- unit_price = variant.get_price(discounts)
+ unit_price = variant.get_price(order.channel.slug, discounts)
unit_price = TaxedMoney(net=unit_price, gross=unit_price)
product = variant.product
product_name = str(product)
@@ -301,15 +301,15 @@ def restock_fulfillment_lines(fulfillment, warehouse):
OrderLine.objects.bulk_update(order_lines, ["quantity_fulfilled"])
-def sum_order_totals(qs):
- zero = Money(0, currency=settings.DEFAULT_CURRENCY)
+def sum_order_totals(qs, currency_code):
+ zero = Money(0, currency=currency_code)
taxed_zero = TaxedMoney(zero, zero)
return sum([order.total for order in qs], taxed_zero)
def get_valid_shipping_methods_for_order(order: Order):
return ShippingMethod.objects.applicable_shipping_methods_for_instance(
- order, price=order.get_subtotal().gross
+ order, channel_id=order.channel_id, price=order.get_subtotal().gross
)
@@ -340,7 +340,7 @@ def get_products_voucher_discount_for_order(order: Order) -> Money:
if not prices:
msg = "This offer is only valid for selected items."
raise NotApplicable(msg)
- return get_products_voucher_discount(voucher, prices) # type: ignore
+ return get_products_voucher_discount(voucher, prices, order.channel) # type: ignore
def get_voucher_discount_for_order(order: Order) -> Money:
@@ -353,9 +353,11 @@ def get_voucher_discount_for_order(order: Order) -> Money:
validate_voucher_in_order(order)
subtotal = order.get_subtotal()
if order.voucher.type == VoucherType.ENTIRE_ORDER:
- return order.voucher.get_discount_amount_for(subtotal.gross)
+ return order.voucher.get_discount_amount_for(subtotal.gross, order.channel)
if order.voucher.type == VoucherType.SHIPPING:
- return order.voucher.get_discount_amount_for(order.shipping_price)
+ return order.voucher.get_discount_amount_for(
+ order.shipping_price, order.channel
+ )
if order.voucher.type == VoucherType.SPECIFIC_PRODUCT:
return get_products_voucher_discount_for_order(order)
raise NotImplementedError("Unknown discount type")
diff --git a/saleor/payment/gateways/adyen/tests/utils/test_common.py b/saleor/payment/gateways/adyen/tests/utils/test_common.py
index 16c0ba4593..162306b35a 100644
--- a/saleor/payment/gateways/adyen/tests/utils/test_common.py
+++ b/saleor/payment/gateways/adyen/tests/utils/test_common.py
@@ -36,6 +36,7 @@ def test_append_klarna_data(
):
# given
checkout_ready_to_complete.payments.add(payment_dummy)
+ channel_id = checkout_ready_to_complete.channel_id
line = checkout_ready_to_complete.lines.first()
payment_data = {
"reference": "test",
@@ -46,9 +47,10 @@ def test_append_klarna_data(
result = append_klarna_data(dummy_payment_data, payment_data)
# then
- total = to_adyen_price(
- line.variant.price_amount * line.quantity, line.variant.currency
- )
+ variant_channel_listing = line.variant.channel_listings.get(channel_id=channel_id)
+ variant_price = variant_channel_listing.price_amount
+ variant_currency = variant_channel_listing.currency
+ total = to_adyen_price(variant_price * line.quantity, variant_currency)
assert result == {
"reference": "test",
"shopperLocale": get_shopper_locale_value(country_code),
diff --git a/saleor/payment/gateways/adyen/utils/common.py b/saleor/payment/gateways/adyen/utils/common.py
index c0132e34ee..23d33665a2 100644
--- a/saleor/payment/gateways/adyen/utils/common.py
+++ b/saleor/payment/gateways/adyen/utils/common.py
@@ -182,7 +182,9 @@ def append_klarna_data(payment_information: "PaymentData", payment_data: dict):
line_items = []
for line in lines:
- total = checkout_line_total(line=line, discounts=discounts)
+ total = checkout_line_total(
+ line=line, discounts=discounts, channel=checkout.channel
+ )
total_gross = total.gross.amount
total_net = total.net.amount
tax_amount = total.tax.amount
diff --git a/saleor/payment/gateways/dummy/plugin.py b/saleor/payment/gateways/dummy/plugin.py
index c9f29ae67a..9a1388663b 100644
--- a/saleor/payment/gateways/dummy/plugin.py
+++ b/saleor/payment/gateways/dummy/plugin.py
@@ -1,7 +1,5 @@
from typing import TYPE_CHECKING
-from django.conf import settings
-
from saleor.plugins.base_plugin import BasePlugin, ConfigurationTypeField
from ..utils import get_supported_currencies
@@ -39,7 +37,7 @@ class DummyGatewayPlugin(BasePlugin):
DEFAULT_CONFIGURATION = [
{"name": "Store customers card", "value": False},
{"name": "Automatic payment capture", "value": True},
- {"name": "Supported currencies", "value": settings.DEFAULT_CURRENCY},
+ {"name": "Supported currencies", "value": "USD, PLN"},
]
CONFIG_STRUCTURE = {
"Store customers card": {
diff --git a/saleor/payment/gateways/dummy_credit_card/plugin.py b/saleor/payment/gateways/dummy_credit_card/plugin.py
index 6821ef37c4..9466173991 100644
--- a/saleor/payment/gateways/dummy_credit_card/plugin.py
+++ b/saleor/payment/gateways/dummy_credit_card/plugin.py
@@ -1,7 +1,5 @@
from typing import TYPE_CHECKING
-from django.conf import settings
-
from saleor.plugins.base_plugin import BasePlugin, ConfigurationTypeField
from ..utils import get_supported_currencies
@@ -39,7 +37,7 @@ class DummyCreditCardGatewayPlugin(BasePlugin):
DEFAULT_CONFIGURATION = [
{"name": "Store customers card", "value": False},
{"name": "Automatic payment capture", "value": True},
- {"name": "Supported currencies", "value": settings.DEFAULT_CURRENCY},
+ {"name": "Supported currencies", "value": "USD, PLN"},
]
CONFIG_STRUCTURE = {
"Store customers card": {
diff --git a/saleor/payment/gateways/utils.py b/saleor/payment/gateways/utils.py
index b37aede819..3246b16540 100644
--- a/saleor/payment/gateways/utils.py
+++ b/saleor/payment/gateways/utils.py
@@ -1,8 +1,6 @@
import warnings
from typing import TYPE_CHECKING, List
-from django.conf import settings
-
if TYPE_CHECKING:
from ..interface import GatewayConfig
@@ -15,10 +13,9 @@ def get_supported_currencies(config: "GatewayConfig", gateway_name: str) -> List
"""
supp_currencies = config.supported_currencies
if not supp_currencies:
- currencies = [settings.DEFAULT_CURRENCY]
+ currencies: List[str] = []
warnings.warn(
- f"Default currency used for {gateway_name}. "
- "DEFAULT_CURRENCY setting is deprecated, "
+ f"Supported currencies not configured for {gateway_name}, "
"please configure supported currencies for this gateway."
)
else:
diff --git a/saleor/payment/migrations/0002_transfer_payment_to_payment_method.py b/saleor/payment/migrations/0002_transfer_payment_to_payment_method.py
index 1bacc84925..60f637ad7a 100644
--- a/saleor/payment/migrations/0002_transfer_payment_to_payment_method.py
+++ b/saleor/payment/migrations/0002_transfer_payment_to_payment_method.py
@@ -1,5 +1,6 @@
# Generated by Django 2.1.2 on 2018-10-17 19:42
-from django.conf import settings
+import os
+
from django.db import migrations
from prices import Money
@@ -144,7 +145,7 @@ def transfer_payments_to_payment_methods(apps, schema_editor):
token=pay.token,
captured_amount=pay.captured_amount,
total=pay.total,
- currency=pay.currency or settings.DEFAULT_CURRENCY,
+ currency=pay.currency or os.environ.get("DEFAULT_CURRENCY", "USD"),
is_active=get_is_active(pay.status, pay),
charge_status=get_charge_status(pay),
)
diff --git a/saleor/payment/models.py b/saleor/payment/models.py
index d76a39aafd..a26b881704 100644
--- a/saleor/payment/models.py
+++ b/saleor/payment/models.py
@@ -102,10 +102,10 @@ class Payment(models.Model):
return max(self.transactions.all(), default=None, key=attrgetter("pk"))
def get_total(self):
- return Money(self.total, self.currency or settings.DEFAULT_CURRENCY)
+ return Money(self.total, self.currency)
def get_authorized_amount(self):
- money = zero_money()
+ money = zero_money(self.currency)
# Query all the transactions which should be prefetched
# to optimize db queries
@@ -132,14 +132,14 @@ class Payment(models.Model):
# Calculate authorized amount from all succeeded auth transactions
for txn in authorized_txns:
- money += Money(txn.amount, self.currency or settings.DEFAULT_CURRENCY)
+ money += Money(txn.amount, self.currency)
# If multiple partial capture is supported later though it's unlikely,
# the authorized amount should exclude the already captured amount here
return money
def get_captured_amount(self):
- return Money(self.captured_amount, self.currency or settings.DEFAULT_CURRENCY)
+ return Money(self.captured_amount, self.currency)
def get_charge_amount(self):
"""Retrieve the maximum capture possible."""
@@ -232,4 +232,4 @@ class Transaction(models.Model):
)
def get_amount(self):
- return Money(self.amount, self.currency or settings.DEFAULT_CURRENCY)
+ return Money(self.amount, self.currency)
diff --git a/saleor/payment/tests/test_gateways_utils.py b/saleor/payment/tests/test_gateways_utils.py
index 920583569c..b0d9a38e8a 100644
--- a/saleor/payment/tests/test_gateways_utils.py
+++ b/saleor/payment/tests/test_gateways_utils.py
@@ -38,17 +38,16 @@ def test_get_supported_currencies(
assert currencies == expected_currencies
-def test_get_supported_currencies_default_currency(gateway_config):
+def test_get_supported_currencies_not_configured(gateway_config):
# when
with warnings.catch_warnings(record=True) as warns:
currencies = get_supported_currencies(gateway_config, "Test")
expected_warning = (
- "Default currency used for Test. "
- "DEFAULT_CURRENCY setting is deprecated, "
+ "Supported currencies not configured for Test, "
"please configure supported currencies for this gateway."
)
assert any([str(warning.message) == expected_warning for warning in warns])
# then
- assert currencies == ["USD"]
+ assert currencies == []
diff --git a/saleor/payment/tests/test_payment.py b/saleor/payment/tests/test_payment.py
index 624ad17509..04d82342ec 100644
--- a/saleor/payment/tests/test_payment.py
+++ b/saleor/payment/tests/test_payment.py
@@ -37,7 +37,7 @@ def gateway_response(settings, payment_method_details):
action_required=False,
transaction_id="transaction-token",
amount=Decimal(14.50),
- currency=settings.DEFAULT_CURRENCY,
+ currency="USD",
kind=TransactionKind.CAPTURE,
error=None,
raw_response={
@@ -107,7 +107,7 @@ def test_create_payment_requires_order_or_checkout(settings):
"gateway": "Dummy",
"payment_token": "token",
"total": 10,
- "currency": settings.DEFAULT_CURRENCY,
+ "currency": "USD",
"email": "[email protected]",
}
with pytest.raises(TypeError) as e:
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index db0756d2c7..12d2ef76d8 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -4,7 +4,6 @@ from decimal import Decimal
from typing import Dict, Optional
import graphene
-from django.conf import settings
from django.core.serializers.json import DjangoJSONEncoder
from django.db import transaction
@@ -236,9 +235,6 @@ def validate_gateway_response(response: GatewayResponse):
)
)
- if response.currency != settings.DEFAULT_CURRENCY:
- logger.warning("Transaction currency is different than Saleor's.")
-
try:
json.dumps(response.raw_response, cls=DjangoJSONEncoder)
except (TypeError, ValueError):
diff --git a/saleor/plugins/avatax/__init__.py b/saleor/plugins/avatax/__init__.py
index cf6e3477ae..c674a6f826 100644
--- a/saleor/plugins/avatax/__init__.py
+++ b/saleor/plugins/avatax/__init__.py
@@ -205,15 +205,18 @@ def append_line_to_data(
)
-def append_shipping_to_data(data: List[Dict], shipping_method):
+def append_shipping_to_data(data: List[Dict], shipping_method, channel_id):
charge_taxes_on_shipping = (
Site.objects.get_current().settings.charge_taxes_on_shipping
)
if charge_taxes_on_shipping and shipping_method:
+ shipping_price = shipping_method.channel_listings.get(
+ channel_id=channel_id
+ ).price
append_line_to_data(
data,
quantity=1,
- amount=shipping_method.price.amount,
+ amount=shipping_price.amount,
tax_code=COMMON_CARRIER_CODE,
item_code="Shipping",
)
@@ -228,6 +231,7 @@ def get_checkout_lines_data(
"variant__product__collections",
"variant__product__product_type",
).filter(variant__product__charge_taxes=True)
+ channel = checkout.channel
for line in lines:
name = line.variant.product.name
product = line.variant.product
@@ -238,14 +242,14 @@ def get_checkout_lines_data(
data=data,
quantity=line.quantity,
amount=base_calculations.base_checkout_line_total(
- line, discounts
+ line, channel, discounts
).gross.amount,
tax_code=tax_code,
item_code=line.variant.sku,
name=name,
)
- append_shipping_to_data(data, checkout.shipping_method)
+ append_shipping_to_data(data, checkout.shipping_method, checkout.channel_id)
return data
@@ -294,7 +298,7 @@ def get_order_lines_data(
name=order.discount_name,
tax_included=True, # Voucher should be always applied as a gross amount
)
- append_shipping_to_data(data, order.shipping_method)
+ append_shipping_to_data(data, order.shipping_method, order.channel_id)
return data
@@ -305,7 +309,7 @@ def generate_request_data(
address: Dict[str, str],
customer_email: str,
config: AvataxConfiguration,
- currency=settings.DEFAULT_CURRENCY,
+ currency: str,
):
company_address = Site.objects.get_current().settings.company_address
if company_address:
@@ -428,7 +432,7 @@ def get_order_request_data(order: "Order", config: AvataxConfiguration):
address=address.as_data() if address else {},
customer_email=order.user_email,
config=config,
- currency=order.total.currency,
+ currency=order.currency,
)
return data
diff --git a/saleor/plugins/avatax/plugin.py b/saleor/plugins/avatax/plugin.py
index 00d27ee8b1..36424f3a8d 100644
--- a/saleor/plugins/avatax/plugin.py
+++ b/saleor/plugins/avatax/plugin.py
@@ -37,6 +37,7 @@ from .tasks import api_post_request_task
if TYPE_CHECKING:
# flake8: noqa
from ...checkout.models import Checkout, CheckoutLine
+ from ...channel.models import Channel
from ...order.models import Order, OrderLine
from ..models import PluginConfiguration
@@ -121,12 +122,15 @@ class AvataxPlugin(BasePlugin):
self,
price: TaxedMoney,
lines: Iterable["CheckoutLine"],
+ channel: "Channel",
discounts: Iterable[DiscountInfo],
):
for line in lines:
if line.variant.product.charge_taxes:
continue
- line_price = base_calculations.base_checkout_line_total(line, discounts)
+ line_price = base_calculations.base_checkout_line_total(
+ line, channel, discounts
+ )
price.gross.amount += line_price.gross.amount
price.net.amount += line_price.net.amount
return price
@@ -154,7 +158,9 @@ class AvataxPlugin(BasePlugin):
total_gross = Money(amount=total_net + tax, currency=currency)
total_net = Money(amount=total_net, currency=currency)
taxed_total = TaxedMoney(net=total_net, gross=total_gross)
- total = self._append_prices_of_not_taxed_lines(taxed_total, lines, discounts)
+ total = self._append_prices_of_not_taxed_lines(
+ taxed_total, lines, checkout.channel, discounts
+ )
voucher_value = checkout.discount
if voucher_value:
total -= voucher_value
@@ -182,7 +188,9 @@ class AvataxPlugin(BasePlugin):
sub_total_gross = Money(sub_net + sub_tax, currency)
sub_total_net = Money(sub_net, currency)
taxed_subtotal = TaxedMoney(net=sub_total_net, gross=sub_total_gross)
- return self._append_prices_of_not_taxed_lines(taxed_subtotal, lines, discounts)
+ return self._append_prices_of_not_taxed_lines(
+ taxed_subtotal, lines, checkout.channel, discounts
+ )
def calculate_checkout_subtotal(
self,
@@ -305,6 +313,7 @@ class AvataxPlugin(BasePlugin):
self,
checkout_line: "CheckoutLine",
discounts: Iterable[DiscountInfo],
+ channel: "Channel",
previous_value: TaxedMoney,
) -> TaxedMoney:
if self._skip_plugin(previous_value):
diff --git a/saleor/plugins/avatax/tests/test_avatax.py b/saleor/plugins/avatax/tests/test_avatax.py
index c81eddbc73..b9961c1382 100644
--- a/saleor/plugins/avatax/tests/test_avatax.py
+++ b/saleor/plugins/avatax/tests/test_avatax.py
@@ -94,8 +94,10 @@ def test_calculate_checkout_line_total(
manager.assign_tax_code_to_object_meta(product.product_type, "PC040156")
product.save()
product.product_type.save()
- discounts = [discount_info] if with_discount else None
- total = manager.calculate_checkout_line_total(line, discounts)
+ discounts = [discount_info] if with_discount else []
+ total = manager.calculate_checkout_line_total(
+ line, discounts, checkout_with_item.channel
+ )
total = quantize_price(total, total.currency)
assert total == TaxedMoney(
net=Money(expected_net, "USD"), gross=Money(expected_gross, "USD")
@@ -441,9 +443,12 @@ def test_get_cached_tax_codes_or_fetch_wrong_response(monkeypatch):
assert len(tax_codes) == 0
-def test_taxes_need_new_fetch(monkeypatch, checkout_with_item, address):
+def test_checkout_needs_new_fetch(
+ monkeypatch, checkout_with_item, address, shipping_method
+):
monkeypatch.setattr("saleor.plugins.avatax.cache.get", lambda x: None)
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"
)
diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.py
index 0136cf66c5..d8a1dfe31d 100644
--- a/saleor/plugins/base_plugin.py
+++ b/saleor/plugins/base_plugin.py
@@ -19,6 +19,7 @@ from .models import PluginConfiguration
if TYPE_CHECKING:
# flake8: noqa
from ..account.models import Address, User
+ from ..channel.models import Channel
from ..checkout.models import Checkout, CheckoutLine
from ..core.taxes import TaxType
from ..discount import DiscountInfo
@@ -135,10 +136,12 @@ class BasePlugin:
"""
return NotImplemented
+ # TODO: Add information about this change to `breaking changes in changelog`
def calculate_checkout_line_total(
self,
checkout_line: "CheckoutLine",
discounts: List["DiscountInfo"],
+ channel: "Channel",
previous_value: TaxedMoney,
) -> TaxedMoney:
"""Calculate checkout line total.
diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.py
index 27712f7679..86f23e8320 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -19,6 +19,7 @@ from .models import PluginConfiguration
if TYPE_CHECKING:
# flake8: noqa
from ..account.models import Address, User
+ from ..channel.models import Channel
from ..checkout.models import Checkout, CheckoutLine
from ..invoice.models import Invoice
from ..order.models import Fulfillment, Order, OrderLine
@@ -125,7 +126,8 @@ class PluginsManager(PaymentInterface):
discounts: Iterable[DiscountInfo],
) -> TaxedMoney:
line_totals = [
- self.calculate_checkout_line_total(line, discounts) for line in lines
+ self.calculate_checkout_line_total(line, discounts, checkout.channel)
+ for line in lines
]
default_value = base_calculations.base_checkout_subtotal(
line_totals, checkout.currency
@@ -154,7 +156,9 @@ class PluginsManager(PaymentInterface):
def calculate_order_shipping(self, order: "Order") -> TaxedMoney:
if not order.shipping_method:
return zero_taxed_money(order.currency)
- shipping_price = order.shipping_method.price
+ shipping_price = order.shipping_method.channel_listings.get(
+ channel_id=order.channel_id
+ ).price
default_value = quantize_price(
TaxedMoney(net=shipping_price, gross=shipping_price),
shipping_price.currency,
@@ -167,14 +171,21 @@ class PluginsManager(PaymentInterface):
)
def calculate_checkout_line_total(
- self, checkout_line: "CheckoutLine", discounts: Iterable[DiscountInfo]
+ self,
+ checkout_line: "CheckoutLine",
+ discounts: Iterable[DiscountInfo],
+ channel: "Channel",
):
default_value = base_calculations.base_checkout_line_total(
- checkout_line, discounts
+ checkout_line, channel, discounts
)
return quantize_price(
self.__run_method_on_plugins(
- "calculate_checkout_line_total", default_value, checkout_line, discounts
+ "calculate_checkout_line_total",
+ default_value,
+ checkout_line,
+ discounts,
+ channel,
),
checkout_line.checkout.currency,
)
diff --git a/saleor/plugins/tests/sample_plugins.py b/saleor/plugins/tests/sample_plugins.py
index 8235565534..37a47a48f5 100644
--- a/saleor/plugins/tests/sample_plugins.py
+++ b/saleor/plugins/tests/sample_plugins.py
@@ -77,7 +77,9 @@ class PluginSample(BasePlugin):
price = Money("1.0", currency=order.currency)
return TaxedMoney(price, price)
- def calculate_checkout_line_total(self, checkout_line, discounts, previous_value):
+ def calculate_checkout_line_total(
+ self, checkout_line, discounts, channel, previous_value
+ ):
price = Money("1.0", currency=checkout_line.checkout.currency)
return TaxedMoney(price, price)
@@ -147,7 +149,7 @@ class ActiveDummyPaymentGateway(BasePlugin):
]
PLUGIN_NAME = "SampleDummy"
DEFAULT_ACTIVE = True
- SUPPORTED_CURRENCIES = ["PLN", "USD"]
+ SUPPORTED_CURRENCIES = ["EUR", "USD"]
def process_payment(self, payment_information, previous_value):
pass
diff --git a/saleor/plugins/tests/test_manager.py b/saleor/plugins/tests/test_manager.py
index 55ffc4367c..c7ca9e6e2d 100644
--- a/saleor/plugins/tests/test_manager.py
+++ b/saleor/plugins/tests/test_manager.py
@@ -104,7 +104,7 @@ def test_manager_calculates_checkout_line_total(
currency = checkout_with_item.currency
expected_total = Money(amount, currency)
taxed_total = PluginsManager(plugins=plugins).calculate_checkout_line_total(
- line, [discount_info]
+ line, [discount_info], checkout_with_item.channel
)
assert TaxedMoney(expected_total, expected_total) == taxed_total
@@ -146,13 +146,13 @@ def test_manager_show_taxes_on_storefront(plugins, show_taxes):
"plugins, price",
[(["saleor.plugins.tests.sample_plugins.PluginSample"], "1.0"), ([], "10.0")],
)
-def test_manager_apply_taxes_to_product(product, plugins, price):
+def test_manager_apply_taxes_to_product(product, plugins, price, channel_USD):
country = Country("PL")
variant = product.variants.all()[0]
- currency = variant.get_price().currency
+ currency = variant.get_price(channel_USD.slug).currency
expected_price = Money(price, currency)
taxed_price = PluginsManager(plugins=plugins).apply_taxes_to_product(
- product, variant.get_price(), country
+ product, variant.get_price(channel_USD.slug), country
)
assert TaxedMoney(expected_price, expected_price) == taxed_price
@@ -162,11 +162,14 @@ def test_manager_apply_taxes_to_product(product, plugins, price):
[(["saleor.plugins.tests.sample_plugins.PluginSample"], "1.0"), ([], "10.0")],
)
def test_manager_apply_taxes_to_shipping(
- shipping_method, address, plugins, price_amount
+ shipping_method, address, plugins, price_amount, channel_USD
):
+ shipping_price = shipping_method.channel_listings.get(
+ channel_id=channel_USD.id
+ ).price
expected_price = Money(price_amount, "USD")
taxed_price = PluginsManager(plugins=plugins).apply_taxes_to_shipping(
- shipping_method.price, address
+ shipping_price, address
)
assert TaxedMoney(expected_price, expected_price) == taxed_price
@@ -312,7 +315,7 @@ def test_manager_serve_list_all_payment_gateways_specified_currency():
]
manager = PluginsManager(plugins=plugins)
assert (
- manager.list_payment_gateways(currency="PLN", active_only=False)
+ manager.list_payment_gateways(currency="EUR", active_only=False)
== expected_gateways
)
diff --git a/saleor/plugins/vatlayer/plugin.py b/saleor/plugins/vatlayer/plugin.py
index 66281715aa..1077bf2620 100644
--- a/saleor/plugins/vatlayer/plugin.py
+++ b/saleor/plugins/vatlayer/plugin.py
@@ -29,6 +29,7 @@ if TYPE_CHECKING:
# flake8: noqa
from ...account.models import Address
from ...checkout.models import Checkout, CheckoutLine
+ from ...channel.models import Channel
from ...discount import DiscountInfo
from ...order.models import Order, OrderLine
from ..models import PluginConfiguration
@@ -122,8 +123,10 @@ class VatlayerPlugin(BasePlugin):
taxes = self._get_taxes_for_country(address.country)
if not checkout.shipping_method:
return previous_value
-
- return get_taxed_shipping_price(checkout.shipping_method.price, taxes)
+ shipping_price = checkout.shipping_method.channel_listings.get(
+ channel_id=checkout.channel_id
+ ).price
+ return get_taxed_shipping_price(shipping_price, taxes)
def calculate_order_shipping(
self, order: "Order", previous_value: TaxedMoney
@@ -137,12 +140,16 @@ class VatlayerPlugin(BasePlugin):
taxes = self._get_taxes_for_country(address.country)
if not order.shipping_method:
return previous_value
- return get_taxed_shipping_price(order.shipping_method.price, taxes)
+ shipping_price = order.shipping_method.channel_listings.get(
+ channel_id=order.channel_id
+ ).price
+ return get_taxed_shipping_price(shipping_price, taxes)
def calculate_checkout_line_total(
self,
checkout_line: "CheckoutLine",
discounts: List["DiscountInfo"],
+ channel: "Channel",
previous_value: TaxedMoney,
) -> TaxedMoney:
if self._skip_plugin(previous_value):
@@ -152,7 +159,7 @@ class VatlayerPlugin(BasePlugin):
checkout_line.checkout.shipping_address
or checkout_line.checkout.billing_address
)
- price = checkout_line.variant.get_price(discounts)
+ price = checkout_line.variant.get_price(channel.slug, discounts)
country = address.country if address else None
return (
self.__apply_taxes_to_product(checkout_line.variant.product, price, country)
diff --git a/saleor/plugins/vatlayer/tests/test_vatlayer.py b/saleor/plugins/vatlayer/tests/test_vatlayer.py
index 2cc19d00af..8c060f98f6 100644
--- a/saleor/plugins/vatlayer/tests/test_vatlayer.py
+++ b/saleor/plugins/vatlayer/tests/test_vatlayer.py
@@ -181,7 +181,9 @@ def test_apply_tax_to_price_no_taxes_raise_typeerror_for_invalid_type():
assert apply_tax_to_price(None, "standard", 100)
-def test_vatlayer_plugin_caches_taxes(vatlayer, monkeypatch, product, address):
+def test_vatlayer_plugin_caches_taxes(
+ vatlayer, monkeypatch, product, address, channel_USD
+):
mocked_taxes = Mock(wraps=get_taxes_for_country)
monkeypatch.setattr(
"saleor.plugins.vatlayer.plugin.get_taxes_for_country", mocked_taxes
@@ -189,7 +191,7 @@ def test_vatlayer_plugin_caches_taxes(vatlayer, monkeypatch, product, address):
manager = get_plugins_manager()
plugin = manager.get_plugin(VatlayerPlugin.PLUGIN_ID)
- price = product.variants.first().get_price()
+ price = product.variants.first().get_price(channel_USD.slug)
address.country = Country("de")
plugin.apply_taxes_to_product(
product, price, address.country, TaxedMoney(price, price)
@@ -422,7 +424,9 @@ def test_apply_taxes_to_shipping_price_range(vatlayer, settings):
assert price_range.stop == expected_stop
-def test_apply_taxes_to_product(vatlayer, settings, variant, discount_info):
+def test_apply_taxes_to_product(
+ vatlayer, settings, variant, discount_info, channel_USD
+):
settings.PLUGINS = ["saleor.plugins.vatlayer.plugin.VatlayerPlugin"]
country = Country("PL")
manager = get_plugins_manager()
@@ -431,13 +435,13 @@ def test_apply_taxes_to_product(vatlayer, settings, variant, discount_info):
"vatlayer.description": "standard",
}
price = manager.apply_taxes_to_product(
- variant.product, variant.get_price([discount_info]), country
+ variant.product, variant.get_price(channel_USD.slug, [discount_info]), country
)
assert price == TaxedMoney(net=Money("4.07", "USD"), gross=Money("5.00", "USD"))
def test_apply_taxes_to_product_uses_taxes_from_product_type(
- vatlayer, settings, variant, discount_info
+ vatlayer, settings, variant, discount_info, channel_USD
):
settings.PLUGINS = ["saleor.plugins.vatlayer.plugin.VatlayerPlugin"]
country = Country("PL")
@@ -448,7 +452,7 @@ def test_apply_taxes_to_product_uses_taxes_from_product_type(
"vatlayer.description": "standard",
}
price = manager.apply_taxes_to_product(
- variant.product, variant.get_price([discount_info]), country
+ variant.product, variant.get_price(channel_USD.slug, [discount_info]), country
)
assert price == TaxedMoney(net=Money("4.07", "USD"), gross=Money("5.00", "USD"))
diff --git a/saleor/product/__init__.py b/saleor/product/__init__.py
index cee2b40c6e..f3236ce684 100644
--- a/saleor/product/__init__.py
+++ b/saleor/product/__init__.py
@@ -1,48 +1,3 @@
-from enum import Enum
-
-
-class ProductAvailabilityStatus(str, Enum):
- NOT_PUBLISHED = "not-published"
- VARIANTS_MISSSING = "variants-missing"
- OUT_OF_STOCK = "out-of-stock"
- LOW_STOCK = "low-stock"
- NOT_YET_AVAILABLE = "not-yet-available"
- READY_FOR_PURCHASE = "ready-for-purchase"
-
- @staticmethod
- def get_display(status):
- status_mapping = {
- ProductAvailabilityStatus.NOT_PUBLISHED: "not published",
- ProductAvailabilityStatus.VARIANTS_MISSSING: "variants missing",
- ProductAvailabilityStatus.OUT_OF_STOCK: "out of stock",
- ProductAvailabilityStatus.LOW_STOCK: "stock running low",
- ProductAvailabilityStatus.NOT_YET_AVAILABLE: "not yet available",
- ProductAvailabilityStatus.READY_FOR_PURCHASE: "ready for purchase",
- }
-
- if status in status_mapping:
- return status_mapping[status]
- else:
- raise NotImplementedError(f"Unknown status: {status}")
-
-
-class VariantAvailabilityStatus(str, Enum):
- AVAILABLE = "available"
- OUT_OF_STOCK = "out-of-stock"
-
- @staticmethod
- def get_display(status):
- status_mapping = {
- VariantAvailabilityStatus.AVAILABLE: "available",
- VariantAvailabilityStatus.OUT_OF_STOCK: "out of stock",
- }
-
- if status in status_mapping:
- return status_mapping[status]
- else:
- raise NotImplementedError(f"Unknown status: {status}")
-
-
class AttributeInputType:
"""The type that we expect to render the attribute's values as."""
diff --git a/saleor/product/error_codes.py b/saleor/product/error_codes.py
index 534c2b0356..527e29ce8a 100644
--- a/saleor/product/error_codes.py
+++ b/saleor/product/error_codes.py
@@ -9,9 +9,22 @@ class ProductErrorCode(Enum):
DUPLICATED_INPUT_ITEM = "duplicated_input_item"
GRAPHQL_ERROR = "graphql_error"
INVALID = "invalid"
+ PRODUCT_WITHOUT_CATEGORY = "product_without_category"
NOT_PRODUCTS_IMAGE = "not_products_image"
NOT_PRODUCTS_VARIANT = "not_products_variant"
NOT_FOUND = "not_found"
REQUIRED = "required"
UNIQUE = "unique"
VARIANT_NO_DIGITAL_CONTENT = "variant_no_digital_content"
+ CANNOT_MANAGE_PRODUCT_WITHOUT_VARIANT = "cannot_manage_product_without_variant"
+ PRODUCT_NOT_ASSIGNED_TO_CHANNEL = "product_not_assigned_to_channel"
+
+
+class CollectionErrorCode(Enum):
+ DUPLICATED_INPUT_ITEM = "duplicated_input_item"
+ GRAPHQL_ERROR = "graphql_error"
+ INVALID = "invalid"
+ NOT_FOUND = "not_found"
+ REQUIRED = "required"
+ UNIQUE = "unique"
+ CANNOT_MANAGE_PRODUCT_WITHOUT_VARIANT = "cannot_manage_product_without_variant"
diff --git a/saleor/product/management/commands/update_all_products_minimal_variant_prices.py b/saleor/product/management/commands/update_all_products_discounted_prices.py
similarity index 64%
rename from saleor/product/management/commands/update_all_products_minimal_variant_prices.py
rename to saleor/product/management/commands/update_all_products_discounted_prices.py
index 4248eea4b5..c108ffaa5f 100644
--- a/saleor/product/management/commands/update_all_products_minimal_variant_prices.py
+++ b/saleor/product/management/commands/update_all_products_discounted_prices.py
@@ -5,19 +5,19 @@ from tqdm import tqdm
from ....discount.utils import fetch_active_discounts
from ...models import Product
-from ...utils.variant_prices import update_product_minimal_variant_price
+from ...utils.variant_prices import update_product_discounted_price
logger = logging.getLogger(__name__)
class Command(BaseCommand):
- help = "Recalculates the minimal variant prices for all products."
+ help = "Recalculates the discounted prices for products in all channels."
def handle(self, *args, **options):
- self.stdout.write('Updating "minimal_variant_price" field of all the products.')
+ self.stdout.write('Updating "discounted_price" field of all the products.')
# Fetching the discounts just once and reusing them
discounts = fetch_active_discounts()
# Run the update on all the products with "progress bar" (tqdm)
qs = Product.objects.all()
for product in tqdm(qs.iterator(), total=qs.count()):
- update_product_minimal_variant_price(product, discounts=discounts)
+ update_product_discounted_price(product, discounts=discounts)
diff --git a/saleor/product/migrations/0106_django_prices_2.py b/saleor/product/migrations/0106_django_prices_2.py
index dfa27e127d..d4117e2410 100644
--- a/saleor/product/migrations/0106_django_prices_2.py
+++ b/saleor/product/migrations/0106_django_prices_2.py
@@ -1,5 +1,7 @@
# Generated by Django 2.2.4 on 2019-08-14 09:13
+import os
+
from django.conf import settings
from django.db import migrations, models
@@ -26,7 +28,7 @@ class Migration(migrations.Migration):
model_name="product",
name="currency",
field=models.CharField(
- default=settings.DEFAULT_CURRENCY,
+ default=os.environ.get("DEFAULT_CURRENCY", "USD"),
max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH,
),
),
@@ -35,7 +37,7 @@ class Migration(migrations.Migration):
name="currency",
field=models.CharField(
blank=True,
- default=settings.DEFAULT_CURRENCY,
+ default=os.environ.get("DEFAULT_CURRENCY", "USD"),
max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH,
null=True,
),
diff --git a/saleor/product/migrations/0133_product_variant_channel_listing.py b/saleor/product/migrations/0133_product_variant_channel_listing.py
new file mode 100644
index 0000000000..ad17adf68b
--- /dev/null
+++ b/saleor/product/migrations/0133_product_variant_channel_listing.py
@@ -0,0 +1,89 @@
+# Generated by Django 3.0.6 on 2020-08-20 10:50
+
+import django.db.models.deletion
+from django.db import migrations, models
+from django.utils.text import slugify
+
+
+def migrate_variant_price_data(apps, schema_editor):
+ Channel = apps.get_model("channel", "Channel")
+ ProductVariant = apps.get_model("product", "ProductVariant")
+ ProductVariantChannelListing = apps.get_model(
+ "product", "ProductVariantChannelListing"
+ )
+
+ if ProductVariant.objects.exists():
+ channels_dict = {}
+
+ for variant in ProductVariant.objects.iterator():
+ currency = variant.currency
+ channel = channels_dict.get(currency)
+ if not channel:
+ name = f"Channel {currency}"
+ channel, _ = Channel.objects.get_or_create(
+ currency_code=currency,
+ defaults={"name": name, "slug": slugify(name)},
+ )
+ channels_dict[currency] = channel
+ ProductVariantChannelListing.objects.create(
+ variant=variant,
+ channel=channel,
+ currency=currency,
+ price_amount=variant.price_amount,
+ cost_price_amount=variant.cost_price_amount,
+ )
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("channel", "0001_initial"),
+ ("checkout", "0030_checkout_channel_listing"),
+ ("product", "0132_product_rating"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="ProductVariantChannelListing",
+ fields=[
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("currency", models.CharField(max_length=3,),),
+ ("price_amount", models.DecimalField(decimal_places=3, max_digits=12)),
+ (
+ "channel",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="variant_listings",
+ to="channel.Channel",
+ ),
+ ),
+ (
+ "variant",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="channel_listings",
+ to="product.ProductVariant",
+ ),
+ ),
+ (
+ "cost_price_amount",
+ models.DecimalField(
+ blank=True, decimal_places=3, max_digits=12, null=True
+ ),
+ ),
+ ],
+ options={"ordering": ("pk",), "unique_together": {("variant", "channel")}},
+ ),
+ migrations.RunPython(migrate_variant_price_data),
+ migrations.RemoveField(model_name="productvariant", name="price_amount",),
+ migrations.RemoveField(model_name="productvariant", name="cost_price_amount",),
+ migrations.RemoveField(model_name="productvariant", name="currency",),
+ ]
diff --git a/saleor/product/migrations/0134_product_channel_listing.py b/saleor/product/migrations/0134_product_channel_listing.py
new file mode 100644
index 0000000000..e576a47f7d
--- /dev/null
+++ b/saleor/product/migrations/0134_product_channel_listing.py
@@ -0,0 +1,95 @@
+# Generated by Django 3.1 on 2020-08-19 07:50
+
+import django.db.models.deletion
+from django.db import migrations, models
+from django.utils.text import slugify
+
+
+def migrate_products_publishable_data(apps, schema_editor):
+ Channel = apps.get_model("channel", "Channel")
+ Product = apps.get_model("product", "Product")
+ ProductChannelListing = apps.get_model("product", "ProductChannelListing")
+
+ channels_dict = {}
+
+ for product in Product.objects.iterator():
+ currency = product.currency
+ channel = channels_dict.get(currency)
+ if not channel:
+ name = f"Channel {currency}"
+ channel, _ = Channel.objects.get_or_create(
+ currency_code=currency, defaults={"name": name, "slug": slugify(name)},
+ )
+ channels_dict[currency] = channel
+ ProductChannelListing.objects.create(
+ product=product,
+ channel=channel,
+ is_published=product.is_published,
+ publication_date=product.publication_date,
+ currency=currency,
+ visible_in_listings=product.visible_in_listings,
+ available_for_purchase=product.available_for_purchase,
+ discounted_price_amount=product.minimal_variant_price_amount,
+ )
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("channel", "0001_initial"),
+ ("product", "0133_product_variant_channel_listing"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="ProductChannelListing",
+ fields=[
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("publication_date", models.DateField(blank=True, null=True)),
+ ("is_published", models.BooleanField(default=False)),
+ (
+ "channel",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="product_listings",
+ to="channel.channel",
+ ),
+ ),
+ (
+ "product",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="channel_listings",
+ to="product.product",
+ ),
+ ),
+ (
+ "discounted_price_amount",
+ models.DecimalField(
+ blank=True, decimal_places=3, max_digits=12, null=True,
+ ),
+ ),
+ ("currency", models.CharField(max_length=3)),
+ ("visible_in_listings", models.BooleanField(default=False)),
+ ("available_for_purchase", models.DateField(blank=True, null=True)),
+ ],
+ options={"ordering": ("pk",), "unique_together": {("product", "channel")}},
+ ),
+ migrations.RunPython(migrate_products_publishable_data),
+ migrations.RemoveField(model_name="product", name="is_published",),
+ migrations.RemoveField(model_name="product", name="publication_date",),
+ migrations.RemoveField(model_name="product", name="currency",),
+ migrations.RemoveField(
+ model_name="product", name="minimal_variant_price_amount",
+ ),
+ migrations.RemoveField(model_name="product", name="visible_in_listings",),
+ migrations.RemoveField(model_name="product", name="available_for_purchase",),
+ ]
diff --git a/saleor/product/migrations/0135_collection_channel_listing.py b/saleor/product/migrations/0135_collection_channel_listing.py
new file mode 100644
index 0000000000..224c874ff0
--- /dev/null
+++ b/saleor/product/migrations/0135_collection_channel_listing.py
@@ -0,0 +1,80 @@
+# Generated by Django 3.1.2 on 2020-11-10 09:29
+
+import os
+
+import django.db.models.deletion
+from django.db import migrations, models
+from django.utils.text import slugify
+
+
+def create_collection_channel_listing(apps, schema_editor):
+ CollectionChannelListing = apps.get_model("product", "CollectionChannelListing")
+ Collection = apps.get_model("product", "Collection")
+ Channel = apps.get_model("channel", "Channel")
+
+ if Collection.objects.exists():
+ currency = os.environ.get("DEFAULT_CURRENCY", "USD")
+ name = f"Channel {currency}"
+ channel, _ = Channel.objects.get_or_create(
+ currency_code=currency, defaults={"name": name, "slug": slugify(name)},
+ )
+ for collection in Collection.objects.iterator():
+
+ CollectionChannelListing.objects.create(
+ collection=collection,
+ channel=channel,
+ is_published=collection.is_published,
+ publication_date=collection.publication_date,
+ )
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("channel", "0001_initial"),
+ ("product", "0134_product_channel_listing"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="CollectionChannelListing",
+ fields=[
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("publication_date", models.DateField(blank=True, null=True)),
+ ("is_published", models.BooleanField(default=False)),
+ (
+ "channel",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="collection_listings",
+ to="channel.channel",
+ ),
+ ),
+ (
+ "collection",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="channel_listings",
+ to="product.collection",
+ ),
+ ),
+ ],
+ options={
+ "ordering": ("pk",),
+ "unique_together": {("collection", "channel")},
+ },
+ ),
+ migrations.RunPython(
+ create_collection_channel_listing, migrations.RunPython.noop
+ ),
+ migrations.RemoveField(model_name="collection", name="is_published",),
+ migrations.RemoveField(model_name="collection", name="publication_date",),
+ ]
diff --git a/saleor/product/models.py b/saleor/product/models.py
index 1ed8abf280..411e13ad08 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -5,7 +5,22 @@ from uuid import uuid4
from django.conf import settings
from django.contrib.postgres.aggregates import StringAgg
from django.db import models
-from django.db.models import Case, Count, F, FilteredRelation, Q, Sum, Value, When
+from django.db.models import JSONField # type: ignore
+from django.db.models import (
+ BooleanField,
+ Case,
+ Count,
+ DateField,
+ ExpressionWrapper,
+ F,
+ FilteredRelation,
+ OuterRef,
+ Q,
+ Subquery,
+ Sum,
+ Value,
+ When,
+)
from django.db.models.functions import Coalesce
from django.urls import reverse
from django.utils.encoding import smart_text
@@ -16,13 +31,9 @@ from mptt.managers import TreeManager
from mptt.models import MPTTModel
from versatileimagefield.fields import PPOIField, VersatileImageField
+from ..channel.models import Channel
from ..core.db.fields import SanitizedJSONField
-from ..core.models import (
- ModelWithMetadata,
- PublishableModel,
- PublishedQuerySet,
- SortableModel,
-)
+from ..core.models import ModelWithMetadata, PublishableModel, SortableModel
from ..core.permissions import ProductPermissions, ProductTypePermissions
from ..core.sanitizers.editorjs_sanitizer import clean_editor_js
from ..core.utils import build_absolute_uri
@@ -125,15 +136,77 @@ class ProductType(ModelWithMetadata):
)
-class ProductsQueryset(PublishedQuerySet):
- def published_with_variants(self):
- published = self.published()
- return published.filter(variants__isnull=False).distinct()
+class ProductsQueryset(models.QuerySet):
+ def published(self, channel_slug: str):
+ today = datetime.date.today()
+ return self.filter(
+ Q(channel_listings__publication_date__lte=today)
+ | Q(channel_listings__publication_date__isnull=True),
+ channel_listings__channel__slug=str(channel_slug),
+ channel_listings__channel__is_active=True,
+ channel_listings__is_published=True,
+ )
+
+ def not_published(self, channel_slug: str):
+ today = datetime.date.today()
+ return self.annotate_publication_info(channel_slug).filter(
+ Q(publication_date__gt=today) & Q(is_published=True)
+ | Q(is_published=False)
+ | Q(is_published__isnull=True)
+ )
+
+ def published_with_variants(self, channel_slug: str):
+ published = self.published(channel_slug)
+ query = ProductVariantChannelListing.objects.filter(
+ variant_id=OuterRef("variants__id"), channel__slug=str(channel_slug)
+ ).values_list("variant", flat=True)
+ return published.filter(variants__in=query)
- def visible_to_user(self, user):
+ def visible_to_user(self, user: "User", channel_slug: str):
if self.user_has_access_to_all(user):
+ if channel_slug:
+ return self.filter(channel_listings__channel__slug=str(channel_slug))
return self.all()
- return self.published_with_variants()
+ return self.published_with_variants(channel_slug)
+
+ @staticmethod
+ def user_has_access_to_all(user):
+ return user.is_active and user.has_perm(ProductPermissions.MANAGE_PRODUCTS)
+
+ def annotate_publication_info(self, channel_slug: str):
+ return self.annotate_is_published(channel_slug).annotate_publication_date(
+ channel_slug
+ )
+
+ def annotate_is_published(self, channel_slug: str):
+ query = Subquery(
+ ProductChannelListing.objects.filter(
+ product_id=OuterRef("pk"), channel__slug=str(channel_slug)
+ ).values_list("is_published")[:1]
+ )
+ return self.annotate(
+ is_published=ExpressionWrapper(query, output_field=BooleanField())
+ )
+
+ def annotate_publication_date(self, channel_slug: str):
+ query = Subquery(
+ ProductChannelListing.objects.filter(
+ product_id=OuterRef("pk"), channel__slug=str(channel_slug)
+ ).values_list("publication_date")[:1]
+ )
+ return self.annotate(
+ publication_date=ExpressionWrapper(query, output_field=DateField())
+ )
+
+ def annotate_visible_in_listings(self, channel_slug):
+ query = Subquery(
+ ProductChannelListing.objects.filter(
+ product_id=OuterRef("pk"), channel__slug=str(channel_slug)
+ ).values_list("visible_in_listings")[:1]
+ )
+ return self.annotate(
+ visible_in_listings=ExpressionWrapper(query, output_field=BooleanField())
+ )
def sort_by_attribute(
self, attribute_pk: Union[int, str], descending: bool = False
@@ -230,7 +303,7 @@ class ProductsQueryset(PublishedQuerySet):
)
-class Product(SeoModel, ModelWithMetadata, PublishableModel):
+class Product(SeoModel, ModelWithMetadata):
product_type = models.ForeignKey(
ProductType, related_name="products", on_delete=models.CASCADE
)
@@ -247,28 +320,11 @@ class Product(SeoModel, ModelWithMetadata, PublishableModel):
null=True,
blank=True,
)
-
- currency = models.CharField(
- max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH,
- default=settings.DEFAULT_CURRENCY,
- )
-
- minimal_variant_price_amount = models.DecimalField(
- max_digits=settings.DEFAULT_MAX_DIGITS,
- decimal_places=settings.DEFAULT_DECIMAL_PLACES,
- blank=True,
- null=True,
- )
- minimal_variant_price = MoneyField(
- amount_field="minimal_variant_price_amount", currency_field="currency"
- )
updated_at = models.DateTimeField(auto_now=True, null=True)
charge_taxes = models.BooleanField(default=True)
weight = MeasurementField(
measurement=Weight, unit_choices=WeightUnits.CHOICES, blank=True, null=True
)
- available_for_purchase = models.DateField(blank=True, null=True)
- visible_in_listings = models.BooleanField(default=False)
default_variant = models.OneToOneField(
"ProductVariant",
blank=True,
@@ -317,12 +373,6 @@ class Product(SeoModel, ModelWithMetadata, PublishableModel):
def sort_by_attribute_fields() -> list:
return ["concatenated_values_order", "concatenated_values", "name"]
- def is_available_for_purchase(self):
- return (
- self.available_for_purchase is not None
- and datetime.date.today() >= self.available_for_purchase
- )
-
class ProductTranslation(SeoModelTranslation):
language_code = models.CharField(max_length=10)
@@ -360,66 +410,55 @@ class ProductVariantQueryset(models.QuerySet):
),
)
- def create(self, **kwargs):
- """Create a product's variant.
-
- After the creation update the "minimal_variant_price" of the product.
- """
- variant = super().create(**kwargs)
-
- from .tasks import update_product_minimal_variant_price_task
- update_product_minimal_variant_price_task.delay(variant.product_id)
- return variant
-
- def bulk_create(self, objs, batch_size=None, ignore_conflicts=False):
- """Insert each of the product's variant instances into the database.
-
- After the creation update the "minimal_variant_price" of all the products.
- """
- variants = super().bulk_create(
- objs, batch_size=batch_size, ignore_conflicts=ignore_conflicts
- )
- product_ids = set()
- for obj in objs:
- product_ids.add(obj.product_id)
- product_ids = list(product_ids)
+class ProductChannelListing(PublishableModel):
+ product = models.ForeignKey(
+ Product,
+ null=False,
+ blank=False,
+ related_name="channel_listings",
+ on_delete=models.CASCADE,
+ )
+ channel = models.ForeignKey(
+ Channel,
+ null=False,
+ blank=False,
+ related_name="product_listings",
+ on_delete=models.CASCADE,
+ )
+ visible_in_listings = models.BooleanField(default=False)
+ available_for_purchase = models.DateField(blank=True, null=True)
+ currency = models.CharField(max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH)
+ discounted_price_amount = models.DecimalField(
+ max_digits=settings.DEFAULT_MAX_DIGITS,
+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,
+ blank=True,
+ null=True,
+ )
+ discounted_price = MoneyField(
+ amount_field="discounted_price_amount", currency_field="currency"
+ )
- from .tasks import update_products_minimal_variant_prices_of_catalogues_task
+ class Meta:
+ unique_together = [["product", "channel"]]
+ ordering = ("pk",)
- update_products_minimal_variant_prices_of_catalogues_task.delay(
- product_ids=product_ids
+ def is_available_for_purchase(self):
+ return (
+ self.available_for_purchase is not None
+ and datetime.date.today() >= self.available_for_purchase
)
- return variants
class ProductVariant(SortableModel, ModelWithMetadata):
sku = models.CharField(max_length=255, unique=True)
name = models.CharField(max_length=255, blank=True)
- currency = models.CharField(
- max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH,
- default=settings.DEFAULT_CURRENCY,
- blank=True,
- null=True,
- )
- price_amount = models.DecimalField(
- max_digits=settings.DEFAULT_MAX_DIGITS,
- decimal_places=settings.DEFAULT_DECIMAL_PLACES,
- )
- price = MoneyField(amount_field="price_amount", currency_field="currency")
product = models.ForeignKey(
Product, related_name="variants", on_delete=models.CASCADE
)
images = models.ManyToManyField("ProductImage", through="VariantImage")
track_inventory = models.BooleanField(default=True)
- cost_price_amount = models.DecimalField(
- max_digits=settings.DEFAULT_MAX_DIGITS,
- decimal_places=settings.DEFAULT_DECIMAL_PLACES,
- blank=True,
- null=True,
- )
- cost_price = MoneyField(amount_field="cost_price_amount", currency_field="currency")
weight = MeasurementField(
measurement=Weight, unit_choices=WeightUnits.CHOICES, blank=True, null=True
)
@@ -434,16 +473,16 @@ class ProductVariant(SortableModel, ModelWithMetadata):
def __str__(self) -> str:
return self.name or self.sku
- @property
- def is_visible(self) -> bool:
- return self.product.is_visible
-
- def get_price(self, discounts: Optional[Iterable[DiscountInfo]] = None) -> "Money":
+ def get_price(
+ self, channel_slug: str, discounts: Optional[Iterable[DiscountInfo]] = None
+ ) -> "Money":
+ channel_listing = self.channel_listings.get(channel__slug=channel_slug)
return calculate_discounted_price(
product=self.product,
- price=self.price,
+ price=channel_listing.price,
collections=self.product.collections.all(),
discounts=discounts,
+ channel=channel_listing.channel,
)
def get_weight(self):
@@ -501,6 +540,41 @@ class ProductVariantTranslation(models.Model):
return self.name or str(self.product_variant)
+class ProductVariantChannelListing(models.Model):
+ variant = models.ForeignKey(
+ ProductVariant,
+ null=False,
+ blank=False,
+ related_name="channel_listings",
+ on_delete=models.CASCADE,
+ )
+ channel = models.ForeignKey(
+ Channel,
+ null=False,
+ blank=False,
+ related_name="variant_listings",
+ on_delete=models.CASCADE,
+ )
+ currency = models.CharField(max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH)
+ price_amount = models.DecimalField(
+ max_digits=settings.DEFAULT_MAX_DIGITS,
+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,
+ )
+ price = MoneyField(amount_field="price_amount", currency_field="currency")
+
+ cost_price_amount = models.DecimalField(
+ max_digits=settings.DEFAULT_MAX_DIGITS,
+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,
+ blank=True,
+ null=True,
+ )
+ cost_price = MoneyField(amount_field="cost_price_amount", currency_field="currency")
+
+ class Meta:
+ unique_together = [["variant", "channel"]]
+ ordering = ("pk",)
+
+
class DigitalContent(ModelWithMetadata):
FILE = "file"
TYPE_CHOICES = ((FILE, "digital_product"),)
@@ -855,7 +929,30 @@ class CollectionProduct(SortableModel):
return self.product.collectionproduct.all()
-class Collection(SeoModel, ModelWithMetadata, PublishableModel):
+class CollectionsQueryset(models.QuerySet):
+ @staticmethod
+ def user_has_access_to_all(user):
+ return user.is_active and user.has_perm(ProductPermissions.MANAGE_PRODUCTS)
+
+ def published(self, channel_slug: str):
+ today = datetime.date.today()
+ return self.filter(
+ Q(channel_listings__publication_date__lte=today)
+ | Q(channel_listings__publication_date__isnull=True),
+ channel_listings__channel__slug=str(channel_slug),
+ channel_listings__channel__is_active=True,
+ channel_listings__is_published=True,
+ )
+
+ def visible_to_user(self, user: "User", channel_slug: str):
+ if self.user_has_access_to_all(user):
+ if channel_slug:
+ return self.filter(channel_listings__channel__slug=str(channel_slug))
+ return self.all()
+ return self.published(channel_slug)
+
+
+class Collection(SeoModel, ModelWithMetadata):
name = models.CharField(max_length=250, unique=True)
slug = models.SlugField(max_length=255, unique=True, allow_unicode=True)
products = models.ManyToManyField(
@@ -874,6 +971,8 @@ class Collection(SeoModel, ModelWithMetadata, PublishableModel):
blank=True, default=dict, sanitizer=clean_editor_js
)
+ objects = CollectionsQueryset.as_manager()
+
translated = TranslationProxy()
class Meta:
@@ -883,6 +982,27 @@ class Collection(SeoModel, ModelWithMetadata, PublishableModel):
return self.name
+class CollectionChannelListing(PublishableModel):
+ collection = models.ForeignKey(
+ Collection,
+ null=False,
+ blank=False,
+ related_name="channel_listings",
+ on_delete=models.CASCADE,
+ )
+ channel = models.ForeignKey(
+ Channel,
+ null=False,
+ blank=False,
+ related_name="collection_listings",
+ on_delete=models.CASCADE,
+ )
+
+ class Meta:
+ unique_together = [["collection", "channel"]]
+ ordering = ("pk",)
+
+
class CollectionTranslation(SeoModelTranslation):
language_code = models.CharField(max_length=10)
collection = models.ForeignKey(
diff --git a/saleor/product/tasks.py b/saleor/product/tasks.py
index ac9ec7e925..275f164ef6 100644
--- a/saleor/product/tasks.py
+++ b/saleor/product/tasks.py
@@ -5,10 +5,10 @@ from ..discount.models import Sale
from .models import Attribute, Product, ProductType, ProductVariant
from .utils.attributes import generate_name_for_variant
from .utils.variant_prices import (
- update_product_minimal_variant_price,
- update_products_minimal_variant_prices,
- update_products_minimal_variant_prices_of_catalogues,
- update_products_minimal_variant_prices_of_discount,
+ update_product_discounted_price,
+ update_products_discounted_prices,
+ update_products_discounted_prices_of_catalogues,
+ update_products_discounted_prices_of_discount,
)
@@ -42,29 +42,29 @@ def update_variants_names(product_type_pk: int, saved_attributes_ids: List[int])
@app.task
-def update_product_minimal_variant_price_task(product_pk: int):
+def update_product_discounted_price_task(product_pk: int):
product = Product.objects.get(pk=product_pk)
- update_product_minimal_variant_price(product)
+ update_product_discounted_price(product)
@app.task
-def update_products_minimal_variant_prices_of_catalogues_task(
+def update_products_discounted_prices_of_catalogues_task(
product_ids: Optional[List[int]] = None,
category_ids: Optional[List[int]] = None,
collection_ids: Optional[List[int]] = None,
):
- update_products_minimal_variant_prices_of_catalogues(
+ update_products_discounted_prices_of_catalogues(
product_ids, category_ids, collection_ids
)
@app.task
-def update_products_minimal_variant_prices_of_discount_task(discount_pk: int):
+def update_products_discounted_prices_of_discount_task(discount_pk: int):
discount = Sale.objects.get(pk=discount_pk)
- update_products_minimal_variant_prices_of_discount(discount)
+ update_products_discounted_prices_of_discount(discount)
@app.task
-def update_products_minimal_variant_prices_task(product_ids: List[int]):
+def update_products_discounted_prices_task(product_ids: List[int]):
products = Product.objects.filter(pk__in=product_ids)
- update_products_minimal_variant_prices(products)
+ update_products_discounted_prices(products)
diff --git a/saleor/product/tests/test_category.py b/saleor/product/tests/test_category.py
index 0e6ec08b86..13da34cce0 100644
--- a/saleor/product/tests/test_category.py
+++ b/saleor/product/tests/test_category.py
@@ -17,9 +17,9 @@ def test_collect_categories_tree_products(categories_tree):
)
-@patch("saleor.product.utils.update_products_minimal_variant_prices_task")
+@patch("saleor.product.utils.update_products_discounted_prices_task")
def test_delete_categories(
- mock_update_products_minimal_variant_prices_task,
+ mock_update_products_discounted_prices_task,
categories_tree_with_published_products,
):
parent = categories_tree_with_published_products
@@ -32,7 +32,7 @@ def test_delete_categories(
id__in=[category.id for category in [parent, child]]
).exists()
- calls = mock_update_products_minimal_variant_prices_task.mock_calls
+ calls = mock_update_products_discounted_prices_task.mock_calls
assert len(calls) == 1
call_kwargs = calls[0].kwargs
assert set(call_kwargs["product_ids"]) == {p.pk for p in product_list}
@@ -40,5 +40,6 @@ def test_delete_categories(
for product in product_list:
product.refresh_from_db()
assert not product.category
- assert not product.is_published
- assert not product.publication_date
+ for product_channel_listing in product.channel_listings.all():
+ assert not product_channel_listing.is_published
+ assert not product_channel_listing.publication_date
diff --git a/saleor/product/tests/test_product.py b/saleor/product/tests/test_product.py
index e5601382f0..2c52ce22f7 100644
--- a/saleor/product/tests/test_product.py
+++ b/saleor/product/tests/test_product.py
@@ -12,12 +12,12 @@ from .. import models
from ..models import DigitalContentUrl
from ..thumbnails import create_product_thumbnails
from ..utils.attributes import associate_attribute_values_to_instance
-from ..utils.costs import get_margin_for_variant
+from ..utils.costs import get_margin_for_variant_channel_listing
from ..utils.digital_products import increment_download_count
-def test_filtering_by_attributes(
- db, color_attribute, size_attribute, category, settings
+def test_filtering_by_attribute(
+ db, color_attribute, size_attribute, category, channel_USD, settings
):
product_type_a = models.ProductType.objects.create(
name="New class", slug="new-class1", has_variants=True
@@ -33,8 +33,13 @@ def test_filtering_by_attributes(
product_type=product_type_a,
category=category,
)
- models.ProductVariant.objects.create(
- product=product_a, sku="1234", price_amount=Decimal(10)
+ variant_a = models.ProductVariant.objects.create(product=product_a, sku="1234")
+ models.ProductVariantChannelListing.objects.create(
+ variant=variant_a,
+ channel=channel_USD,
+ cost_price_amount=Decimal(1),
+ price_amount=Decimal(10),
+ currency=channel_USD.currency_code,
)
product_b = models.Product.objects.create(
name="Test product b",
@@ -42,8 +47,13 @@ def test_filtering_by_attributes(
product_type=product_type_b,
category=category,
)
- variant_b = models.ProductVariant.objects.create(
- product=product_b, sku="12345", price_amount=Decimal(10)
+ variant_b = models.ProductVariant.objects.create(product=product_b, sku="12345")
+ models.ProductVariantChannelListing.objects.create(
+ variant=variant_b,
+ channel=channel_USD,
+ cost_price_amount=Decimal(1),
+ price_amount=Decimal(10),
+ currency=channel_USD.currency_code,
)
color = color_attribute.values.first()
color_2 = color_attribute.values.last()
@@ -101,24 +111,40 @@ def test_get_price(
include_discounts,
site_settings,
discount_info,
+ channel_USD,
):
product = models.Product.objects.create(
product_type=product_type, category=category,
)
- variant = product.variants.create(price_amount=15)
-
- price = variant.get_price(discounts=[discount_info] if include_discounts else [])
+ variant = product.variants.create()
+ models.ProductVariantChannelListing.objects.create(
+ variant=variant,
+ channel=channel_USD,
+ price_amount=Decimal(15),
+ currency=channel_USD.currency_code,
+ )
+ price = variant.get_price(
+ channel_USD.slug, discounts=[discount_info] if include_discounts else []
+ )
assert price.amount == expected_price
-def test_product_get_price_do_not_charge_taxes(product_type, category, discount_info):
+def test_product_get_price_do_not_charge_taxes(
+ product_type, category, discount_info, channel_USD
+):
product = models.Product.objects.create(
product_type=product_type, category=category, charge_taxes=False,
)
- variant = product.variants.create(price_amount=Decimal(10))
+ variant = product.variants.create()
+ models.ProductVariantChannelListing.objects.create(
+ variant=variant,
+ channel=channel_USD,
+ price_amount=Decimal(10),
+ currency=channel_USD.currency_code,
+ )
- price = variant.get_price(discounts=[discount_info])
+ price = variant.get_price(channel_USD.slug, discounts=[discount_info])
assert price == Money("5.00", "USD")
@@ -216,16 +242,25 @@ def test_digital_product_view_url_expired(client, digital_content):
@pytest.mark.parametrize(
"price, cost", [(Money("0", "USD"), Money("1", "USD")), (Money("2", "USD"), None)]
)
-def test_costs_get_margin_for_variant(variant, price, cost):
- variant.cost_price = cost
- variant.price = price
- assert not get_margin_for_variant(variant)
+def test_costs_get_margin_for_variant_channel_listing(
+ variant, price, cost, channel_USD
+):
+ variant_channel_listing = variant.channel_listings.filter(
+ channel_id=channel_USD.id
+ ).first()
+ variant_channel_listing.cost_price = cost
+ variant_channel_listing.price = price
+ assert not get_margin_for_variant_channel_listing(variant_channel_listing)
@patch("saleor.product.thumbnails.create_thumbnails")
def test_create_product_thumbnails(mock_create_thumbnails, product_with_image):
product_image = product_with_image.images.first()
create_product_thumbnails(product_image.pk)
- assert mock_create_thumbnails.called_once_with(
- product_image.pk, models.ProductImage, "products"
- )
+ assert mock_create_thumbnails.call_count == 1
+ args, kwargs = mock_create_thumbnails.call_args
+ assert kwargs == {
+ "model": models.ProductImage,
+ "pk": product_image.pk,
+ "size_set": "products",
+ }
diff --git a/saleor/product/tests/test_product_attributes.py b/saleor/product/tests/test_product_attributes.py
index a42513e78f..c74bf4490e 100644
--- a/saleor/product/tests/test_product_attributes.py
+++ b/saleor/product/tests/test_product_attributes.py
@@ -4,7 +4,13 @@ from unittest.mock import MagicMock, Mock
import pytest
from .. import AttributeInputType
-from ..models import AttributeValue, Product, ProductType, ProductVariant
+from ..models import (
+ AttributeValue,
+ Product,
+ ProductType,
+ ProductVariant,
+ ProductVariantChannelListing,
+)
from ..tasks import _update_variants_names
from ..utils.attributes import (
associate_attribute_values_to_instance,
@@ -13,7 +19,7 @@ from ..utils.attributes import (
@pytest.fixture()
-def variant_with_no_attributes(category):
+def variant_with_no_attributes(category, channel_USD):
"""Create a variant having no attributes, the same for the parent product."""
product_type = ProductType.objects.create(
name="Test product type", has_variants=True, is_shipping_required=True
@@ -21,8 +27,13 @@ def variant_with_no_attributes(category):
product = Product.objects.create(
name="Test product", product_type=product_type, category=category,
)
- variant = ProductVariant.objects.create(
- product=product, sku="123", price_amount=Decimal(10)
+ variant = ProductVariant.objects.create(product=product, sku="123")
+ ProductVariantChannelListing.objects.create(
+ variant=variant,
+ channel=channel_USD,
+ cost_price_amount=Decimal(1),
+ price_amount=Decimal(10),
+ currency=channel_USD.currency_code,
)
return variant
diff --git a/saleor/product/tests/test_product_availability.py b/saleor/product/tests/test_product_availability.py
index a8fd5cf0b4..701b2a7be0 100644
--- a/saleor/product/tests/test_product_availability.py
+++ b/saleor/product/tests/test_product_availability.py
@@ -1,75 +1,31 @@
import datetime
-from decimal import Decimal
from unittest.mock import Mock
from freezegun import freeze_time
from prices import Money, TaxedMoney, TaxedMoneyRange
from ...plugins.manager import PluginsManager
-from ...warehouse.models import Stock
-from .. import ProductAvailabilityStatus, models
-from ..utils.availability import (
- get_product_availability,
- get_product_availability_status,
-)
-
-
-def test_product_availability_status(unavailable_product, warehouse):
- product = unavailable_product
- product.product_type.has_variants = True
-
- # product is not published
- status = get_product_availability_status(product, "US")
- assert status == ProductAvailabilityStatus.NOT_PUBLISHED
-
- product.is_published = True
- product.save()
-
- # product has no variants
- status = get_product_availability_status(product, "US")
- assert status == ProductAvailabilityStatus.VARIANTS_MISSSING
-
- variant_1 = product.variants.create(sku="test-1", price_amount=Decimal(10))
- variant_2 = product.variants.create(sku="test-2", price_amount=Decimal(10))
- # create empty stock records
- stock_1 = Stock.objects.create(
- product_variant=variant_1, warehouse=warehouse, quantity=0
- )
- stock_2 = Stock.objects.create(
- product_variant=variant_2, warehouse=warehouse, quantity=0
- )
-
- status = get_product_availability_status(product, "US")
- assert status == ProductAvailabilityStatus.OUT_OF_STOCK
-
- # assign quantity to only one stock record
- stock_1.quantity = 5
- stock_1.save()
- status = get_product_availability_status(product, "US")
- assert status == ProductAvailabilityStatus.LOW_STOCK
+from .. import models
+from ..utils.availability import get_product_availability
- # both stock records have some quantity
- stock_2.quantity = 5
- stock_2.save()
- status = get_product_availability_status(product, "US")
- assert status == ProductAvailabilityStatus.READY_FOR_PURCHASE
- # set product availability date from future
- product.publication_date = datetime.date.today() + datetime.timedelta(days=1)
- product.save()
- status = get_product_availability_status(product, "US")
- assert status == ProductAvailabilityStatus.NOT_YET_AVAILABLE
-
-
-def test_availability(stock, monkeypatch, settings):
+def test_availability(stock, monkeypatch, settings, channel_USD):
product = stock.product_variant.product
+ product_channel_listing = product.channel_listings.first()
+ variants = product.variants.all()
+ variants_channel_listing = models.ProductVariantChannelListing.objects.filter(
+ variant__in=variants
+ )
taxed_price = TaxedMoney(Money("10.0", "USD"), Money("12.30", "USD"))
monkeypatch.setattr(
PluginsManager, "apply_taxes_to_product", Mock(return_value=taxed_price)
)
availability = get_product_availability(
product=product,
+ product_channel_listing=product_channel_listing,
variants=product.variants.all(),
+ variants_channel_listing=variants_channel_listing,
+ channel=channel_USD,
collections=[],
discounts=[],
country="PL",
@@ -86,9 +42,12 @@ def test_availability(stock, monkeypatch, settings):
settings.OPENEXCHANGERATES_API_KEY = "fake-key"
availability = get_product_availability(
product=product,
- variants=product.variants.all(),
+ product_channel_listing=product_channel_listing,
+ variants=variants,
+ variants_channel_listing=variants_channel_listing,
collections=[],
discounts=[],
+ channel=channel_USD,
local_currency="PLN",
country="PL",
)
@@ -96,9 +55,12 @@ def test_availability(stock, monkeypatch, settings):
availability = get_product_availability(
product=product,
- variants=product.variants.all(),
+ product_channel_listing=product_channel_listing,
+ variants=variants,
+ variants_channel_listing=variants_channel_listing,
collections=[],
discounts=[],
+ channel=channel_USD,
country="PL",
)
assert availability.price_range.start.tax.amount
@@ -107,53 +69,187 @@ def test_availability(stock, monkeypatch, settings):
assert availability.price_range_undiscounted.stop.tax.amount
-def test_available_products_only_published(product_list):
- product = product_list[0]
- product.is_published = False
- product.save()
+def test_available_products_only_published(product_list, channel_USD):
+ channel_listing = product_list[0].channel_listings.get()
+ channel_listing.is_published = False
+ channel_listing.save(update_fields=["is_published"])
- available_products = models.Product.objects.published()
+ available_products = models.Product.objects.published(channel_USD.slug)
assert available_products.count() == 2
- assert all([product.is_published for product in available_products])
+ assert all(
+ [
+ product.channel_listings.get(channel__slug=channel_USD.slug).is_published
+ for product in available_products
+ ]
+ )
-def test_available_products_only_available(product_list):
- product = product_list[0]
+def test_available_products_only_available(product_list, channel_USD):
+ channel_listing = product_list[0].channel_listings.get()
date_tomorrow = datetime.date.today() + datetime.timedelta(days=1)
- product.publication_date = date_tomorrow
- product.save()
- available_products = models.Product.objects.published()
+ channel_listing.publication_date = date_tomorrow
+ channel_listing.save(update_fields=["publication_date"])
+
+ available_products = models.Product.objects.published(channel_USD.slug)
assert available_products.count() == 2
- assert all([product.is_visible for product in available_products])
+ assert all(
+ [
+ product.channel_listings.get(channel__slug=channel_USD.slug).is_published
+ for product in available_products
+ ]
+ )
+
+
+def test_available_products_available_from_yesterday(product_list, channel_USD):
+ channel_listing = product_list[0].channel_listings.get()
+ date_tomorrow = datetime.date.today() - datetime.timedelta(days=1)
+ channel_listing.publication_date = date_tomorrow
+ channel_listing.save(update_fields=["publication_date"])
+
+ available_products = models.Product.objects.published(channel_USD.slug)
+ assert available_products.count() == 3
+ assert all(
+ [
+ product.channel_listings.get(channel__slug=channel_USD.slug).is_published
+ for product in available_products
+ ]
+ )
+
+
+def test_available_products_available_without_channel_listings(
+ product_list, channel_PLN
+):
+ available_products = models.Product.objects.published(channel_PLN.slug)
+ assert available_products.count() == 0
+
+
+def test_available_products_available_with_many_channels(
+ product_list_with_many_channels, channel_USD, channel_PLN
+):
+ models.ProductChannelListing.objects.filter(
+ product__in=product_list_with_many_channels, channel=channel_PLN
+ ).update(is_published=False)
+
+ available_products = models.Product.objects.published(channel_PLN.slug)
+ assert available_products.count() == 0
+ available_products = models.Product.objects.published(channel_USD.slug)
+ assert available_products.count() == 3
@freeze_time("2020-03-18 12:00:00")
def test_product_is_visible_from_today(product):
- product.publication_date = datetime.date.today()
- product.save()
- assert product.is_visible
+ product_channel_listing = product.channel_listings.get()
+ product_channel_listing.publication_date = datetime.date.today()
+ product_channel_listing.save()
+ assert product_channel_listing.is_visible
-def test_available_products_with_variants(product_list):
+def test_available_products_with_variants(product_list, channel_USD):
product = product_list[0]
product.variants.all().delete()
- available_products = models.Product.objects.published_with_variants()
+ available_products = models.Product.objects.published_with_variants(
+ channel_USD.slug
+ )
+ assert available_products.count() == 2
+
+
+def test_available_products_with_variants_in_many_channels_usd(
+ product_list_with_variants_many_channel, channel_USD
+):
+ available_products = models.Product.objects.published_with_variants(
+ channel_USD.slug
+ )
+ assert available_products.count() == 1
+
+
+def test_available_products_with_variants_in_many_channels_pln(
+ product_list_with_variants_many_channel, channel_PLN
+):
+ available_products = models.Product.objects.published_with_variants(
+ channel_PLN.slug
+ )
assert available_products.count() == 2
-def test_visible_to_customer_user(customer_user, product_list):
+def test_visible_to_customer_user(customer_user, product_list, channel_USD):
product = product_list[0]
product.variants.all().delete()
- available_products = models.Product.objects.visible_to_user(customer_user)
+ available_products = models.Product.objects.visible_to_user(
+ customer_user, channel_USD.slug
+ )
assert available_products.count() == 2
-def test_visible_to_staff_user(customer_user, product_list, permission_manage_products):
+def test_visible_to_staff_user(
+ customer_user, product_list, channel_USD, permission_manage_products
+):
product = product_list[0]
product.variants.all().delete()
customer_user.user_permissions.add(permission_manage_products)
- available_products = models.Product.objects.visible_to_user(customer_user)
+ available_products = models.Product.objects.visible_to_user(
+ customer_user, channel_USD.slug
+ )
assert available_products.count() == 3
+
+
+def test_filter_not_published_product_is_unpublished(product, channel_USD):
+ channel_listing = product.channel_listings.get()
+ channel_listing.is_published = False
+ channel_listing.save(update_fields=["is_published"])
+
+ available_products = models.Product.objects.not_published(channel_USD.slug)
+ assert available_products.count() == 1
+
+
+def test_filter_not_published_product_published_tomorrow(product, channel_USD):
+ date_tomorrow = datetime.date.today() + datetime.timedelta(days=1)
+ channel_listing = product.channel_listings.get()
+ channel_listing.is_published = True
+ channel_listing.publication_date = date_tomorrow
+ channel_listing.save(update_fields=["is_published", "publication_date"])
+
+ available_products = models.Product.objects.not_published(channel_USD.slug)
+ assert available_products.count() == 1
+
+
+def test_filter_not_published_product_not_published_tomorrow(product, channel_USD):
+ date_tomorrow = datetime.date.today() + datetime.timedelta(days=1)
+ channel_listing = product.channel_listings.get()
+ channel_listing.is_published = False
+ channel_listing.publication_date = date_tomorrow
+ channel_listing.save(update_fields=["is_published", "publication_date"])
+
+ available_products = models.Product.objects.not_published(channel_USD.slug)
+ assert available_products.count() == 1
+
+
+def test_filter_not_published_product_is_published(product, channel_USD):
+ available_products = models.Product.objects.not_published(channel_USD.slug)
+ assert available_products.count() == 0
+
+
+def test_filter_not_published_product_is_unpublished_other_channel(
+ product, channel_USD, channel_PLN
+):
+ models.ProductChannelListing.objects.create(
+ product=product, channel=channel_PLN, is_published=False
+ )
+
+ available_products_usd = models.Product.objects.not_published(channel_USD.slug)
+ assert available_products_usd.count() == 0
+
+ available_products_pln = models.Product.objects.not_published(channel_PLN.slug)
+ assert available_products_pln.count() == 1
+
+
+def test_filter_not_published_product_without_assigned_channel(
+ product, channel_USD, channel_PLN
+):
+ not_available_products_usd = models.Product.objects.not_published(channel_USD.slug)
+ assert not_available_products_usd.count() == 0
+
+ not_available_products_pln = models.Product.objects.not_published(channel_PLN.slug)
+ assert not_available_products_pln.count() == 1
diff --git a/saleor/product/tests/test_product_minimal_variant_price.py b/saleor/product/tests/test_product_minimal_variant_price.py
index 09a98f8d4e..5df5708af3 100644
--- a/saleor/product/tests/test_product_minimal_variant_price.py
+++ b/saleor/product/tests/test_product_minimal_variant_price.py
@@ -1,170 +1,118 @@
from unittest.mock import patch
from django.core.management import call_command
-from graphql_relay import to_global_id
from prices import Money
-from ...graphql.tests.utils import get_graphql_content
-from ..models import ProductVariant
from ..tasks import (
- update_products_minimal_variant_prices_of_catalogues,
- update_products_minimal_variant_prices_task,
+ update_products_discounted_prices_of_catalogues,
+ update_products_discounted_prices_task,
)
-from ..utils.variant_prices import update_product_minimal_variant_price
+from ..utils.variant_prices import update_product_discounted_price
-def test_update_product_minimal_variant_price(product):
+def test_update_product_discounted_price(product, channel_USD):
variant = product.variants.first()
- variant.price = Money("4.99", "USD")
- variant.save()
- product.refresh_from_db()
+ variant_channel_listing = variant.channel_listings.get(channel_id=channel_USD.id)
+ product_channel_listing = product.channel_listings.get(channel_id=channel_USD.id)
+ variant_channel_listing.price = Money("4.99", "USD")
+ variant_channel_listing.save()
+ product_channel_listing.refresh_from_db()
- assert product.minimal_variant_price == Money("10", "USD")
- update_product_minimal_variant_price(product)
- assert product.minimal_variant_price == variant.price
+ assert product_channel_listing.discounted_price == Money("10", "USD")
+ update_product_discounted_price(product)
-def test_update_products_minimal_variant_prices_of_catalogues_for_product(product):
- variant = ProductVariant(
- product=product, sku="SKU_MINIMAL_VARIANT_PRICE", price=Money("0.99", "USD"),
- )
- variant.save()
- product.refresh_from_db()
- assert product.minimal_variant_price == Money("10", "USD")
- update_products_minimal_variant_prices_of_catalogues(product_ids=[product.pk])
- product.refresh_from_db()
- assert product.minimal_variant_price == variant.price
+ product_channel_listing.refresh_from_db()
+ assert product_channel_listing.discounted_price == variant_channel_listing.price
-def test_update_products_minimal_variant_prices_of_catalogues_for_category(
- category, product
+def test_update_products_discounted_prices_of_catalogues_for_product(
+ product, channel_USD
):
- variant = ProductVariant(
- product=product, sku="SKU_MINIMAL_VARIANT_PRICE", price=Money("0.89", "USD"),
- )
- variant.save()
- product.refresh_from_db()
- assert product.minimal_variant_price == Money("10", "USD")
- update_products_minimal_variant_prices_of_catalogues(
- category_ids=[product.category_id]
- )
- product.refresh_from_db()
- assert product.minimal_variant_price == variant.price
+ variant = product.variants.first()
+ variant_channel_listing = variant.channel_listings.get(channel_id=channel_USD.id)
+ product_channel_listing = product.channel_listings.get(channel_id=channel_USD.id)
+ variant_channel_listing.price = Money("0.99", "USD")
+ variant_channel_listing.save()
+ product_channel_listing.refresh_from_db()
+
+ assert product_channel_listing.discounted_price == Money("10", "USD")
+
+ update_products_discounted_prices_of_catalogues(product_ids=[product.pk])
+ product_channel_listing.refresh_from_db()
+ assert product_channel_listing.discounted_price == variant_channel_listing.price
-def test_update_products_minimal_variant_prices_of_catalogues_for_collection(
- collection, product
+
+def test_update_products_discounted_prices_of_catalogues_for_category(
+ category, product, channel_USD
):
- variant = ProductVariant(
- product=product, sku="SKU_MINIMAL_VARIANT_PRICE", price=Money("0.79", "USD"),
+ variant = product.variants.first()
+ variant_channel_listing = variant.channel_listings.get(
+ channel=channel_USD, variant=variant,
)
- variant.save()
- product.refresh_from_db()
- collection.products.add(product)
- assert product.minimal_variant_price == Money("10", "USD")
- update_products_minimal_variant_prices_of_catalogues(collection_ids=[collection.pk])
- product.refresh_from_db()
- assert product.minimal_variant_price == variant.price
+ variant_channel_listing.price = Money("0.89", "USD")
+ variant_channel_listing.save()
+ product_channel_listing = product.channel_listings.get(
+ channel_id=channel_USD.id, product_id=product.id
+ )
+ product_channel_listing.refresh_from_db()
+ assert product_channel_listing.discounted_price == Money("10", "USD")
+ update_products_discounted_prices_of_catalogues(category_ids=[product.category_id])
+ product_channel_listing.refresh_from_db()
+ assert product_channel_listing.discounted_price == variant_channel_listing.price
-@patch(
- "saleor.graphql.product.mutations.products"
- ".update_product_minimal_variant_price_task"
-)
-def test_product_update_updates_minimal_variant_price(
- mock_update_product_minimal_variant_price_task,
- staff_api_client,
- product,
- permission_manage_products,
+
+def test_update_products_discounted_prices_of_catalogues_for_collection(
+ collection, product, channel_USD
):
- assert product.minimal_variant_price == Money("10.00", "USD")
- query = """
- mutation ProductUpdate(
- $productId: ID!,
- $basePrice: PositiveDecimal!,
- ) {
- productUpdate(
- id: $productId
- input: {
- basePrice: $basePrice
- }
- ) {
- product {
- name
- minimalVariantPrice {
- amount
- }
- }
- errors {
- message
- field
- }
- }
- }
- """
- product_id = to_global_id("Product", product.pk)
- product_price = "1.99"
- variables = {"productId": product_id, "basePrice": product_price}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_products]
+ variant = product.variants.first()
+ variant_channel_listing = variant.channel_listings.get(
+ channel=channel_USD, variant=variant,
)
- assert response.status_code == 200
+ variant_channel_listing.price = Money("0.79", "USD")
+ product_channel_listing = product.channel_listings.get(channel_id=channel_USD.id)
+ variant_channel_listing.save()
+ product_channel_listing.refresh_from_db()
+ collection.products.add(product)
+ assert product_channel_listing.discounted_price == Money("10", "USD")
- content = get_graphql_content(response)
- data = content["data"]["productUpdate"]
- assert data["errors"] == []
+ update_products_discounted_prices_of_catalogues(collection_ids=[collection.pk])
+ product_channel_listing.refresh_from_db()
+ assert product_channel_listing.discounted_price == variant_channel_listing.price
- mock_update_product_minimal_variant_price_task.delay.assert_called_once_with(
- product.pk
- )
+def test_update_products_discounted_prices_task(product_list):
-def test_update_products_minimal_variant_prices_task(product_list):
price = Money("0.01", "USD")
for product in product_list:
- assert product.minimal_variant_price is None
+ product_channel_listing = product.channel_listings.get()
+ assert product_channel_listing.discounted_price != price
variant = product.variants.first()
- variant.price = price
- variant.save()
- # Check that "variant.save()" doesn't update the "minimal_variant_price"
- assert product.minimal_variant_price is None
-
- update_products_minimal_variant_prices_task.apply(
+ variant_channel_listing = variant.channel_listings.get()
+ variant_channel_listing.price = price
+ variant_channel_listing.save()
+ # Check that "variant.save()" doesn't update the "discounted_price"
+ assert product_channel_listing.discounted_price != price
+ update_products_discounted_prices_task.apply(
kwargs={"product_ids": [product.pk for product in product_list]}
)
for product in product_list:
product.refresh_from_db()
- assert product.minimal_variant_price == price
-
-
-def test_product_variant_objects_create_updates_minimal_variant_price(product):
- assert product.minimal_variant_price == Money("10.00", "USD")
- ProductVariant.objects.create(product=product, sku="1", price=Money("1.00", "USD"))
- product.refresh_from_db()
- assert product.minimal_variant_price == Money("1.00", "USD")
-
-
-def test_product_variant_objects_bulk_create_updates_minimal_variant_price(product):
- assert product.minimal_variant_price == Money("10.00", "USD")
- ProductVariant.objects.bulk_create(
- [
- ProductVariant(product=product, sku="1", price=Money("1.00", "USD")),
- ProductVariant(product=product, sku="2", price=Money("5.00", "USD")),
- ]
- )
- product.refresh_from_db()
- assert product.minimal_variant_price == Money("1.00", "USD")
+ product_channel_listing = product.channel_listings.get()
+ assert product_channel_listing.discounted_price == price
@patch(
"saleor.product.management.commands"
- ".update_all_products_minimal_variant_prices"
- ".update_product_minimal_variant_price"
+ ".update_all_products_discounted_prices"
+ ".update_product_discounted_price"
)
-def test_management_commmand_update_all_products_minimal_variant_price(
- mock_update_product_minimal_variant_price, product_list
+def test_management_commmand_update_all_products_discounted_price(
+ mock_update_product_discounted_price, product_list
):
- call_command("update_all_products_minimal_variant_prices")
- call_args_list = mock_update_product_minimal_variant_price.call_args_list
+ call_command("update_all_products_discounted_prices")
+ call_args_list = mock_update_product_discounted_price.call_args_list
for (args, kwargs), product in zip(call_args_list, product_list):
assert args[0] == product
diff --git a/saleor/product/tests/test_product_without_variants.py b/saleor/product/tests/test_product_without_variants.py
new file mode 100644
index 0000000000..6cc096c3e9
--- /dev/null
+++ b/saleor/product/tests/test_product_without_variants.py
@@ -0,0 +1,16 @@
+from ..utils import get_products_ids_without_variants
+
+
+def test_get_products_ids_without_variants(product_list):
+ assert get_products_ids_without_variants(product_list) == []
+
+ product = product_list[0]
+ product.variants.all().delete()
+
+ second_product = product_list[1]
+ second_product.variants.all().delete()
+
+ assert get_products_ids_without_variants(product_list) == [
+ product.id,
+ second_product.id,
+ ]
diff --git a/saleor/product/utils/__init__.py b/saleor/product/utils/__init__.py
index 42e81b691c..3fd0e8d5a7 100644
--- a/saleor/product/utils/__init__.py
+++ b/saleor/product/utils/__init__.py
@@ -1,11 +1,10 @@
-from typing import TYPE_CHECKING, List, Union
-from urllib.parse import urlencode
+from typing import TYPE_CHECKING, Dict, Iterable, List, Union
-from django.conf import settings
from django.db import transaction
from ...core.taxes import TaxedMoney, zero_taxed_money
-from ..tasks import update_products_minimal_variant_prices_task
+from ..models import Product, ProductChannelListing
+from ..tasks import update_products_discounted_prices_task
if TYPE_CHECKING:
# flake8: noqa
@@ -13,16 +12,22 @@ if TYPE_CHECKING:
from django.db.models.query import QuerySet
- from ..models import Category, Product, ProductVariant
+ from ...order.models import OrderLine, Order
+ from ..models import Product, ProductVariant, Category
def calculate_revenue_for_variant(
- variant: "ProductVariant", start_date: Union["date", "datetime"]
+ variant: "ProductVariant",
+ start_date: Union["date", "datetime"],
+ order_lines: Iterable["OrderLine"],
+ orders_dict: Dict[int, "Order"],
+ currency_code: str,
) -> TaxedMoney:
"""Calculate total revenue generated by a product variant."""
- revenue = zero_taxed_money()
- for order_line in variant.order_lines.all():
- if order_line.order.created >= start_date:
+ revenue = zero_taxed_money(currency_code)
+ for order_line in order_lines:
+ order = orders_dict[order_line.order_id]
+ if order.created >= start_date:
net = order_line.unit_price_net * order_line.quantity
gross = order_line.unit_price_gross * order_line.quantity
revenue += TaxedMoney(net, gross)
@@ -45,10 +50,12 @@ def delete_categories(categories_ids: List[str]):
for category in categories:
products = products | collect_categories_tree_products(category)
- products.update(is_published=False, publication_date=None)
+ ProductChannelListing.objects.filter(product__in=products).update(
+ is_published=False, publication_date=None
+ )
product_ids = list(products.values_list("id", flat=True))
categories.delete()
- update_products_minimal_variant_prices_task.delay(product_ids=product_ids)
+ update_products_discounted_prices_task.delay(product_ids=product_ids)
def collect_categories_tree_products(category: "Category") -> "QuerySet[Product]":
@@ -58,3 +65,12 @@ def collect_categories_tree_products(category: "Category") -> "QuerySet[Product]
for descendant in descendants:
products = products | descendant.products.all()
return products
+
+
+def get_products_ids_without_variants(products_list: "List[Product]") -> "List[str]":
+ """Return list of product's ids without variants."""
+ products_ids = [product.id for product in products_list]
+ products_ids_without_variants = Product.objects.filter(
+ id__in=products_ids, variants__isnull=True
+ ).values_list("id", flat=True)
+ return list(products_ids_without_variants)
diff --git a/saleor/product/utils/availability.py b/saleor/product/utils/availability.py
index 6ebd9d8fda..86f2873e95 100644
--- a/saleor/product/utils/availability.py
+++ b/saleor/product/utils/availability.py
@@ -1,21 +1,22 @@
from dataclasses import dataclass
-from typing import TYPE_CHECKING, Iterable, Optional, Tuple, Union
+from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union
import opentracing
from django.conf import settings
from prices import MoneyRange, TaxedMoney, TaxedMoneyRange
-from saleor.product.models import Collection, Product, ProductVariant
-
+from ...channel.models import Channel
from ...core.utils import to_local_currency
from ...discount import DiscountInfo
from ...discount.utils import calculate_discounted_price
from ...plugins.manager import get_plugins_manager
-from ...warehouse.availability import (
- are_all_product_variants_in_stock,
- is_product_in_stock,
+from ...product.models import (
+ Collection,
+ Product,
+ ProductChannelListing,
+ ProductVariant,
+ ProductVariantChannelListing,
)
-from .. import ProductAvailabilityStatus
if TYPE_CHECKING:
# flake8: noqa
@@ -42,30 +43,6 @@ class VariantAvailability:
discount_local_currency: Optional[TaxedMoney]
-def get_product_availability_status(
- product: "Product", country: str
-) -> ProductAvailabilityStatus:
- is_visible = product.is_visible
- are_all_variants_in_stock = are_all_product_variants_in_stock(product, country)
- is_in_stock = is_product_in_stock(product, country)
- requires_variants = product.product_type.has_variants
-
- if not product.is_published:
- return ProductAvailabilityStatus.NOT_PUBLISHED
- if requires_variants and not product.variants.exists():
- # We check the requires_variants flag here in order to not show this
- # status with product types that don't require variants, as in that
- # case variants are hidden from the UI and user doesn't manage them.
- return ProductAvailabilityStatus.VARIANTS_MISSSING
- if not is_in_stock:
- return ProductAvailabilityStatus.OUT_OF_STOCK
- if not are_all_variants_in_stock:
- return ProductAvailabilityStatus.LOW_STOCK
- if not is_visible and product.publication_date is not None:
- return ProductAvailabilityStatus.NOT_YET_AVAILABLE
- return ProductAvailabilityStatus.READY_FOR_PURCHASE
-
-
def _get_total_discount_from_range(
undiscounted: TaxedMoneyRange, discounted: TaxedMoneyRange
) -> Optional[TaxedMoney]:
@@ -110,15 +87,18 @@ def _get_product_price_range(
def get_variant_price(
*,
variant: ProductVariant,
+ variant_channel_listing: ProductVariantChannelListing,
product: Product,
collections: Iterable[Collection],
- discounts: Iterable[DiscountInfo]
+ discounts: Iterable[DiscountInfo],
+ channel: Channel
):
return calculate_discounted_price(
product=product,
- price=variant.price,
+ price=variant_channel_listing.price,
collections=collections,
discounts=discounts,
+ channel=channel,
)
@@ -126,19 +106,23 @@ def get_product_price_range(
*,
product: Product,
variants: Iterable[ProductVariant],
+ variants_channel_listing: List[ProductVariantChannelListing],
collections: Iterable[Collection],
- discounts: Iterable[DiscountInfo]
+ discounts: Iterable[DiscountInfo],
+ channel: Channel,
) -> Optional[MoneyRange]:
with opentracing.global_tracer().start_active_span("get_product_price_range"):
if variants:
prices = [
get_variant_price(
variant=variant,
+ variant_channel_listing=variants_channel_listing[i],
product=product,
collections=collections,
discounts=discounts,
+ channel=channel,
)
- for variant in variants
+ for i, variant in enumerate(variants)
]
return MoneyRange(min(prices), max(prices))
@@ -148,9 +132,12 @@ def get_product_price_range(
def get_product_availability(
*,
product: Product,
+ product_channel_listing: Optional[ProductChannelListing],
variants: Iterable[ProductVariant],
+ variants_channel_listing: List[ProductVariantChannelListing],
collections: Iterable[Collection],
discounts: Iterable[DiscountInfo],
+ channel: Channel,
country: Optional[str] = None,
local_currency: Optional[str] = None,
plugins: Optional["PluginsManager"] = None,
@@ -163,8 +150,10 @@ def get_product_availability(
discounted_net_range = get_product_price_range(
product=product,
variants=variants,
+ variants_channel_listing=variants_channel_listing,
collections=collections,
discounts=discounts,
+ channel=channel,
)
if discounted_net_range is not None:
discounted = TaxedMoneyRange(
@@ -178,7 +167,12 @@ def get_product_availability(
undiscounted = None
undiscounted_net_range = get_product_price_range(
- product=product, variants=variants, collections=collections, discounts=[]
+ product=product,
+ variants=variants,
+ variants_channel_listing=variants_channel_listing,
+ collections=collections,
+ discounts=[],
+ channel=channel,
)
if undiscounted_net_range is not None:
undiscounted = TaxedMoneyRange(
@@ -199,7 +193,10 @@ def get_product_availability(
discounted, undiscounted, local_currency
)
- is_on_sale = product.is_visible and discount is not None
+ is_visible = (
+ product_channel_listing is not None and product_channel_listing.is_visible
+ )
+ is_on_sale = is_visible and discount is not None
return ProductAvailability(
on_sale=is_on_sale,
@@ -213,9 +210,12 @@ def get_product_availability(
def get_variant_availability(
variant: ProductVariant,
+ variant_channel_listing: ProductVariantChannelListing,
product: Product,
+ product_channel_listing: Optional[ProductChannelListing],
collections: Iterable[Collection],
discounts: Iterable[DiscountInfo],
+ channel: Channel,
country: Optional[str] = None,
local_currency: Optional[str] = None,
plugins: Optional["PluginsManager"] = None,
@@ -227,16 +227,23 @@ def get_variant_availability(
product,
get_variant_price(
variant=variant,
+ variant_channel_listing=variant_channel_listing,
product=product,
collections=collections,
discounts=discounts,
+ channel=channel,
),
country,
)
undiscounted = plugins.apply_taxes_to_product(
product,
get_variant_price(
- variant=variant, product=product, collections=collections, discounts=[]
+ variant=variant,
+ variant_channel_listing=variant_channel_listing,
+ product=product,
+ collections=collections,
+ discounts=[],
+ channel=channel,
),
country,
)
@@ -253,7 +260,10 @@ def get_variant_availability(
price_local_currency = None
discount_local_currency = None
- is_on_sale = product.is_visible and discount is not None
+ is_visible = (
+ product_channel_listing is not None and product_channel_listing.is_visible
+ )
+ is_on_sale = is_visible and discount is not None
return VariantAvailability(
on_sale=is_on_sale,
diff --git a/saleor/product/utils/costs.py b/saleor/product/utils/costs.py
index dcf3e147a6..ccfb69eaaf 100644
--- a/saleor/product/utils/costs.py
+++ b/saleor/product/utils/costs.py
@@ -4,12 +4,11 @@ from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple
from prices import MoneyRange
from ...core.taxes import zero_money
+from ..models import ProductVariantChannelListing
if TYPE_CHECKING:
from prices import Money
- from ..models import Product, ProductVariant
-
@dataclass
class CostsData:
@@ -22,17 +21,20 @@ class CostsData:
def get_product_costs_data(
- product: "Product",
+ variant_channel_listings: Iterable[ProductVariantChannelListing],
+ has_variants: bool,
+ currency: str,
) -> Tuple[MoneyRange, Tuple[float, float]]:
- purchase_costs_range = MoneyRange(start=zero_money(), stop=zero_money())
+ purchase_costs_range = MoneyRange(
+ start=zero_money(currency), stop=zero_money(currency)
+ )
margin = (0.0, 0.0)
- if not product.variants.exists():
+ if not has_variants:
return purchase_costs_range, margin
- variants = product.variants.all()
- costs_data = get_cost_data_from_variants(variants)
+ costs_data = get_cost_data_from_variant_channel_listing(variant_channel_listings)
if costs_data.costs:
purchase_costs_range = MoneyRange(min(costs_data.costs), max(costs_data.costs))
if costs_data.margins:
@@ -40,38 +42,44 @@ def get_product_costs_data(
return purchase_costs_range, margin
-def get_cost_data_from_variants(variants: Iterable["ProductVariant"]) -> CostsData:
+def get_cost_data_from_variant_channel_listing(
+ variant_channel_listings: Iterable["ProductVariantChannelListing"],
+) -> CostsData:
costs: List[CostsData] = []
margins: List[float] = []
- for variant in variants:
- costs_data = get_variant_costs_data(variant)
+ for variant_channel_listing in variant_channel_listings:
+ costs_data = get_variant_costs_data(variant_channel_listing)
costs += costs_data.costs
margins += costs_data.margins
return CostsData(costs, margins)
-def get_variant_costs_data(variant: "ProductVariant") -> CostsData:
+def get_variant_costs_data(
+ variant_channel_listing: "ProductVariantChannelListing",
+) -> CostsData:
costs = []
margins = []
- costs.append(get_cost_price(variant))
- margin = get_margin_for_variant(variant)
+ costs.append(get_cost_price(variant_channel_listing))
+ margin = get_margin_for_variant_channel_listing(variant_channel_listing)
if margin:
margins.append(margin)
return CostsData(costs, margins)
-def get_cost_price(variant: "ProductVariant") -> "Money":
- if not variant.cost_price:
- return zero_money()
- return variant.cost_price
+def get_cost_price(variant_channel_listing: "ProductVariantChannelListing") -> "Money":
+ if not variant_channel_listing.cost_price:
+ return zero_money(variant_channel_listing.currency)
+ return variant_channel_listing.cost_price
-def get_margin_for_variant(variant: "ProductVariant") -> Optional[float]:
- if variant.cost_price is None:
+def get_margin_for_variant_channel_listing(
+ variant_channel_listing: "ProductVariantChannelListing",
+) -> Optional[float]:
+ if variant_channel_listing.cost_price is None:
return None
- base_price = variant.price
+ base_price = variant_channel_listing.price # type: ignore
if not base_price:
return None
- margin = base_price - variant.cost_price
+ margin = base_price - variant_channel_listing.cost_price
percent = round((margin / base_price) * 100, 0)
return percent
diff --git a/saleor/product/utils/variant_prices.py b/saleor/product/utils/variant_prices.py
index 6a930971d2..ee6ffda93e 100644
--- a/saleor/product/utils/variant_prices.py
+++ b/saleor/product/utils/variant_prices.py
@@ -1,56 +1,76 @@
import operator
+from collections import defaultdict
from functools import reduce
from typing import Optional
from django.db.models.query_utils import Q
from prices import Money
-from ...discount.utils import fetch_active_discounts
-from ..models import Product
+from ...discount.utils import calculate_discounted_price, fetch_active_discounts
+from ..models import Product, ProductChannelListing, ProductVariantChannelListing
-def _get_product_minimal_variant_price(product, discounts) -> Optional[Money]:
- # Start with the product's price as the minimal one
- minimal_variant_price = None
- for variant in product.variants.all():
- variant_price = variant.get_price(discounts=discounts)
- if minimal_variant_price is None:
- minimal_variant_price = variant_price
- else:
- minimal_variant_price = min(minimal_variant_price, variant_price)
- return minimal_variant_price
+def _get_variant_prices_in_channels_dict(product):
+ prices_dict = defaultdict(list)
+ for variant_channel_listing in ProductVariantChannelListing.objects.filter(
+ variant__product_id=product
+ ):
+ channel_id = variant_channel_listing.channel_id
+ prices_dict[channel_id].append(variant_channel_listing.price)
+ return prices_dict
-def update_product_minimal_variant_price(product, discounts=None, save=True):
- if discounts is None:
- discounts = fetch_active_discounts()
- minimal_variant_price = _get_product_minimal_variant_price(product, discounts)
- if product.minimal_variant_price != minimal_variant_price:
- product.minimal_variant_price_amount = minimal_variant_price.amount
- if save:
- product.save(update_fields=["minimal_variant_price_amount", "updated_at"])
- return product
+def _get_product_discounted_price(
+ variant_prices, product, collections, discounts, channel
+) -> Optional[Money]:
+ discounted_variants_price = []
+ for variant_price in variant_prices:
+ discounted_variant_price = calculate_discounted_price(
+ product=product,
+ price=variant_price,
+ collections=collections,
+ discounts=discounts,
+ channel=channel,
+ )
+ discounted_variants_price.append(discounted_variant_price)
+ return min(discounted_variants_price)
-def update_products_minimal_variant_prices(products, discounts=None):
+def update_product_discounted_price(product, discounts=None):
if discounts is None:
discounts = fetch_active_discounts()
- changed_products_to_update = []
- for product in products:
- old_minimal_variant_price = product.minimal_variant_price
- updated_product = update_product_minimal_variant_price(
- product, discounts, save=False
+ collections = list(product.collections.all())
+ variant_prices_in_channels_dict = _get_variant_prices_in_channels_dict(product)
+ changed_products_channels_to_update = []
+ for product_channel_listing in product.channel_listings.all():
+ channel_id = product_channel_listing.channel_id
+ variant_prices_dict = variant_prices_in_channels_dict[channel_id]
+ product_discounted_price = _get_product_discounted_price(
+ variant_prices_dict,
+ product,
+ collections,
+ discounts,
+ product_channel_listing.channel,
)
- # Check if the "minimal_variant_price" has changed
- if updated_product.minimal_variant_price != old_minimal_variant_price:
- changed_products_to_update.append(updated_product)
- # Bulk update the changed products
- Product.objects.bulk_update(
- changed_products_to_update, ["minimal_variant_price_amount"]
+ if product_channel_listing.discounted_price != product_discounted_price:
+ product_channel_listing.discounted_price_amount = (
+ product_discounted_price.amount
+ )
+ changed_products_channels_to_update.append(product_channel_listing)
+ ProductChannelListing.objects.bulk_update(
+ changed_products_channels_to_update, ["discounted_price_amount"]
)
-def update_products_minimal_variant_prices_of_catalogues(
+def update_products_discounted_prices(products, discounts=None):
+ if discounts is None:
+ discounts = fetch_active_discounts()
+
+ for product in products.prefetch_related("channel_listings"):
+ update_product_discounted_price(product, discounts)
+
+
+def update_products_discounted_prices_of_catalogues(
product_ids=None, category_ids=None, collection_ids=None
):
# Building the matching products query
@@ -67,11 +87,11 @@ def update_products_minimal_variant_prices_of_catalogues(
q_or = reduce(operator.or_, q_list)
products = Product.objects.filter(q_or).distinct()
- update_products_minimal_variant_prices(products)
+ update_products_discounted_prices(products)
-def update_products_minimal_variant_prices_of_discount(discount):
- update_products_minimal_variant_prices_of_catalogues(
+def update_products_discounted_prices_of_discount(discount):
+ update_products_discounted_prices_of_catalogues(
product_ids=discount.products.all().values_list("id", flat=True),
category_ids=discount.categories.all().values_list("id", flat=True),
collection_ids=discount.collections.all().values_list("id", flat=True),
diff --git a/saleor/settings.py b/saleor/settings.py
index 9f5f445645..f46a391f16 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -234,6 +234,7 @@ INSTALLED_APPS = [
"saleor.discount",
"saleor.giftcard",
"saleor.product",
+ "saleor.channel",
"saleor.checkout",
"saleor.core",
"saleor.csv",
@@ -245,7 +246,6 @@ INSTALLED_APPS = [
"saleor.shipping",
"saleor.search",
"saleor.site",
- "saleor.data_feeds",
"saleor.page",
"saleor.payment",
"saleor.warehouse",
@@ -364,9 +364,6 @@ DEFAULT_CURRENCY_CODE_LENGTH = 3
# Following the recommendation of https://tools.ietf.org/html/rfc5322#section-2.1.1
DEFAULT_MAX_EMAIL_DISPLAY_NAME_LENGTH = 78
-# note: having multiple currencies is not supported yet
-AVAILABLE_CURRENCIES = [DEFAULT_CURRENCY]
-
COUNTRIES_OVERRIDE = {"EU": "European Union"}
OPENEXCHANGERATES_API_KEY = os.environ.get("OPENEXCHANGERATES_API_KEY")
@@ -489,6 +486,10 @@ OPENTRACING_MAX_QUERY_LENGTH_LOG = 2000
# Slugs for menus precreated in Django migrations
DEFAULT_MENUS = {"top_menu_name": "navbar", "bottom_menu_name": "footer"}
+# Slug for channel precreated in Django migrations
+DEFAULT_CHANNEL_SLUG = os.environ.get("DEFAULT_CHANNEL_SLUG", "default-channel")
+
+
# Sentry
SENTRY_DSN = os.environ.get("SENTRY_DSN")
if SENTRY_DSN:
diff --git a/saleor/shipping/migrations/0017_django_price_2.py b/saleor/shipping/migrations/0017_django_price_2.py
index dc92ff1abc..6baa8b4bd4 100644
--- a/saleor/shipping/migrations/0017_django_price_2.py
+++ b/saleor/shipping/migrations/0017_django_price_2.py
@@ -1,5 +1,7 @@
# Generated by Django 2.2.4 on 2019-08-14 09:13
+import os
+
from django.conf import settings
from django.db import migrations, models
@@ -26,7 +28,7 @@ class Migration(migrations.Migration):
model_name="shippingmethod",
name="currency",
field=models.CharField(
- default=settings.DEFAULT_CURRENCY,
+ default=os.environ.get("DEFAULT_CURRENCY", "USD"),
max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH,
),
),
diff --git a/saleor/shipping/migrations/0022_shipping_method_channel_listing.py b/saleor/shipping/migrations/0022_shipping_method_channel_listing.py
new file mode 100644
index 0000000000..347753ff83
--- /dev/null
+++ b/saleor/shipping/migrations/0022_shipping_method_channel_listing.py
@@ -0,0 +1,113 @@
+# Generated by Django 3.1 on 2020-08-24 10:09
+
+import django.db.models.deletion
+from django.db import migrations, models
+from django.utils.text import slugify
+
+
+def create_shipping_method_channel_listing(apps, schema_editor):
+ ShippingMethod = apps.get_model("shipping", "ShippingMethod")
+ ShippingMethodChannelListing = apps.get_model(
+ "shipping", "ShippingMethodChannelListing"
+ )
+ Channel = apps.get_model("channel", "Channel")
+
+ channels_dict = {}
+
+ for shipping_method in ShippingMethod.objects.iterator():
+ currency = shipping_method.currency
+ name = f"Channel {currency}"
+ channel = channels_dict.get(currency)
+ if not channel:
+ channel, _ = Channel.objects.get_or_create(
+ currency_code=currency, defaults={"name": name, "slug": slugify(name)},
+ )
+ channels_dict[currency] = channel
+ if shipping_method.type == "price":
+ max_value = shipping_method.maximum_order_price_amount
+ min_value = shipping_method.minimum_order_price_amount
+ else:
+ max_value, min_value = None, None
+ ShippingMethodChannelListing.objects.create(
+ channel=channel,
+ shipping_method=shipping_method,
+ maximum_order_price_amount=max_value,
+ minimum_order_price_amount=min_value,
+ price_amount=shipping_method.price_amount,
+ currency=currency,
+ )
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("channel", "0001_initial"),
+ ("shipping", "0021_auto_20201021_2158"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="ShippingMethodChannelListing",
+ fields=[
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ (
+ "minimum_order_price_amount",
+ models.DecimalField(
+ blank=True,
+ decimal_places=3,
+ default=0,
+ max_digits=12,
+ null=True,
+ ),
+ ),
+ ("currency", models.CharField(max_length=3)),
+ (
+ "maximum_order_price_amount",
+ models.DecimalField(
+ blank=True, decimal_places=3, max_digits=12, null=True
+ ),
+ ),
+ (
+ "price_amount",
+ models.DecimalField(decimal_places=3, default=0, max_digits=12),
+ ),
+ (
+ "channel",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="shipping_method_listings",
+ to="channel.channel",
+ ),
+ ),
+ (
+ "shipping_method",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="channel_listings",
+ to="shipping.shippingmethod",
+ ),
+ ),
+ ],
+ options={
+ "ordering": ("pk",),
+ "unique_together": {("shipping_method", "channel")},
+ },
+ ),
+ migrations.RunPython(create_shipping_method_channel_listing),
+ migrations.RemoveField(
+ model_name="shippingmethod", name="maximum_order_price_amount",
+ ),
+ migrations.RemoveField(
+ model_name="shippingmethod", name="minimum_order_price_amount",
+ ),
+ migrations.RemoveField(model_name="shippingmethod", name="price_amount",),
+ migrations.RemoveField(model_name="shippingmethod", name="currency",),
+ ]
diff --git a/saleor/shipping/models.py b/saleor/shipping/models.py
index 180197c098..1048484c35 100644
--- a/saleor/shipping/models.py
+++ b/saleor/shipping/models.py
@@ -2,13 +2,14 @@ from typing import TYPE_CHECKING, Union
from django.conf import settings
from django.db import models
-from django.db.models import Q
+from django.db.models import OuterRef, Q, Subquery
from django_countries.fields import CountryField
from django_measurement.models import MeasurementField
from django_prices.models import MoneyField
from measurement.measures import Weight
-from prices import Money, MoneyRange
+from prices import Money
+from ..channel.models import Channel
from ..core.models import ModelWithMetadata
from ..core.permissions import ShippingPermissions
from ..core.utils.translations import TranslationProxy
@@ -37,11 +38,17 @@ def _applicable_weight_based_methods(weight, qs):
def _applicable_price_based_methods(price: Money, qs):
"""Return price based shipping methods that are applicable for the given total."""
- qs = qs.price_based()
+ qs_shipping_method = qs.price_based()
+
+ price_based = Q(shipping_method_id__in=qs_shipping_method)
min_price_matched = Q(minimum_order_price_amount__lte=price.amount)
no_price_limit = Q(maximum_order_price_amount__isnull=True)
max_price_matched = Q(maximum_order_price_amount__gte=price.amount)
- return qs.filter(min_price_matched & (no_price_limit | max_price_matched))
+
+ applicable_price_based_methods = ShippingMethodChannelListing.objects.filter(
+ price_based & min_price_matched & (no_price_limit | max_price_matched)
+ ).values_list("shipping_method__id", flat=True)
+ return qs_shipping_method.filter(id__in=applicable_price_based_methods)
def _get_weight_type_display(min_weight, max_weight):
@@ -68,16 +75,6 @@ class ShippingZone(ModelWithMetadata):
def __str__(self):
return self.name
- @property
- def price_range(self):
- prices = [
- shipping_method.get_total()
- for shipping_method in self.shipping_methods.all()
- ]
- if prices:
- return MoneyRange(min(prices), max(prices))
- return None
-
class Meta:
permissions = (
(ShippingPermissions.MANAGE_SHIPPING.codename, "Manage shipping."),
@@ -91,22 +88,40 @@ class ShippingMethodQueryset(models.QuerySet):
def weight_based(self):
return self.filter(type=ShippingMethodType.WEIGHT_BASED)
- def applicable_shipping_methods(self, price: Money, weight, country_code):
+ def applicable_shipping_methods_by_channel(self, shipping_methods, channel_id):
+ query = ShippingMethodChannelListing.objects.filter(
+ shipping_method=OuterRef("pk"), channel_id=channel_id
+ ).values_list("price_amount")
+ return shipping_methods.annotate(price_amount=Subquery(query)).order_by(
+ "price_amount"
+ )
+
+ def applicable_shipping_methods(
+ self, price: Money, channel_id, weight, country_code
+ ):
"""Return the ShippingMethods that can be used on an order with shipment.
It is based on the given country code, and by shipping methods that are
applicable to the given price & weight total.
"""
qs = self.filter(
- shipping_zone__countries__contains=country_code, currency=price.currency,
+ shipping_zone__countries__contains=country_code,
+ channel_listings__currency=price.currency,
)
- qs = qs.prefetch_related("shipping_zone").order_by("price_amount")
+ qs = self.applicable_shipping_methods_by_channel(qs, channel_id)
+ qs = qs.prefetch_related("shipping_zone")
price_based_methods = _applicable_price_based_methods(price, qs)
weight_based_methods = _applicable_weight_based_methods(weight, qs)
- return price_based_methods | weight_based_methods
+ shipping_methods = price_based_methods | weight_based_methods
+
+ return shipping_methods
def applicable_shipping_methods_for_instance(
- self, instance: Union["Checkout", "Order"], price: Money, country_code=None
+ self,
+ instance: Union["Checkout", "Order"],
+ channel_id,
+ price: Money,
+ country_code=None,
):
if not instance.is_shipping_required():
return None
@@ -115,6 +130,7 @@ class ShippingMethodQueryset(models.QuerySet):
return self.applicable_shipping_methods(
price=price,
+ channel_id=channel_id,
weight=instance.get_total_weight(),
country_code=country_code or instance.shipping_address.country.code,
)
@@ -123,41 +139,9 @@ class ShippingMethodQueryset(models.QuerySet):
class ShippingMethod(ModelWithMetadata):
name = models.CharField(max_length=100)
type = models.CharField(max_length=30, choices=ShippingMethodType.CHOICES)
- currency = models.CharField(
- max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH,
- default=settings.DEFAULT_CURRENCY,
- )
- price_amount = models.DecimalField(
- max_digits=settings.DEFAULT_MAX_DIGITS,
- decimal_places=settings.DEFAULT_DECIMAL_PLACES,
- default=0,
- )
- price = MoneyField(amount_field="price_amount", currency_field="currency")
shipping_zone = models.ForeignKey(
ShippingZone, related_name="shipping_methods", on_delete=models.CASCADE
)
-
- minimum_order_price_amount = models.DecimalField(
- max_digits=settings.DEFAULT_MAX_DIGITS,
- decimal_places=settings.DEFAULT_DECIMAL_PLACES,
- default=0,
- blank=True,
- null=True,
- )
- minimum_order_price = MoneyField(
- amount_field="minimum_order_price_amount", currency_field="currency"
- )
-
- maximum_order_price_amount = models.DecimalField(
- max_digits=settings.DEFAULT_MAX_DIGITS,
- decimal_places=settings.DEFAULT_DECIMAL_PLACES,
- blank=True,
- null=True,
- )
- maximum_order_price = MoneyField(
- amount_field="maximum_order_price_amount", currency_field="currency"
- )
-
minimum_order_weight = MeasurementField(
measurement=Weight,
unit_choices=WeightUnits.CHOICES,
@@ -180,21 +164,7 @@ class ShippingMethod(ModelWithMetadata):
def __repr__(self):
if self.type == ShippingMethodType.PRICE_BASED:
- minimum = "%s%s" % (
- self.minimum_order_price.amount,
- self.minimum_order_price.currency,
- )
- max_price = self.maximum_order_price
- maximum = (
- "%s%s" % (max_price.amount, max_price.currency)
- if max_price
- else "no limit"
- )
- return "ShippingMethod(type=%s min=%s, max=%s)" % (
- self.type,
- minimum,
- maximum,
- )
+ return "ShippingMethod(type=%s)" % (self.type,)
return "ShippingMethod(type=%s weight_range=(%s)" % (
self.type,
_get_weight_type_display(
@@ -202,9 +172,56 @@ class ShippingMethod(ModelWithMetadata):
),
)
+
+class ShippingMethodChannelListing(models.Model):
+ shipping_method = models.ForeignKey(
+ ShippingMethod,
+ null=False,
+ blank=False,
+ related_name="channel_listings",
+ on_delete=models.CASCADE,
+ )
+ channel = models.ForeignKey(
+ Channel,
+ null=False,
+ blank=False,
+ related_name="shipping_method_listings",
+ on_delete=models.CASCADE,
+ )
+ minimum_order_price_amount = models.DecimalField(
+ max_digits=settings.DEFAULT_MAX_DIGITS,
+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,
+ default=0,
+ blank=True,
+ null=True,
+ )
+ minimum_order_price = MoneyField(
+ amount_field="minimum_order_price_amount", currency_field="currency"
+ )
+ currency = models.CharField(max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH,)
+ maximum_order_price_amount = models.DecimalField(
+ max_digits=settings.DEFAULT_MAX_DIGITS,
+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,
+ blank=True,
+ null=True,
+ )
+ maximum_order_price = MoneyField(
+ amount_field="maximum_order_price_amount", currency_field="currency"
+ )
+ price = MoneyField(amount_field="price_amount", currency_field="currency")
+ price_amount = models.DecimalField(
+ max_digits=settings.DEFAULT_MAX_DIGITS,
+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,
+ default=0,
+ )
+
def get_total(self):
return self.price
+ class Meta:
+ unique_together = [["shipping_method", "channel"]]
+ ordering = ("pk",)
+
class ShippingMethodTranslation(models.Model):
language_code = models.CharField(max_length=10)
diff --git a/saleor/shipping/tests/test_shipping.py b/saleor/shipping/tests/test_shipping.py
index 2b785b2800..ecda0211e1 100644
--- a/saleor/shipping/tests/test_shipping.py
+++ b/saleor/shipping/tests/test_shipping.py
@@ -3,17 +3,15 @@ from django_countries import countries
from measurement.measures import Weight
from prices import Money
-from ..models import ShippingMethod, ShippingMethodType, ShippingZone
+from ..models import (
+ ShippingMethod,
+ ShippingMethodChannelListing,
+ ShippingMethodType,
+ ShippingZone,
+)
from ..utils import default_shipping_zone_exists, get_countries_without_shipping_zone
-def test_shipping_get_total(monkeypatch, shipping_zone):
- method = shipping_zone.shipping_methods.get()
- price = Money("10.0", "USD")
-
- assert method.get_total() == price
-
-
@pytest.mark.parametrize(
"price, min_price, max_price, shipping_included",
(
@@ -26,17 +24,22 @@ def test_shipping_get_total(monkeypatch, shipping_zone):
),
) # regular case
def test_applicable_shipping_methods_price(
- shipping_zone, price, min_price, max_price, shipping_included
+ shipping_zone, price, min_price, max_price, shipping_included, channel_USD
):
- method = shipping_zone.shipping_methods.create(
+ method = shipping_zone.shipping_methods.create(type=ShippingMethodType.PRICE_BASED,)
+ ShippingMethodChannelListing.objects.create(
+ currency=channel_USD.currency_code,
minimum_order_price_amount=min_price,
maximum_order_price_amount=max_price,
- currency="USD",
- type=ShippingMethodType.PRICE_BASED,
+ shipping_method=method,
+ channel=channel_USD,
)
assert "PL" in shipping_zone.countries
result = ShippingMethod.objects.applicable_shipping_methods(
- price=Money(price, "USD"), weight=Weight(kg=0), country_code="PL"
+ price=Money(price, "USD"),
+ weight=Weight(kg=0),
+ country_code="PL",
+ channel_id=channel_USD.id,
)
assert (method in result) == shipping_included
@@ -53,61 +56,91 @@ def test_applicable_shipping_methods_price(
),
) # regular case
def test_applicable_shipping_methods_weight(
- weight, min_weight, max_weight, shipping_included, shipping_zone
+ weight, min_weight, max_weight, shipping_included, shipping_zone, channel_USD
):
method = shipping_zone.shipping_methods.create(
minimum_order_weight=min_weight,
maximum_order_weight=max_weight,
type=ShippingMethodType.WEIGHT_BASED,
)
+ ShippingMethodChannelListing.objects.create(
+ shipping_method=method, channel=channel_USD, currency=channel_USD.currency_code
+ )
+
assert "PL" in shipping_zone.countries
result = ShippingMethod.objects.applicable_shipping_methods(
- price=Money("0", "USD"), weight=weight, country_code="PL"
+ price=Money("0", "USD"),
+ weight=weight,
+ country_code="PL",
+ channel_id=channel_USD.id,
)
assert (method in result) == shipping_included
-def test_applicable_shipping_methods_country_code_outside_shipping_zone(shipping_zone):
- method = shipping_zone.shipping_methods.create(
+def test_applicable_shipping_methods_country_code_outside_shipping_zone(
+ shipping_zone, channel_USD
+):
+ method = shipping_zone.shipping_methods.create(type=ShippingMethodType.PRICE_BASED,)
+ ShippingMethodChannelListing.objects.create(
minimum_order_price=Money("1.0", "USD"),
maximum_order_price=Money("10.0", "USD"),
- type=ShippingMethodType.PRICE_BASED,
+ shipping_method=method,
+ channel=channel_USD,
)
+
shipping_zone.countries = ["DE"]
shipping_zone.save()
result = ShippingMethod.objects.applicable_shipping_methods(
- price=Money("5.0", "USD"), weight=Weight(kg=0), country_code="PL"
+ price=Money("5.0", "USD"),
+ weight=Weight(kg=0),
+ country_code="PL",
+ channel_id=channel_USD.id,
)
assert method not in result
-def test_applicable_shipping_methods_inproper_shipping_method_type(shipping_zone):
+def test_applicable_shipping_methods_inproper_shipping_method_type(
+ shipping_zone, channel_USD
+):
"""Case when shipping suits the price requirements of the weight type
shipping method and the other way around.
"""
price_method = shipping_zone.shipping_methods.create(
- minimum_order_price=Money("1.0", "USD"),
- maximum_order_price=Money("10.0", "USD"),
- minimum_order_weight=Weight(kg=100),
- type=ShippingMethodType.WEIGHT_BASED,
+ minimum_order_weight=Weight(kg=100), type=ShippingMethodType.WEIGHT_BASED,
)
weight_method = shipping_zone.shipping_methods.create(
minimum_order_weight=Weight(kg=1),
maximum_order_weight=Weight(kg=10),
- minimum_order_price=Money("1000.0", "USD"),
type=ShippingMethodType.PRICE_BASED,
)
+ ShippingMethodChannelListing.objects.bulk_create(
+ [
+ ShippingMethodChannelListing(
+ minimum_order_price=Money("1.0", "USD"),
+ maximum_order_price=Money("10.0", "USD"),
+ shipping_method=price_method,
+ channel=channel_USD,
+ ),
+ ShippingMethodChannelListing(
+ shipping_method=weight_method,
+ channel=channel_USD,
+ minimum_order_price=Money("1000.0", "USD"),
+ ),
+ ]
+ )
+
result = ShippingMethod.objects.applicable_shipping_methods(
- price=Money("5.0", "USD"), weight=Weight(kg=5), country_code="PL"
+ price=Money("5.0", "USD"),
+ weight=Weight(kg=5),
+ country_code="PL",
+ channel_id=channel_USD.id,
)
assert price_method not in result
assert weight_method not in result
-def test_applicable_shipping_methods(shipping_zone):
+def test_applicable_shipping_methods(shipping_zone, channel_USD):
price_method = shipping_zone.shipping_methods.create(
- minimum_order_price=Money("1.0", "USD"),
- maximum_order_price=Money("10.0", "USD"),
type=ShippingMethodType.PRICE_BASED,
)
weight_method = shipping_zone.shipping_methods.create(
@@ -115,14 +148,57 @@ def test_applicable_shipping_methods(shipping_zone):
maximum_order_weight=Weight(kg=10),
type=ShippingMethodType.WEIGHT_BASED,
)
+ ShippingMethodChannelListing.objects.bulk_create(
+ [
+ ShippingMethodChannelListing(
+ shipping_method=weight_method,
+ channel=channel_USD,
+ currency=channel_USD.currency_code,
+ ),
+ ShippingMethodChannelListing(
+ minimum_order_price=Money("1.0", "USD"),
+ maximum_order_price=Money("10.0", "USD"),
+ shipping_method=price_method,
+ channel=channel_USD,
+ currency=channel_USD.currency_code,
+ ),
+ ]
+ )
result = ShippingMethod.objects.applicable_shipping_methods(
- price=Money("5.0", "USD"), weight=Weight(kg=5), country_code="PL"
+ price=Money("5.0", "USD"),
+ weight=Weight(kg=5),
+ country_code="PL",
+ channel_id=channel_USD.id,
)
assert price_method in result
assert weight_method in result
-def test_use_default_shipping_zone(shipping_zone):
+def test_applicable_shipping_methods_not_in_channel(shipping_zone, channel_USD):
+ price_method = shipping_zone.shipping_methods.create(
+ type=ShippingMethodType.PRICE_BASED,
+ )
+ weight_method = shipping_zone.shipping_methods.create(
+ minimum_order_weight=Weight(kg=1),
+ maximum_order_weight=Weight(kg=10),
+ type=ShippingMethodType.WEIGHT_BASED,
+ )
+ ShippingMethodChannelListing.objects.create(
+ shipping_method=weight_method,
+ channel=channel_USD,
+ currency=channel_USD.currency_code,
+ ),
+ result = ShippingMethod.objects.applicable_shipping_methods(
+ price=Money("5.0", "USD"),
+ weight=Weight(kg=5),
+ country_code="PL",
+ channel_id=channel_USD.id,
+ )
+ assert price_method not in result
+ assert weight_method in result
+
+
+def test_use_default_shipping_zone(shipping_zone, channel_USD):
shipping_zone.countries = ["PL"]
shipping_zone.save()
@@ -135,8 +211,17 @@ def test_use_default_shipping_zone(shipping_zone):
maximum_order_weight=Weight(kg=10),
type=ShippingMethodType.WEIGHT_BASED,
)
+
+ ShippingMethodChannelListing.objects.create(
+ shipping_method=weight_method,
+ channel=channel_USD,
+ currency=channel_USD.currency_code,
+ )
result = ShippingMethod.objects.applicable_shipping_methods(
- price=Money("5.0", "USD"), weight=Weight(kg=5), country_code="DE"
+ price=Money("5.0", "USD"),
+ weight=Weight(kg=5),
+ country_code="DE",
+ channel_id=channel_USD.id,
)
assert result[0] == weight_method
diff --git a/saleor/site/migrations/0026_remove_sitesettings_homepage_collection.py b/saleor/site/migrations/0026_remove_sitesettings_homepage_collection.py
new file mode 100644
index 0000000000..7fd9f48bfc
--- /dev/null
+++ b/saleor/site/migrations/0026_remove_sitesettings_homepage_collection.py
@@ -0,0 +1,14 @@
+# Generated by Django 3.1 on 2020-10-14 10:07
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("site", "0025_auto_20191024_0552"),
+ ]
+
+ operations = [
+ migrations.RemoveField(model_name="sitesettings", name="homepage_collection",),
+ ]
diff --git a/saleor/site/models.py b/saleor/site/models.py
index 0dd9a7d720..82a50dc354 100644
--- a/saleor/site/models.py
+++ b/saleor/site/models.py
@@ -44,13 +44,6 @@ class SiteSettings(models.Model):
display_gross_prices = models.BooleanField(default=True)
charge_taxes_on_shipping = models.BooleanField(default=True)
track_inventory_by_default = models.BooleanField(default=True)
- homepage_collection = models.ForeignKey(
- "product.Collection",
- on_delete=models.SET_NULL,
- related_name="+",
- blank=True,
- null=True,
- )
default_weight_unit = models.CharField(
max_length=10, choices=WeightUnits.CHOICES, default=WeightUnits.KILOGRAM
)
diff --git a/saleor/static/populatedb_data.json b/saleor/static/populatedb_data.json
index ef2caa0680..05fff34777 100644
--- a/saleor/static/populatedb_data.json
+++ b/saleor/static/populatedb_data.json
@@ -432,8 +432,6 @@
"model": "product.product",
"pk": 61,
"fields": {
- "publication_date": "2020-01-01",
- "is_published": true,
"private_metadata": {},
"metadata": {
"taxes": {
@@ -458,21 +456,15 @@
}]
},
"category": 20,
- "currency": "USD",
- "minimal_variant_price_amount": "7.500",
- "updated_at": "2020-11-09T07:58:16.994Z",
+ "updated_at": "2020-08-31T06:53:16.102Z",
"charge_taxes": true,
- "weight": "0.0:kg",
- "available_for_purchase": "2020-10-08",
- "visible_in_listings": true
+ "weight": "0.0:kg"
}
},
{
"model": "product.product",
"pk": 62,
"fields": {
- "publication_date": "2020-01-01",
- "is_published": true,
"private_metadata": {},
"metadata": {
"vatlayer.code": "standard",
@@ -493,21 +485,15 @@
}]
},
"category": 20,
- "currency": "USD",
- "minimal_variant_price_amount": "15.000",
- "updated_at": "2020-11-09T07:58:17.191Z",
+ "updated_at": "2020-08-31T06:53:16.307Z",
"charge_taxes": true,
- "weight": "1.0:kg",
- "available_for_purchase": "2021-02-26",
- "visible_in_listings": true
+ "weight": "1.0:kg"
}
},
{
"model": "product.product",
"pk": 63,
"fields": {
- "publication_date": "2020-01-01",
- "is_published": true,
"private_metadata": {},
"metadata": {
"vatlayer.code": "standard",
@@ -528,21 +514,15 @@
}]
},
"category": 20,
- "currency": "USD",
- "minimal_variant_price_amount": "7.500",
- "updated_at": "2020-11-09T07:58:17.392Z",
+ "updated_at": "2020-08-31T06:53:29.317Z",
"charge_taxes": true,
- "weight": "0.0:kg",
- "available_for_purchase": "2021-08-06",
- "visible_in_listings": true
+ "weight": "0.0:kg"
}
},
{
"model": "product.product",
"pk": 64,
"fields": {
- "publication_date": "2020-01-01",
- "is_published": true,
"private_metadata": {},
"metadata": {
"vatlayer.code": "standard",
@@ -563,21 +543,15 @@
}]
},
"category": 20,
- "currency": "USD",
- "minimal_variant_price_amount": "10.500",
- "updated_at": "2020-11-09T07:58:17.598Z",
+ "updated_at": "2020-08-31T06:53:29.548Z",
"charge_taxes": true,
- "weight": "0.0:kg",
- "available_for_purchase": "2021-01-26",
- "visible_in_listings": true
+ "weight": "0.0:kg"
}
},
{
"model": "product.product",
"pk": 65,
"fields": {
- "publication_date": "2020-01-01",
- "is_published": true,
"private_metadata": {},
"metadata": {
"vatlayer.code": "standard",
@@ -598,21 +572,15 @@
}]
},
"category": 20,
- "currency": "USD",
- "minimal_variant_price_amount": "15.000",
- "updated_at": "2020-11-09T07:58:17.796Z",
+ "updated_at": "2020-08-31T06:53:29.787Z",
"charge_taxes": true,
- "weight": "1.0:kg",
- "available_for_purchase": "2021-01-26",
- "visible_in_listings": true
+ "weight": "1.0:kg"
}
},
{
"model": "product.product",
"pk": 71,
"fields": {
- "publication_date": "2020-01-01",
- "is_published": true,
"private_metadata": {},
"metadata": {
"vatlayer.code": "standard",
@@ -633,21 +601,15 @@
}]
},
"category": 14,
- "currency": "USD",
- "minimal_variant_price_amount": "2.500",
- "updated_at": "2020-11-09T07:58:18.002Z",
+ "updated_at": "2020-08-31T06:53:17.155Z",
"charge_taxes": true,
- "weight": "1.0:kg",
- "available_for_purchase": "2020-08-31",
- "visible_in_listings": true
+ "weight": "1.0:kg"
}
},
{
"model": "product.product",
"pk": 72,
"fields": {
- "publication_date": "2020-01-01",
- "is_published": true,
"private_metadata": {},
"metadata": {
"vatlayer.code": "standard",
@@ -668,21 +630,15 @@
}]
},
"category": 14,
- "currency": "USD",
- "minimal_variant_price_amount": "5.000",
- "updated_at": "2020-11-09T07:58:18.770Z",
+ "updated_at": "2020-08-31T06:53:17.312Z",
"charge_taxes": true,
- "weight": "1.0:kg",
- "available_for_purchase": "2020-08-31",
- "visible_in_listings": true
+ "weight": "1.0:kg"
}
},
{
"model": "product.product",
"pk": 73,
"fields": {
- "publication_date": "2020-01-01",
- "is_published": true,
"private_metadata": {},
"metadata": {
"vatlayer.code": "standard",
@@ -703,21 +659,15 @@
}]
},
"category": 14,
- "currency": "USD",
- "minimal_variant_price_amount": "4.000",
- "updated_at": "2020-11-09T07:58:18.987Z",
+ "updated_at": "2020-08-31T06:53:17.473Z",
"charge_taxes": true,
- "weight": "1.0:kg",
- "available_for_purchase": "2020-08-31",
- "visible_in_listings": true
+ "weight": "1.0:kg"
}
},
{
"model": "product.product",
"pk": 74,
"fields": {
- "publication_date": "2020-01-01",
- "is_published": true,
"private_metadata": {},
"metadata": {
"vatlayer.code": "standard",
@@ -738,21 +688,15 @@
}]
},
"category": 14,
- "currency": "USD",
- "minimal_variant_price_amount": "5.000",
- "updated_at": "2020-11-09T07:58:19.186Z",
+ "updated_at": "2020-08-31T06:53:17.630Z",
"charge_taxes": true,
- "weight": "1.0:kg",
- "available_for_purchase": "2020-08-31",
- "visible_in_listings": true
+ "weight": "1.0:kg"
}
},
{
"model": "product.product",
"pk": 75,
"fields": {
- "publication_date": "2020-01-01",
- "is_published": true,
"private_metadata": {},
"metadata": {
"vatlayer.code": "standard",
@@ -773,21 +717,15 @@
}]
},
"category": 14,
- "currency": "USD",
- "minimal_variant_price_amount": "2.500",
- "updated_at": "2020-11-09T07:58:19.390Z",
+ "updated_at": "2020-08-31T06:53:17.782Z",
"charge_taxes": true,
- "weight": "1.0:kg",
- "available_for_purchase": "2020-08-31",
- "visible_in_listings": true
+ "weight": "1.0:kg"
}
},
{
"model": "product.product",
"pk": 76,
"fields": {
- "publication_date": "2020-01-01",
- "is_published": true,
"private_metadata": {},
"metadata": {
"vatlayer.code": "standard",
@@ -808,21 +746,15 @@
}]
},
"category": 14,
- "currency": "USD",
- "minimal_variant_price_amount": "5.000",
- "updated_at": "2020-11-09T07:58:19.588Z",
+ "updated_at": "2020-08-31T06:53:31.827Z",
"charge_taxes": true,
- "weight": "1.0:kg",
- "available_for_purchase": "2020-08-31",
- "visible_in_listings": true
+ "weight": "1.0:kg"
}
},
{
"model": "product.product",
"pk": 77,
"fields": {
- "publication_date": "2020-01-01",
- "is_published": true,
"private_metadata": {},
"metadata": {
"vatlayer.code": "standard",
@@ -843,21 +775,15 @@
}]
},
"category": 14,
- "currency": "USD",
- "minimal_variant_price_amount": "5.000",
- "updated_at": "2020-11-09T07:58:19.790Z",
+ "updated_at": "2020-08-31T06:53:18.105Z",
"charge_taxes": true,
- "weight": "1.0:kg",
- "available_for_purchase": "2020-08-31",
- "visible_in_listings": true
+ "weight": "1.0:kg"
}
},
{
"model": "product.product",
"pk": 78,
"fields": {
- "publication_date": "2020-01-01",
- "is_published": true,
"private_metadata": {},
"metadata": {
"vatlayer.code": "standard",
@@ -878,21 +804,15 @@
}]
},
"category": 14,
- "currency": "USD",
- "minimal_variant_price_amount": "5.000",
- "updated_at": "2020-11-09T07:58:19.995Z",
+ "updated_at": "2020-08-31T06:53:32.287Z",
"charge_taxes": true,
- "weight": "1.0:kg",
- "available_for_purchase": "2020-08-31",
- "visible_in_listings": true
+ "weight": "1.0:kg"
}
},
{
"model": "product.product",
"pk": 79,
"fields": {
- "publication_date": "2020-01-01",
- "is_published": true,
"private_metadata": {},
"metadata": {
"vatlayer.code": "standard",
@@ -913,21 +833,15 @@
}]
},
"category": 14,
- "currency": "USD",
- "minimal_variant_price_amount": "2.500",
- "updated_at": "2020-11-09T07:58:20.222Z",
+ "updated_at": "2020-08-31T06:53:18.411Z",
"charge_taxes": true,
- "weight": "1.0:kg",
- "available_for_purchase": "2020-08-31",
- "visible_in_listings": true
+ "weight": "1.0:kg"
}
},
{
"model": "product.product",
"pk": 81,
"fields": {
- "publication_date": "2020-01-01",
- "is_published": true,
"private_metadata": {},
"metadata": {
"vatlayer.code": "standard",
@@ -948,21 +862,15 @@
}]
},
"category": 15,
- "currency": "USD",
- "minimal_variant_price_amount": "5.000",
- "updated_at": "2020-11-09T07:58:18.179Z",
+ "updated_at": "2020-08-31T06:53:18.558Z",
"charge_taxes": true,
- "weight": "0.0:kg",
- "available_for_purchase": "2020-08-31",
- "visible_in_listings": true
+ "weight": "0.0:kg"
}
},
{
"model": "product.product",
"pk": 82,
"fields": {
- "publication_date": "2020-01-01",
- "is_published": true,
"private_metadata": {},
"metadata": {
"vatlayer.code": "standard",
@@ -983,21 +891,15 @@
}]
},
"category": 15,
- "currency": "USD",
- "minimal_variant_price_amount": "3.500",
- "updated_at": "2020-11-09T07:58:18.236Z",
+ "updated_at": "2020-08-31T06:53:30.364Z",
"charge_taxes": true,
- "weight": "0.0:kg",
- "available_for_purchase": "2020-08-31",
- "visible_in_listings": true
+ "weight": "0.0:kg"
}
},
{
"model": "product.product",
"pk": 83,
"fields": {
- "publication_date": "2020-01-01",
- "is_published": true,
"private_metadata": {},
"metadata": {
"vatlayer.code": "standard",
@@ -1018,21 +920,15 @@
}]
},
"category": 15,
- "currency": "USD",
- "minimal_variant_price_amount": "2.500",
- "updated_at": "2020-11-09T07:58:18.301Z",
+ "updated_at": "2020-08-31T06:53:18.900Z",
"charge_taxes": true,
- "weight": "1.0:kg",
- "available_for_purchase": "2020-08-31",
- "visible_in_listings": true
+ "weight": "1.0:kg"
}
},
{
"model": "product.product",
"pk": 84,
"fields": {
- "publication_date": "2020-01-01",
- "is_published": true,
"private_metadata": {},
"metadata": {
"vatlayer.code": "standard",
@@ -1053,21 +949,15 @@
}]
},
"category": 15,
- "currency": "USD",
- "minimal_variant_price_amount": "5.000",
- "updated_at": "2020-11-09T07:58:18.367Z",
+ "updated_at": "2020-08-31T06:53:30.527Z",
"charge_taxes": true,
- "weight": "1.0:kg",
- "available_for_purchase": "2020-08-31",
- "visible_in_listings": true
+ "weight": "1.0:kg"
}
},
{
"model": "product.product",
"pk": 85,
"fields": {
- "publication_date": "2020-01-01",
- "is_published": true,
"private_metadata": {},
"metadata": {
"vatlayer.code": "standard",
@@ -1088,21 +978,15 @@
}]
},
"category": 22,
- "currency": "USD",
- "minimal_variant_price_amount": "5.000",
- "updated_at": "2020-11-09T07:58:18.509Z",
+ "updated_at": "2020-08-31T06:53:30.677Z",
"charge_taxes": true,
- "weight": "0.0:kg",
- "available_for_purchase": "2020-08-31",
- "visible_in_listings": true
+ "weight": "0.0:kg"
}
},
{
"model": "product.product",
"pk": 86,
"fields": {
- "publication_date": "2020-01-01",
- "is_published": true,
"private_metadata": {},
"metadata": {
"vatlayer.code": "standard",
@@ -1123,21 +1007,15 @@
}]
},
"category": 22,
- "currency": "USD",
- "minimal_variant_price_amount": "3.500",
- "updated_at": "2020-11-09T07:58:18.619Z",
+ "updated_at": "2020-08-31T06:53:20.430Z",
"charge_taxes": true,
- "weight": "0.0:kg",
- "available_for_purchase": "2020-08-31",
- "visible_in_listings": true
+ "weight": "0.0:kg"
}
},
{
"model": "product.product",
"pk": 87,
"fields": {
- "publication_date": "2020-01-01",
- "is_published": true,
"private_metadata": {},
"metadata": {
"vatlayer.code": "standard",
@@ -1158,21 +1036,15 @@
}]
},
"category": 13,
- "currency": "USD",
- "minimal_variant_price_amount": "2.500",
- "updated_at": "2020-11-09T07:58:20.422Z",
+ "updated_at": "2020-08-31T06:53:32.761Z",
"charge_taxes": true,
- "weight": "0.0:kg",
- "available_for_purchase": "2020-08-31",
- "visible_in_listings": true
+ "weight": "0.0:kg"
}
},
{
"model": "product.product",
"pk": 88,
"fields": {
- "publication_date": "2020-01-01",
- "is_published": true,
"private_metadata": {},
"metadata": {
"vatlayer.code": "standard",
@@ -1193,21 +1065,15 @@
}]
},
"category": 13,
- "currency": "USD",
- "minimal_variant_price_amount": "5.000",
- "updated_at": "2020-11-09T07:58:20.737Z",
+ "updated_at": "2020-08-31T06:53:33.172Z",
"charge_taxes": true,
- "weight": "1.0:kg",
- "available_for_purchase": "2020-08-31",
- "visible_in_listings": true
+ "weight": "1.0:kg"
}
},
{
"model": "product.product",
"pk": 89,
"fields": {
- "publication_date": "2020-01-01",
- "is_published": true,
"private_metadata": {},
"metadata": {
"vatlayer.code": "standard",
@@ -1228,21 +1094,15 @@
}]
},
"category": 10,
- "currency": "USD",
- "minimal_variant_price_amount": "5.000",
- "updated_at": "2020-11-09T07:58:21.004Z",
+ "updated_at": "2020-08-31T06:53:33.473Z",
"charge_taxes": true,
- "weight": "0.0:kg",
- "available_for_purchase": "2020-08-31",
- "visible_in_listings": true
+ "weight": "0.0:kg"
}
},
{
"model": "product.product",
"pk": 107,
"fields": {
- "publication_date": "2020-01-01",
- "is_published": true,
"private_metadata": {},
"metadata": {
"vatlayer.code": "standard",
@@ -1263,21 +1123,15 @@
}]
},
"category": 11,
- "currency": "USD",
- "minimal_variant_price_amount": "5.000",
- "updated_at": "2020-11-09T07:58:21.332Z",
+ "updated_at": "2020-08-31T06:53:22.365Z",
"charge_taxes": true,
- "weight": "0.0:kg",
- "available_for_purchase": "2020-08-31",
- "visible_in_listings": true
+ "weight": "0.0:kg"
}
},
{
"model": "product.product",
"pk": 108,
"fields": {
- "publication_date": "2020-01-01",
- "is_published": true,
"private_metadata": {},
"metadata": {
"vatlayer.code": "standard",
@@ -1298,21 +1152,15 @@
}]
},
"category": 11,
- "currency": "USD",
- "minimal_variant_price_amount": "2.500",
- "updated_at": "2020-11-09T07:58:21.657Z",
+ "updated_at": "2020-08-31T06:53:34.274Z",
"charge_taxes": true,
- "weight": "0.0:kg",
- "available_for_purchase": "2020-08-31",
- "visible_in_listings": true
+ "weight": "0.0:kg"
}
},
{
"model": "product.product",
"pk": 109,
"fields": {
- "publication_date": "2020-01-01",
- "is_published": true,
"private_metadata": {},
"metadata": {
"vatlayer.code": "standard",
@@ -1333,21 +1181,15 @@
}]
},
"category": 11,
- "currency": "USD",
- "minimal_variant_price_amount": "3.500",
- "updated_at": "2020-11-09T07:58:21.991Z",
+ "updated_at": "2020-08-31T06:53:22.900Z",
"charge_taxes": true,
- "weight": "0.0:kg",
- "available_for_purchase": "2020-08-31",
- "visible_in_listings": true
+ "weight": "0.0:kg"
}
},
{
"model": "product.product",
"pk": 110,
"fields": {
- "publication_date": "2020-01-01",
- "is_published": true,
"private_metadata": {},
"metadata": {
"vatlayer.code": "standard",
@@ -1368,21 +1210,15 @@
}]
},
"category": 11,
- "currency": "USD",
- "minimal_variant_price_amount": "5.000",
- "updated_at": "2020-11-09T07:58:22.334Z",
+ "updated_at": "2020-08-31T06:53:35.075Z",
"charge_taxes": true,
- "weight": "0.0:kg",
- "available_for_purchase": "2020-08-31",
- "visible_in_listings": true
+ "weight": "0.0:kg"
}
},
{
"model": "product.product",
"pk": 111,
"fields": {
- "publication_date": "2020-01-01",
- "is_published": true,
"private_metadata": {},
"metadata": {
"vatlayer.code": "standard",
@@ -1403,21 +1239,15 @@
}]
},
"category": 10,
- "currency": "USD",
- "minimal_variant_price_amount": "3.500",
- "updated_at": "2020-11-09T07:58:22.720Z",
+ "updated_at": "2020-08-31T06:53:35.478Z",
"charge_taxes": true,
- "weight": "0.0:kg",
- "available_for_purchase": "2020-08-31",
- "visible_in_listings": true
+ "weight": "0.0:kg"
}
},
{
"model": "product.product",
"pk": 112,
"fields": {
- "publication_date": "2020-01-01",
- "is_published": true,
"private_metadata": {},
"metadata": {
"vatlayer.code": "standard",
@@ -1438,21 +1268,15 @@
}]
},
"category": 10,
- "currency": "USD",
- "minimal_variant_price_amount": "5.000",
- "updated_at": "2020-11-09T07:58:23.050Z",
+ "updated_at": "2020-08-31T06:53:24.137Z",
"charge_taxes": true,
- "weight": "0.0:kg",
- "available_for_purchase": "2020-08-31",
- "visible_in_listings": true
+ "weight": "0.0:kg"
}
},
{
"model": "product.product",
"pk": 113,
"fields": {
- "publication_date": "2020-01-01",
- "is_published": true,
"private_metadata": {},
"metadata": {
"vatlayer.code": "standard",
@@ -1473,21 +1297,15 @@
}]
},
"category": 10,
- "currency": "USD",
- "minimal_variant_price_amount": "4.000",
- "updated_at": "2020-11-09T07:58:23.388Z",
+ "updated_at": "2020-08-31T06:53:36.267Z",
"charge_taxes": true,
- "weight": "0.0:kg",
- "available_for_purchase": "2020-08-31",
- "visible_in_listings": true
+ "weight": "0.0:kg"
}
},
{
"model": "product.product",
"pk": 114,
"fields": {
- "publication_date": "2020-01-01",
- "is_published": true,
"private_metadata": {},
"metadata": {
"vatlayer.code": "standard",
@@ -1508,21 +1326,15 @@
}]
},
"category": 10,
- "currency": "USD",
- "minimal_variant_price_amount": "5.000",
- "updated_at": "2020-11-09T07:58:23.756Z",
+ "updated_at": "2020-08-31T06:53:36.707Z",
"charge_taxes": true,
- "weight": "0.0:kg",
- "available_for_purchase": "2020-08-31",
- "visible_in_listings": true
+ "weight": "0.0:kg"
}
},
{
"model": "product.product",
"pk": 115,
"fields": {
- "publication_date": "2020-01-01",
- "is_published": true,
"private_metadata": {},
"metadata": {
"vatlayer.code": "standard",
@@ -1543,21 +1355,15 @@
}]
},
"category": 12,
- "currency": "USD",
- "minimal_variant_price_amount": "5.000",
- "updated_at": "2020-11-09T07:58:24.157Z",
+ "updated_at": "2020-08-31T06:53:25.468Z",
"charge_taxes": true,
- "weight": "0.0:kg",
- "available_for_purchase": "2020-08-31",
- "visible_in_listings": true
+ "weight": "0.0:kg"
}
},
{
"model": "product.product",
"pk": 116,
"fields": {
- "publication_date": "2020-01-01",
- "is_published": true,
"private_metadata": {},
"metadata": {
"vatlayer.code": "standard",
@@ -1578,21 +1384,15 @@
}]
},
"category": 12,
- "currency": "USD",
- "minimal_variant_price_amount": "3.500",
- "updated_at": "2020-11-09T07:58:24.557Z",
+ "updated_at": "2020-08-31T06:53:25.725Z",
"charge_taxes": true,
- "weight": "0.0:kg",
- "available_for_purchase": "2020-08-31",
- "visible_in_listings": true
+ "weight": "0.0:kg"
}
},
{
"model": "product.product",
"pk": 117,
"fields": {
- "publication_date": "2020-01-01",
- "is_published": true,
"private_metadata": {},
"metadata": {
"vatlayer.code": "standard",
@@ -1613,21 +1413,15 @@
}]
},
"category": 12,
- "currency": "USD",
- "minimal_variant_price_amount": "4.000",
- "updated_at": "2020-11-09T07:58:24.891Z",
+ "updated_at": "2020-08-31T06:53:37.920Z",
"charge_taxes": true,
- "weight": "0.0:kg",
- "available_for_purchase": "2020-08-31",
- "visible_in_listings": true
+ "weight": "0.0:kg"
}
},
{
"model": "product.product",
"pk": 118,
"fields": {
- "publication_date": "2020-01-01",
- "is_published": true,
"private_metadata": {},
"metadata": {
"vatlayer.code": "standard",
@@ -1648,21 +1442,15 @@
}]
},
"category": 12,
- "currency": "USD",
- "minimal_variant_price_amount": "5.000",
- "updated_at": "2020-11-09T07:58:25.250Z",
+ "updated_at": "2020-08-31T06:53:26.266Z",
"charge_taxes": true,
- "weight": "0.0:kg",
- "available_for_purchase": "2020-08-31",
- "visible_in_listings": true
+ "weight": "0.0:kg"
}
},
{
"model": "product.product",
"pk": 119,
"fields": {
- "publication_date": "2020-01-01",
- "is_published": true,
"private_metadata": {},
"metadata": {},
"seo_title": "",
@@ -1680,21 +1468,15 @@
}]
},
"category": 23,
- "currency": "USD",
- "minimal_variant_price_amount": "8.000",
- "updated_at": "2020-11-09T07:58:25.605Z",
+ "updated_at": "2020-08-31T06:53:27.068Z",
"charge_taxes": false,
- "weight": "0.0:kg",
- "available_for_purchase": "2020-08-31",
- "visible_in_listings": true
+ "weight": "0.0:kg"
}
},
{
"model": "product.product",
"pk": 120,
"fields": {
- "publication_date": "2020-01-01",
- "is_published": true,
"private_metadata": {},
"metadata": {},
"seo_title": "",
@@ -1712,21 +1494,15 @@
}]
},
"category": 23,
- "currency": "USD",
- "minimal_variant_price_amount": "9.990",
- "updated_at": "2020-11-09T07:58:25.674Z",
+ "updated_at": "2020-08-31T06:53:27.344Z",
"charge_taxes": false,
- "weight": "0.0:kg",
- "available_for_purchase": "2020-08-31",
- "visible_in_listings": true
+ "weight": "0.0:kg"
}
},
{
"model": "product.product",
"pk": 121,
"fields": {
- "publication_date": "2020-01-01",
- "is_published": true,
"private_metadata": {},
"metadata": {},
"seo_title": "",
@@ -1744,21 +1520,15 @@
}]
},
"category": 23,
- "currency": "USD",
- "minimal_variant_price_amount": "9.990",
- "updated_at": "2020-11-09T07:58:25.758Z",
+ "updated_at": "2020-08-31T06:53:27.611Z",
"charge_taxes": false,
- "weight": "0.0:kg",
- "available_for_purchase": "2020-08-31",
- "visible_in_listings": false
+ "weight": "0.0:kg"
}
},
{
"model": "product.product",
"pk": 122,
"fields": {
- "publication_date": "2020-01-01",
- "is_published": true,
"private_metadata": {},
"metadata": {},
"seo_title": "",
@@ -1776,21 +1546,15 @@
}]
},
"category": 23,
- "currency": "USD",
- "minimal_variant_price_amount": "9.990",
- "updated_at": "2020-11-09T07:58:25.839Z",
+ "updated_at": "2020-08-31T06:53:27.873Z",
"charge_taxes": false,
- "weight": "0.0:kg",
- "available_for_purchase": "2020-08-31",
- "visible_in_listings": false
+ "weight": "0.0:kg"
}
},
{
"model": "product.product",
"pk": 123,
"fields": {
- "publication_date": "2020-01-01",
- "is_published": true,
"private_metadata": {},
"metadata": {},
"seo_title": "",
@@ -1808,21 +1572,15 @@
}]
},
"category": 23,
- "currency": "USD",
- "minimal_variant_price_amount": "9.990",
- "updated_at": "2020-11-09T07:58:25.918Z",
+ "updated_at": "2020-08-31T06:53:28.105Z",
"charge_taxes": false,
- "weight": "0.0:kg",
- "available_for_purchase": "2020-08-31",
- "visible_in_listings": false
+ "weight": "0.0:kg"
}
},
{
"model": "product.product",
"pk": 124,
"fields": {
- "publication_date": "2020-01-01",
- "is_published": true,
"private_metadata": {},
"metadata": {},
"seo_title": "",
@@ -1840,2134 +1598,5072 @@
}]
},
"category": 23,
- "currency": "USD",
- "minimal_variant_price_amount": "9.990",
- "updated_at": "2020-11-09T07:58:25.993Z",
+ "updated_at": "2020-08-31T06:53:28.398Z",
"charge_taxes": false,
- "weight": "0.0:kg",
- "available_for_purchase": "2021-08-31",
- "visible_in_listings": false
+ "weight": "0.0:kg"
}
},
{
- "model": "product.productvariant",
- "pk": 171,
+ "model": "product.productchannellisting",
+ "pk": 1,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "546451996",
- "name": "1l",
- "currency": "USD",
- "price_amount": "15.00",
- "product": 61,
- "track_inventory": true,
- "cost_price_amount": "5.00",
- "weight": "1.0:kg",
- "default": true
- }
- },
- {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 72,
+ "channel": 1,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "USD"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 2,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 74,
+ "channel": 1,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "USD"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 3,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 122,
+ "channel": 1,
+ "visible_in_listings": false,
+ "available_for_purchase": "2020-08-31",
+ "currency": "USD"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 4,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 79,
+ "channel": 1,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "USD"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 5,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 115,
+ "channel": 1,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "USD"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 6,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 116,
+ "channel": 1,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "USD"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 7,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 73,
+ "channel": 1,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "USD"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 8,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 76,
+ "channel": 1,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "USD"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 9,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 89,
+ "channel": 1,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "USD"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 10,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 85,
+ "channel": 1,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "USD"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 11,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 78,
+ "channel": 1,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "USD"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 12,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 65,
+ "channel": 1,
+ "visible_in_listings": true,
+ "available_for_purchase": "2021-08-31",
+ "currency": "USD"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 13,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 123,
+ "channel": 1,
+ "visible_in_listings": false,
+ "available_for_purchase": "2020-08-31",
+ "currency": "USD"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 14,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 120,
+ "channel": 1,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "USD"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 15,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 64,
+ "channel": 1,
+ "visible_in_listings": true,
+ "available_for_purchase": "2021-08-31",
+ "currency": "USD"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 16,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 117,
+ "channel": 1,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "USD"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 17,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 61,
+ "channel": 1,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "USD"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 18,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 121,
+ "channel": 1,
+ "visible_in_listings": false,
+ "available_for_purchase": "2020-08-31",
+ "currency": "USD"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 19,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 71,
+ "channel": 1,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "USD"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 20,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 75,
+ "channel": 1,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "USD"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 21,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 107,
+ "channel": 1,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "USD"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 22,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 108,
+ "channel": 1,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "USD"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 23,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 109,
+ "channel": 1,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "USD"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 24,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 110,
+ "channel": 1,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "USD"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 25,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 77,
+ "channel": 1,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "USD"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 26,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 63,
+ "channel": 1,
+ "visible_in_listings": true,
+ "available_for_purchase": "2021-08-31",
+ "currency": "USD"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 27,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 81,
+ "channel": 1,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "USD"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 28,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 119,
+ "channel": 1,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "USD"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 29,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 84,
+ "channel": 1,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "USD"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 30,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 83,
+ "channel": 1,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "USD"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 31,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 62,
+ "channel": 1,
+ "visible_in_listings": true,
+ "available_for_purchase": "2021-08-31",
+ "currency": "USD"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 32,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 112,
+ "channel": 1,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "USD"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 33,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 111,
+ "channel": 1,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "USD"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 34,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 114,
+ "channel": 1,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "USD"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 35,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 113,
+ "channel": 1,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "USD"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 36,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 124,
+ "channel": 1,
+ "visible_in_listings": false,
+ "available_for_purchase": "2021-08-31",
+ "currency": "USD"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 37,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 118,
+ "channel": 1,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "USD"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 38,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 86,
+ "channel": 1,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "USD"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 39,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 88,
+ "channel": 1,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "USD"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 40,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 82,
+ "channel": 1,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "USD"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 41,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 87,
+ "channel": 1,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "USD"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 42,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 72,
+ "channel": 2,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "PLN"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 43,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 74,
+ "channel": 2,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "PLN"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 44,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 122,
+ "channel": 2,
+ "visible_in_listings": false,
+ "available_for_purchase": "2020-08-31",
+ "currency": "PLN"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 45,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 79,
+ "channel": 2,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "PLN"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 46,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 115,
+ "channel": 2,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "PLN"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 47,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 116,
+ "channel": 2,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "PLN"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 48,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 73,
+ "channel": 2,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "PLN"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 49,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 76,
+ "channel": 2,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "PLN"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 50,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 89,
+ "channel": 2,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "PLN"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 51,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 85,
+ "channel": 2,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "PLN"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 52,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 78,
+ "channel": 2,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "PLN"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 53,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 65,
+ "channel": 2,
+ "visible_in_listings": true,
+ "available_for_purchase": "2021-08-31",
+ "currency": "PLN"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 54,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 123,
+ "channel": 2,
+ "visible_in_listings": false,
+ "available_for_purchase": "2020-08-31",
+ "currency": "PLN"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 55,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 120,
+ "channel": 2,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "PLN"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 56,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 64,
+ "channel": 2,
+ "visible_in_listings": true,
+ "available_for_purchase": "2021-08-31",
+ "currency": "PLN"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 57,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 117,
+ "channel": 2,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "PLN"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 58,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 61,
+ "channel": 2,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "PLN"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 59,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 121,
+ "channel": 2,
+ "visible_in_listings": false,
+ "available_for_purchase": "2020-08-31",
+ "currency": "PLN"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 60,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 71,
+ "channel": 2,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "PLN"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 61,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 75,
+ "channel": 2,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "PLN"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 62,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 107,
+ "channel": 2,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "PLN"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 63,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 108,
+ "channel": 2,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "PLN"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 64,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 109,
+ "channel": 2,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "PLN"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 65,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 110,
+ "channel": 2,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "PLN"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 66,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 77,
+ "channel": 2,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "PLN"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 67,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 63,
+ "channel": 2,
+ "visible_in_listings": true,
+ "available_for_purchase": "2021-08-31",
+ "currency": "PLN"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 68,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 81,
+ "channel": 2,
+ "visible_in_listings": false,
+ "available_for_purchase": "2020-08-31",
+ "currency": "PLN"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 69,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "product": 119,
+ "channel": 2,
+ "visible_in_listings": false,
+ "available_for_purchase": "2020-08-31",
+ "currency": "PLN"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 70,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": false,
+ "product": 84,
+ "channel": 2,
+ "visible_in_listings": true,
+ "available_for_purchase": "2020-08-31",
+ "currency": "PLN"
+ }
+ },
+ {
+ "model": "product.productchannellisting",
+ "pk": 71,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": false,
+ "product": 83,
+ "channel": 2,
+ "visible_in_listings": false,
+ "available_for_purchase": "2020-08-31",
+ "currency": "PLN"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 171,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "546451996",
+ "name": "1l",
+ "product": 61,
+ "track_inventory": true,
+ "weight": "1.0:kg",
+ "default": true
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 172,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "546451997",
+ "name": "2.5l",
+ "product": 61,
+ "track_inventory": true,
+ "weight": "2.5:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 173,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "546451999",
+ "name": "5l",
+ "product": 61,
+ "track_inventory": true,
+ "weight": "5.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 174,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "998223591",
+ "name": "1l",
+ "product": 62,
+ "track_inventory": true,
+ "weight": "1.0:kg",
+ "default": true
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 175,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "998223599",
+ "name": "2.5l",
+ "product": 62,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 176,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "998223594",
+ "name": "5l",
+ "product": 62,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 177,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "998223582",
+ "name": "1l",
+ "product": 63,
+ "track_inventory": true,
+ "weight": "1.0:kg",
+ "default": true
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 178,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "998223583",
+ "name": "2.5l",
+ "product": 63,
+ "track_inventory": true,
+ "weight": "2.5:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 179,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "998223584",
+ "name": "5l",
+ "product": 63,
+ "track_inventory": true,
+ "weight": "5.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 180,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "998323582",
+ "name": "1l",
+ "product": 64,
+ "track_inventory": true,
+ "weight": "1.0:kg",
+ "default": true
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 181,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "998323583",
+ "name": "2.5l",
+ "product": 64,
+ "track_inventory": true,
+ "weight": "2.5:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 182,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "998323584",
+ "name": "5l",
+ "product": 64,
+ "track_inventory": true,
+ "weight": "5.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 183,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "998423582",
+ "name": "1l",
+ "product": 65,
+ "track_inventory": true,
+ "weight": "1.0:kg",
+ "default": true
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 184,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "998423583",
+ "name": "2.5l",
+ "product": 65,
+ "track_inventory": true,
+ "weight": "2.5:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 185,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "998423585",
+ "name": "5l",
+ "product": 65,
+ "track_inventory": true,
+ "weight": "5.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 190,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "988323582",
+ "name": "500ml",
+ "product": 71,
+ "track_inventory": true,
+ "weight": "1.0:kg",
+ "default": true
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 191,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "938323582",
+ "name": "1l",
+ "product": 71,
+ "track_inventory": true,
+ "weight": "1.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 192,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "988323522",
+ "name": "2l",
+ "product": 71,
+ "track_inventory": true,
+ "weight": "2.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 193,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "12312312321",
+ "name": "",
+ "product": 81,
+ "track_inventory": true,
+ "weight": "0.0:kg",
+ "default": true
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 194,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "1231998121",
+ "name": "",
+ "product": 82,
+ "track_inventory": true,
+ "weight": "0.0:kg",
+ "default": true
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 195,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "98616712",
+ "name": "",
+ "product": 83,
+ "track_inventory": true,
+ "weight": "0.0:kg",
+ "default": true
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 196,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "98616713",
+ "name": "",
+ "product": 84,
+ "track_inventory": true,
+ "weight": "0.0:kg",
+ "default": true
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 197,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "698223582",
+ "name": "45cm x 45cm",
+ "product": 85,
+ "track_inventory": true,
+ "weight": "0.0:kg",
+ "default": true
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 198,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "698223581",
+ "name": "55cm x 55cm",
+ "product": 85,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 199,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "987126191",
+ "name": "45cm x 45cm",
+ "product": 86,
+ "track_inventory": true,
+ "weight": "0.0:kg",
+ "default": true
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 200,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "998223590",
+ "name": "55cm x 55cm",
+ "product": 86,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 202,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "93855755",
+ "name": "500ml",
+ "product": 72,
+ "track_inventory": true,
+ "weight": "1.0:kg",
+ "default": true
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 203,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "43226647",
+ "name": "1l",
+ "product": 72,
+ "track_inventory": true,
+ "weight": "1.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 204,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "80884671",
+ "name": "2l",
+ "product": 72,
+ "track_inventory": true,
+ "weight": "2.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 205,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "67882967",
+ "name": "500ml",
+ "product": 73,
+ "track_inventory": true,
+ "weight": "1.0:kg",
+ "default": true
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 206,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "14925419",
+ "name": "1l",
+ "product": 73,
+ "track_inventory": true,
+ "weight": "1.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 207,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "62426105",
+ "name": "2l",
+ "product": 73,
+ "track_inventory": true,
+ "weight": "2.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 208,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "45328412",
+ "name": "500ml",
+ "product": 74,
+ "track_inventory": true,
+ "weight": "1.0:kg",
+ "default": true
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 209,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "27512590",
+ "name": "1l",
+ "product": 74,
+ "track_inventory": true,
+ "weight": "1.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 210,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "40636347",
+ "name": "2l",
+ "product": 74,
+ "track_inventory": true,
+ "weight": "2.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 211,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "43200242",
+ "name": "500ml",
+ "product": 75,
+ "track_inventory": true,
+ "weight": "1.0:kg",
+ "default": true
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 212,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "79129513",
+ "name": "1l",
+ "product": 75,
+ "track_inventory": true,
+ "weight": "1.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 213,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "75799450",
+ "name": "2l",
+ "product": 75,
+ "track_inventory": true,
+ "weight": "2.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 214,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "3944859",
+ "name": "500ml",
+ "product": 76,
+ "track_inventory": true,
+ "weight": "1.0:kg",
+ "default": true
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 215,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "5829405",
+ "name": "1l",
+ "product": 76,
+ "track_inventory": true,
+ "weight": "1.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 216,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "84725784",
+ "name": "2l",
+ "product": 76,
+ "track_inventory": true,
+ "weight": "2.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 217,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "70058446",
+ "name": "500ml",
+ "product": 77,
+ "track_inventory": true,
+ "weight": "1.0:kg",
+ "default": true
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 218,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "94044081",
+ "name": "1l",
+ "product": 77,
+ "track_inventory": true,
+ "weight": "1.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 219,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "80696397",
+ "name": "2l",
+ "product": 77,
+ "track_inventory": true,
+ "weight": "2.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 220,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "60752428",
+ "name": "500ml",
+ "product": 78,
+ "track_inventory": true,
+ "weight": "1.0:kg",
+ "default": true
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 221,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "81470859",
+ "name": "1l",
+ "product": 78,
+ "track_inventory": true,
+ "weight": "1.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 222,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "30635751",
+ "name": "2l",
+ "product": 78,
+ "track_inventory": true,
+ "weight": "2.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 223,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "57211177",
+ "name": "500ml",
+ "product": 79,
+ "track_inventory": true,
+ "weight": "1.0:kg",
+ "default": true
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 224,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "57423879",
+ "name": "1l",
+ "product": 79,
+ "track_inventory": true,
+ "weight": "1.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 225,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "21438542",
+ "name": "2l",
+ "product": 79,
+ "track_inventory": true,
+ "weight": "2.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 242,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "398323583",
+ "name": "39",
+ "product": 87,
+ "track_inventory": true,
+ "weight": "0.0:kg",
+ "default": true
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 243,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "398323584",
+ "name": "40",
+ "product": 87,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 244,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "398323585",
+ "name": "41",
+ "product": 87,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 245,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "398323586",
+ "name": "42",
+ "product": 87,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 246,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "398323588",
+ "name": "43",
+ "product": 87,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 247,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "993223583",
+ "name": "40",
+ "product": 88,
+ "track_inventory": true,
+ "weight": "1.0:kg",
+ "default": true
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 248,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "978223582",
+ "name": "41",
+ "product": 88,
+ "track_inventory": true,
+ "weight": "1.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 249,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "918323583",
+ "name": "40",
+ "product": 88,
+ "track_inventory": true,
+ "weight": "2.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 250,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "918223582",
+ "name": "45",
+ "product": 88,
+ "track_inventory": true,
+ "weight": "2.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 251,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "988323583",
+ "name": "S",
+ "product": 89,
+ "track_inventory": true,
+ "weight": "0.0:kg",
+ "default": true
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 252,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "338223582",
+ "name": "M",
+ "product": 89,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 253,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "118223591",
+ "name": "L",
+ "product": 89,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 254,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "448323583",
+ "name": "XL",
+ "product": 89,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 255,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "3128223583",
+ "name": "XXL",
+ "product": 89,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 256,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "29716755",
+ "name": "S",
+ "product": 107,
+ "track_inventory": true,
+ "weight": "0.0:kg",
+ "default": true
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 257,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "66594736",
+ "name": "M",
+ "product": 107,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 258,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "50269944",
+ "name": "L",
+ "product": 107,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 259,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "31352185",
+ "name": "XL",
+ "product": 107,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 260,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "85364796",
+ "name": "XXL",
+ "product": 107,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 261,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "44026421",
+ "name": "S",
+ "product": 108,
+ "track_inventory": true,
+ "weight": "0.0:kg",
+ "default": true
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 262,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "90892602",
+ "name": "M",
+ "product": 108,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 263,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "59014392",
+ "name": "L",
+ "product": 108,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 264,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "43659438",
+ "name": "XL",
+ "product": 108,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 265,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "60597697",
+ "name": "XXL",
+ "product": 108,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 266,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "26592266",
+ "name": "S",
+ "product": 109,
+ "track_inventory": true,
+ "weight": "0.0:kg",
+ "default": true
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 267,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "36260498",
+ "name": "M",
+ "product": 109,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 268,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "37558859",
+ "name": "L",
+ "product": 109,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 269,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "19402012",
+ "name": "XL",
+ "product": 109,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 270,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "17570141",
+ "name": "XXL",
+ "product": 109,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 271,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "98530976",
+ "name": "S",
+ "product": 110,
+ "track_inventory": true,
+ "weight": "0.0:kg",
+ "default": true
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 272,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "46806935",
+ "name": "M",
+ "product": 110,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 273,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "71103052",
+ "name": "L",
+ "product": 110,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 274,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "84812015",
+ "name": "XL",
+ "product": 110,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 275,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "89820261",
+ "name": "XXL",
+ "product": 110,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 276,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "81115323",
+ "name": "S",
+ "product": 111,
+ "track_inventory": true,
+ "weight": "0.0:kg",
+ "default": true
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 277,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "38254631",
+ "name": "M",
+ "product": 111,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 278,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "11511539",
+ "name": "L",
+ "product": 111,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 279,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "84192227",
+ "name": "XL",
+ "product": 111,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 280,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "91642659",
+ "name": "XXL",
+ "product": 111,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 281,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "76491340",
+ "name": "S",
+ "product": 112,
+ "track_inventory": true,
+ "weight": "0.0:kg",
+ "default": true
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 282,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "55101176",
+ "name": "M",
+ "product": 112,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 283,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "28094954",
+ "name": "L",
+ "product": 112,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 284,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "40232182",
+ "name": "XL",
+ "product": 112,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 285,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "21522631",
+ "name": "XXL",
+ "product": 112,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 286,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "29810068",
+ "name": "S",
+ "product": 113,
+ "track_inventory": true,
+ "weight": "0.0:kg",
+ "default": true
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 287,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "57917658",
+ "name": "M",
+ "product": 113,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 288,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "42680611",
+ "name": "L",
+ "product": 113,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 289,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "72289815",
+ "name": "XL",
+ "product": 113,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 290,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "98653891",
+ "name": "XXL",
+ "product": 113,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 291,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "77306807",
+ "name": "S",
+ "product": 114,
+ "track_inventory": true,
+ "weight": "0.0:kg",
+ "default": true
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 292,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "68848129",
+ "name": "M",
+ "product": 114,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 293,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "35342696",
+ "name": "L",
+ "product": 114,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 294,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "98935349",
+ "name": "XL",
+ "product": 114,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 295,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "45179543",
+ "name": "XXL",
+ "product": 114,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 296,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "62783187",
+ "name": "S",
+ "product": 115,
+ "track_inventory": true,
+ "weight": "0.0:kg",
+ "default": true
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 297,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "91406604",
+ "name": "M",
+ "product": 115,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 298,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "22119503",
+ "name": "L",
+ "product": 115,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 299,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "19230637",
+ "name": "XL",
+ "product": 115,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 300,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "61630747",
+ "name": "XXL",
+ "product": 115,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 301,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "15744278",
+ "name": "S",
+ "product": 116,
+ "track_inventory": true,
+ "weight": "0.0:kg",
+ "default": true
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 302,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "21599567",
+ "name": "M",
+ "product": 116,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 303,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "65363253",
+ "name": "L",
+ "product": 116,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 304,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "51987722",
+ "name": "XL",
+ "product": 116,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 305,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "43313080",
+ "name": "XXL",
+ "product": 116,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 306,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "33963052",
+ "name": "S",
+ "product": 117,
+ "track_inventory": true,
+ "weight": "0.0:kg",
+ "default": true
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 307,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "66846240",
+ "name": "M",
+ "product": 117,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 308,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "55365141",
+ "name": "L",
+ "product": 117,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 309,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "73186143",
+ "name": "XL",
+ "product": 117,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 310,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "42651772",
+ "name": "XXL",
+ "product": 117,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 311,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "70760297",
+ "name": "S",
+ "product": 118,
+ "track_inventory": true,
+ "weight": "0.0:kg",
+ "default": true
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 312,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "36334412",
+ "name": "M",
+ "product": 118,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 313,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "35994675",
+ "name": "L",
+ "product": 118,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 314,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "10404946",
+ "name": "XL",
+ "product": 118,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 315,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "45507483",
+ "name": "XXL",
+ "product": 118,
+ "track_inventory": true,
+ "weight": "0.0:kg"
+ }
+ },
+ {
"model": "product.productvariant",
- "pk": 172,
+ "pk": 316,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "sea-lullabies-mp3",
+ "name": "MP3",
+ "product": 119,
+ "track_inventory": true,
+ "weight": null,
+ "default": true
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 317,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "lake-tunes-mp3",
+ "name": "MP3",
+ "product": 120,
+ "track_inventory": true,
+ "weight": null,
+ "default": true
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 318,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "ocean-poems-mp3",
+ "name": "MP3",
+ "product": 121,
+ "track_inventory": true,
+ "weight": null,
+ "default": true
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 319,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "bathroom-songs-mp3",
+ "name": "MP3",
+ "product": 122,
+ "track_inventory": true,
+ "weight": null,
+ "default": true
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 320,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "lagoon-chants-mp3",
+ "name": "MP3",
+ "product": 123,
+ "track_inventory": true,
+ "weight": null,
+ "default": true
+ }
+ },
+ {
+ "model": "product.productvariant",
+ "pk": 321,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "sku": "waterfall-ballads-mp3",
+ "name": "MP3",
+ "product": 124,
+ "track_inventory": true,
+ "weight": null,
+ "default": true
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 1,
+ "fields": {
+ "variant": 314,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 2,
+ "fields": {
+ "variant": 278,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 3,
+ "fields": {
+ "variant": 253,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 4,
+ "fields": {
+ "variant": 193,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": null
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 5,
+ "fields": {
+ "variant": 194,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": null
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 6,
+ "fields": {
+ "variant": 206,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "1.500"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 7,
+ "fields": {
+ "variant": 301,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 8,
+ "fields": {
+ "variant": 270,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 9,
+ "fields": {
+ "variant": 299,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 10,
+ "fields": {
+ "variant": 269,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 11,
+ "fields": {
+ "variant": 225,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "7.000",
+ "cost_price_amount": "2.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 12,
+ "fields": {
+ "variant": 285,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 13,
+ "fields": {
+ "variant": 302,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 14,
+ "fields": {
+ "variant": 298,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 15,
+ "fields": {
+ "variant": 266,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 16,
+ "fields": {
+ "variant": 209,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "1.500"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 17,
+ "fields": {
+ "variant": 283,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 18,
+ "fields": {
+ "variant": 256,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 19,
+ "fields": {
+ "variant": 286,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 20,
+ "fields": {
+ "variant": 222,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "7.000",
+ "cost_price_amount": "2.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 21,
+ "fields": {
+ "variant": 255,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 22,
+ "fields": {
+ "variant": 259,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 23,
+ "fields": {
+ "variant": 252,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 24,
+ "fields": {
+ "variant": 306,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 25,
+ "fields": {
+ "variant": 293,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 26,
+ "fields": {
+ "variant": 313,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 27,
+ "fields": {
+ "variant": 267,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 28,
+ "fields": {
+ "variant": 312,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 29,
+ "fields": {
+ "variant": 268,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 30,
+ "fields": {
+ "variant": 277,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 31,
+ "fields": {
+ "variant": 214,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "1.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 32,
+ "fields": {
+ "variant": 242,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "20.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 33,
+ "fields": {
+ "variant": 243,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "20.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 34,
+ "fields": {
+ "variant": 244,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "20.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 35,
+ "fields": {
+ "variant": 245,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "20.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 36,
+ "fields": {
+ "variant": 246,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "20.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 37,
+ "fields": {
+ "variant": 284,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 38,
+ "fields": {
+ "variant": 210,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "7.000",
+ "cost_price_amount": "2.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 39,
+ "fields": {
+ "variant": 310,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 40,
+ "fields": {
+ "variant": 288,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 41,
+ "fields": {
+ "variant": 211,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "1.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 42,
+ "fields": {
+ "variant": 203,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "1.500"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 43,
+ "fields": {
+ "variant": 305,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 44,
+ "fields": {
+ "variant": 264,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 45,
+ "fields": {
+ "variant": 261,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 46,
+ "fields": {
+ "variant": 254,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 47,
+ "fields": {
+ "variant": 295,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 48,
+ "fields": {
+ "variant": 208,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "1.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 49,
+ "fields": {
+ "variant": 315,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 50,
+ "fields": {
+ "variant": 272,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 51,
+ "fields": {
+ "variant": 258,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 52,
+ "fields": {
+ "variant": 304,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 53,
+ "fields": {
+ "variant": 171,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "15.000",
+ "cost_price_amount": "5.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 54,
+ "fields": {
+ "variant": 172,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "35.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 55,
+ "fields": {
+ "variant": 173,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "49.000",
+ "cost_price_amount": "20.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 56,
+ "fields": {
+ "variant": 282,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 57,
+ "fields": {
+ "variant": 308,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 58,
+ "fields": {
+ "variant": 223,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "1.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 59,
+ "fields": {
+ "variant": 224,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "1.500"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 60,
+ "fields": {
+ "variant": 287,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 61,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "546451997",
- "name": "2.5l",
+ "variant": 215,
+ "channel": 1,
"currency": "USD",
- "price_amount": "35.00",
- "product": 61,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "2.5:kg"
+ "price_amount": "5.000",
+ "cost_price_amount": "1.500"
}
},
{
- "model": "product.productvariant",
- "pk": 173,
+ "model": "product.productvariantchannellisting",
+ "pk": 62,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "546451999",
- "name": "5l",
+ "variant": 263,
+ "channel": 1,
"currency": "USD",
- "price_amount": "49.00",
- "product": 61,
- "track_inventory": true,
- "cost_price_amount": "20.00",
- "weight": "5.0:kg"
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
}
},
{
- "model": "product.productvariant",
- "pk": 174,
+ "model": "product.productvariantchannellisting",
+ "pk": 63,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "998223591",
- "name": "1l",
+ "variant": 265,
+ "channel": 1,
"currency": "USD",
- "price_amount": "15.00",
- "product": 62,
- "track_inventory": true,
- "cost_price_amount": "5.00",
- "weight": "1.0:kg",
- "default": true
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
}
},
{
- "model": "product.productvariant",
- "pk": 175,
+ "model": "product.productvariantchannellisting",
+ "pk": 64,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "998223599",
- "name": "2.5l",
+ "variant": 220,
+ "channel": 1,
"currency": "USD",
- "price_amount": "25.00",
- "product": 62,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "price_amount": "5.000",
+ "cost_price_amount": "1.000"
}
},
{
- "model": "product.productvariant",
- "pk": 176,
+ "model": "product.productvariantchannellisting",
+ "pk": 65,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "998223594",
- "name": "5l",
+ "variant": 300,
+ "channel": 1,
"currency": "USD",
- "price_amount": "49.00",
- "product": 62,
- "track_inventory": true,
- "cost_price_amount": "25.00",
- "weight": "0.0:kg"
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
}
},
{
- "model": "product.productvariant",
- "pk": 177,
+ "model": "product.productvariantchannellisting",
+ "pk": 66,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "998223582",
- "name": "1l",
+ "variant": 207,
+ "channel": 1,
"currency": "USD",
- "price_amount": "15.00",
- "product": 63,
- "track_inventory": true,
- "cost_price_amount": "5.00",
- "weight": "1.0:kg",
- "default": true
+ "price_amount": "7.000",
+ "cost_price_amount": "2.000"
}
},
{
- "model": "product.productvariant",
- "pk": 178,
+ "model": "product.productvariantchannellisting",
+ "pk": 67,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "998223583",
- "name": "2.5l",
+ "variant": 296,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 68,
+ "fields": {
+ "variant": 303,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 69,
+ "fields": {
+ "variant": 257,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 70,
+ "fields": {
+ "variant": 307,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 71,
+ "fields": {
+ "variant": 205,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "1.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 72,
+ "fields": {
+ "variant": 292,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 73,
+ "fields": {
+ "variant": 198,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "12.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 74,
+ "fields": {
+ "variant": 197,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "20.000",
+ "cost_price_amount": "11.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 75,
+ "fields": {
+ "variant": 217,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "1.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 76,
+ "fields": {
+ "variant": 311,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 77,
+ "fields": {
+ "variant": 273,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 78,
+ "fields": {
+ "variant": 289,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 79,
+ "fields": {
+ "variant": 309,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 80,
+ "fields": {
+ "variant": 213,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "7.000",
+ "cost_price_amount": "2.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 81,
+ "fields": {
+ "variant": 281,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 82,
+ "fields": {
+ "variant": 291,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 83,
+ "fields": {
+ "variant": 212,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "1.500"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 84,
+ "fields": {
+ "variant": 219,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "7.000",
+ "cost_price_amount": "2.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 85,
+ "fields": {
+ "variant": 204,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "7.000",
+ "cost_price_amount": "2.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 86,
+ "fields": {
+ "variant": 276,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 87,
+ "fields": {
+ "variant": 221,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "1.500"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 88,
+ "fields": {
+ "variant": 279,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 89,
+ "fields": {
+ "variant": 216,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "7.000",
+ "cost_price_amount": "2.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 90,
+ "fields": {
+ "variant": 274,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 91,
+ "fields": {
+ "variant": 260,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 92,
+ "fields": {
+ "variant": 275,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 93,
+ "fields": {
+ "variant": 262,
+ "channel": 1,
"currency": "USD",
- "price_amount": "25.00",
- "product": 63,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "2.5:kg"
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
}
},
{
- "model": "product.productvariant",
- "pk": 179,
+ "model": "product.productvariantchannellisting",
+ "pk": 94,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "998223584",
- "name": "5l",
+ "variant": 297,
+ "channel": 1,
"currency": "USD",
- "price_amount": "49.00",
- "product": 63,
- "track_inventory": true,
- "cost_price_amount": "20.00",
- "weight": "5.0:kg"
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
}
},
{
- "model": "product.productvariant",
- "pk": 180,
+ "model": "product.productvariantchannellisting",
+ "pk": 95,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "998323582",
- "name": "1l",
+ "variant": 280,
+ "channel": 1,
"currency": "USD",
- "price_amount": "15.00",
- "product": 64,
- "track_inventory": true,
- "cost_price_amount": "5.00",
- "weight": "1.0:kg",
- "default": true
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
}
},
{
- "model": "product.productvariant",
- "pk": 181,
+ "model": "product.productvariantchannellisting",
+ "pk": 96,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "998323583",
- "name": "2.5l",
+ "variant": 250,
+ "channel": 1,
"currency": "USD",
- "price_amount": "30.00",
- "product": 64,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "2.5:kg"
+ "price_amount": "5.000",
+ "cost_price_amount": "20.000"
}
},
{
- "model": "product.productvariant",
- "pk": 182,
+ "model": "product.productvariantchannellisting",
+ "pk": 97,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "998323584",
- "name": "5l",
+ "variant": 249,
+ "channel": 1,
"currency": "USD",
- "price_amount": "49.00",
- "product": 64,
- "track_inventory": true,
- "cost_price_amount": "15.00",
- "weight": "5.0:kg"
+ "price_amount": "5.000",
+ "cost_price_amount": null
}
},
{
- "model": "product.productvariant",
- "pk": 183,
+ "model": "product.productvariantchannellisting",
+ "pk": 98,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "998423582",
- "name": "1l",
+ "variant": 191,
+ "channel": 1,
"currency": "USD",
- "price_amount": "15.00",
- "product": 65,
- "track_inventory": true,
- "cost_price_amount": "5.00",
- "weight": "1.0:kg",
- "default": true
+ "price_amount": "5.000",
+ "cost_price_amount": "1.500"
}
},
{
- "model": "product.productvariant",
- "pk": 184,
+ "model": "product.productvariantchannellisting",
+ "pk": 99,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "998423583",
- "name": "2.5l",
+ "variant": 202,
+ "channel": 1,
"currency": "USD",
- "price_amount": "30.00",
- "product": 65,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "2.5:kg"
+ "price_amount": "5.000",
+ "cost_price_amount": "1.000"
}
},
{
- "model": "product.productvariant",
- "pk": 185,
+ "model": "product.productvariantchannellisting",
+ "pk": 100,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "998423585",
- "name": "5l",
+ "variant": 218,
+ "channel": 1,
"currency": "USD",
- "price_amount": "49.00",
- "product": 65,
- "track_inventory": true,
- "cost_price_amount": "15.00",
- "weight": "5.0:kg"
+ "price_amount": "5.000",
+ "cost_price_amount": "1.500"
}
},
{
- "model": "product.productvariant",
- "pk": 190,
+ "model": "product.productvariantchannellisting",
+ "pk": 101,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "988323582",
- "name": "500ml",
+ "variant": 248,
+ "channel": 1,
"currency": "USD",
- "price_amount": "5.00",
- "product": 71,
- "track_inventory": true,
- "cost_price_amount": "1.00",
- "weight": "1.0:kg",
- "default": true
+ "price_amount": "5.000",
+ "cost_price_amount": "20.000"
}
},
{
- "model": "product.productvariant",
- "pk": 191,
+ "model": "product.productvariantchannellisting",
+ "pk": 102,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "938323582",
- "name": "1l",
+ "variant": 271,
+ "channel": 1,
"currency": "USD",
- "price_amount": "5.00",
- "product": 71,
- "track_inventory": true,
- "cost_price_amount": "1.50",
- "weight": "1.0:kg"
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
}
},
{
- "model": "product.productvariant",
- "pk": 192,
+ "model": "product.productvariantchannellisting",
+ "pk": 103,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "988323522",
- "name": "2l",
+ "variant": 195,
+ "channel": 1,
"currency": "USD",
- "price_amount": "7.00",
- "product": 71,
- "track_inventory": true,
- "cost_price_amount": "2.00",
- "weight": "2.0:kg"
+ "price_amount": "5.000",
+ "cost_price_amount": null
}
},
{
- "model": "product.productvariant",
- "pk": 193,
+ "model": "product.productvariantchannellisting",
+ "pk": 104,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "12312312321",
- "name": "",
+ "variant": 196,
+ "channel": 1,
"currency": "USD",
- "price_amount": "5.00",
- "product": 81,
- "track_inventory": true,
- "cost_price_amount": null,
- "weight": "0.0:kg",
- "default": true
+ "price_amount": "5.000",
+ "cost_price_amount": null
}
},
{
- "model": "product.productvariant",
- "pk": 194,
+ "model": "product.productvariantchannellisting",
+ "pk": 105,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "1231998121",
- "name": "",
+ "variant": 290,
+ "channel": 1,
"currency": "USD",
- "price_amount": "5.00",
- "product": 82,
- "track_inventory": true,
- "cost_price_amount": null,
- "weight": "0.0:kg",
- "default": true
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
}
},
{
- "model": "product.productvariant",
- "pk": 195,
+ "model": "product.productvariantchannellisting",
+ "pk": 106,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "98616712",
- "name": "",
+ "variant": 199,
+ "channel": 1,
"currency": "USD",
- "price_amount": "5.00",
- "product": 83,
- "track_inventory": true,
- "cost_price_amount": null,
- "weight": "0.0:kg",
- "default": true
+ "price_amount": "5.000",
+ "cost_price_amount": "13.000"
}
},
{
- "model": "product.productvariant",
- "pk": 196,
+ "model": "product.productvariantchannellisting",
+ "pk": 107,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "98616713",
- "name": "",
+ "variant": 192,
+ "channel": 1,
"currency": "USD",
- "price_amount": "5.00",
- "product": 84,
- "track_inventory": true,
- "cost_price_amount": null,
- "weight": "0.0:kg",
- "default": true
+ "price_amount": "7.000",
+ "cost_price_amount": "2.000"
}
},
{
- "model": "product.productvariant",
- "pk": 197,
+ "model": "product.productvariantchannellisting",
+ "pk": 108,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "698223582",
- "name": "45cm x 45cm",
+ "variant": 190,
+ "channel": 1,
"currency": "USD",
- "price_amount": "20.00",
- "product": 85,
- "track_inventory": true,
- "cost_price_amount": "11.00",
- "weight": "0.0:kg",
- "default": true
+ "price_amount": "5.000",
+ "cost_price_amount": "1.000"
}
},
{
- "model": "product.productvariant",
- "pk": 198,
+ "model": "product.productvariantchannellisting",
+ "pk": 109,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "698223581",
- "name": "55cm x 55cm",
+ "variant": 251,
+ "channel": 1,
"currency": "USD",
- "price_amount": "5.00",
- "product": 85,
- "track_inventory": true,
- "cost_price_amount": "12.00",
- "weight": "0.0:kg"
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
}
},
{
- "model": "product.productvariant",
- "pk": 199,
+ "model": "product.productvariantchannellisting",
+ "pk": 110,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "987126191",
- "name": "45cm x 45cm",
+ "variant": 294,
+ "channel": 1,
"currency": "USD",
- "price_amount": "5.00",
- "product": 86,
- "track_inventory": true,
- "cost_price_amount": "13.00",
- "weight": "0.0:kg",
- "default": true
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
}
},
{
- "model": "product.productvariant",
- "pk": 200,
+ "model": "product.productvariantchannellisting",
+ "pk": 111,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "998223590",
- "name": "55cm x 55cm",
+ "variant": 247,
+ "channel": 1,
"currency": "USD",
- "price_amount": "5.00",
- "product": 86,
- "track_inventory": true,
- "cost_price_amount": "13.00",
- "weight": "0.0:kg"
+ "price_amount": "5.000",
+ "cost_price_amount": "10.000"
}
},
{
- "model": "product.productvariant",
- "pk": 202,
+ "model": "product.productvariantchannellisting",
+ "pk": 112,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "93855755",
- "name": "500ml",
+ "variant": 177,
+ "channel": 1,
"currency": "USD",
- "price_amount": "5.00",
- "product": 72,
- "track_inventory": true,
- "cost_price_amount": "1.00",
- "weight": "1.0:kg",
- "default": true
+ "price_amount": "15.000",
+ "cost_price_amount": "5.000"
}
},
{
- "model": "product.productvariant",
- "pk": 203,
+ "model": "product.productvariantchannellisting",
+ "pk": 113,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "43226647",
- "name": "1l",
+ "variant": 178,
+ "channel": 1,
"currency": "USD",
- "price_amount": "5.00",
- "product": 72,
- "track_inventory": true,
- "cost_price_amount": "1.50",
- "weight": "1.0:kg"
+ "price_amount": "25.000",
+ "cost_price_amount": "10.000"
}
},
{
- "model": "product.productvariant",
- "pk": 204,
+ "model": "product.productvariantchannellisting",
+ "pk": 114,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "80884671",
- "name": "2l",
+ "variant": 179,
+ "channel": 1,
"currency": "USD",
- "price_amount": "7.00",
- "product": 72,
- "track_inventory": true,
- "cost_price_amount": "2.00",
- "weight": "2.0:kg"
+ "price_amount": "49.000",
+ "cost_price_amount": "20.000"
}
},
{
- "model": "product.productvariant",
- "pk": 205,
+ "model": "product.productvariantchannellisting",
+ "pk": 115,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "67882967",
- "name": "500ml",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 73,
- "track_inventory": true,
- "cost_price_amount": "1.00",
- "weight": "1.0:kg",
- "default": true
+ "variant": 200,
+ "channel": 1,
+ "currency": "USD",
+ "price_amount": "5.000",
+ "cost_price_amount": "13.000"
}
},
{
- "model": "product.productvariant",
- "pk": 206,
+ "model": "product.productvariantchannellisting",
+ "pk": 116,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "14925419",
- "name": "1l",
+ "variant": 174,
+ "channel": 1,
"currency": "USD",
- "price_amount": "5.00",
- "product": 73,
- "track_inventory": true,
- "cost_price_amount": "1.50",
- "weight": "1.0:kg"
+ "price_amount": "15.000",
+ "cost_price_amount": "5.000"
}
},
{
- "model": "product.productvariant",
- "pk": 207,
+ "model": "product.productvariantchannellisting",
+ "pk": 117,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "62426105",
- "name": "2l",
+ "variant": 176,
+ "channel": 1,
"currency": "USD",
- "price_amount": "7.00",
- "product": 73,
- "track_inventory": true,
- "cost_price_amount": "2.00",
- "weight": "2.0:kg"
+ "price_amount": "49.000",
+ "cost_price_amount": "25.000"
}
},
{
- "model": "product.productvariant",
- "pk": 208,
+ "model": "product.productvariantchannellisting",
+ "pk": 118,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "45328412",
- "name": "500ml",
+ "variant": 175,
+ "channel": 1,
"currency": "USD",
- "price_amount": "5.00",
- "product": 74,
- "track_inventory": true,
- "cost_price_amount": "1.00",
- "weight": "1.0:kg",
- "default": true
+ "price_amount": "25.000",
+ "cost_price_amount": "10.000"
}
},
{
- "model": "product.productvariant",
- "pk": 209,
+ "model": "product.productvariantchannellisting",
+ "pk": 119,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "27512590",
- "name": "1l",
+ "variant": 180,
+ "channel": 1,
"currency": "USD",
- "price_amount": "5.00",
- "product": 74,
- "track_inventory": true,
- "cost_price_amount": "1.50",
- "weight": "1.0:kg"
+ "price_amount": "15.000",
+ "cost_price_amount": "5.000"
}
},
{
- "model": "product.productvariant",
- "pk": 210,
+ "model": "product.productvariantchannellisting",
+ "pk": 120,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "40636347",
- "name": "2l",
+ "variant": 181,
+ "channel": 1,
"currency": "USD",
- "price_amount": "7.00",
- "product": 74,
- "track_inventory": true,
- "cost_price_amount": "2.00",
- "weight": "2.0:kg"
+ "price_amount": "30.000",
+ "cost_price_amount": "10.000"
}
},
{
- "model": "product.productvariant",
- "pk": 211,
+ "model": "product.productvariantchannellisting",
+ "pk": 121,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "43200242",
- "name": "500ml",
+ "variant": 182,
+ "channel": 1,
"currency": "USD",
- "price_amount": "5.00",
- "product": 75,
- "track_inventory": true,
- "cost_price_amount": "1.00",
- "weight": "1.0:kg",
- "default": true
+ "price_amount": "49.000",
+ "cost_price_amount": "15.000"
}
},
{
- "model": "product.productvariant",
- "pk": 212,
+ "model": "product.productvariantchannellisting",
+ "pk": 122,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "79129513",
- "name": "1l",
+ "variant": 183,
+ "channel": 1,
"currency": "USD",
- "price_amount": "5.00",
- "product": 75,
- "track_inventory": true,
- "cost_price_amount": "1.50",
- "weight": "1.0:kg"
+ "price_amount": "15.000",
+ "cost_price_amount": "5.000"
}
},
{
- "model": "product.productvariant",
- "pk": 213,
+ "model": "product.productvariantchannellisting",
+ "pk": 123,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "75799450",
- "name": "2l",
+ "variant": 184,
+ "channel": 1,
"currency": "USD",
- "price_amount": "7.00",
- "product": 75,
- "track_inventory": true,
- "cost_price_amount": "2.00",
- "weight": "2.0:kg"
+ "price_amount": "30.000",
+ "cost_price_amount": "10.000"
}
},
{
- "model": "product.productvariant",
- "pk": 214,
+ "model": "product.productvariantchannellisting",
+ "pk": 124,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "3944859",
- "name": "500ml",
+ "variant": 185,
+ "channel": 1,
"currency": "USD",
- "price_amount": "5.00",
- "product": 76,
- "track_inventory": true,
- "cost_price_amount": "1.00",
- "weight": "1.0:kg",
- "default": true
+ "price_amount": "49.000",
+ "cost_price_amount": "15.000"
}
},
{
- "model": "product.productvariant",
- "pk": 215,
+ "model": "product.productvariantchannellisting",
+ "pk": 125,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "5829405",
- "name": "1l",
+ "variant": 319,
+ "channel": 1,
"currency": "USD",
- "price_amount": "5.00",
- "product": 76,
- "track_inventory": true,
- "cost_price_amount": "1.50",
- "weight": "1.0:kg"
+ "price_amount": "9.990",
+ "cost_price_amount": null
}
},
{
- "model": "product.productvariant",
- "pk": 216,
+ "model": "product.productvariantchannellisting",
+ "pk": 126,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "84725784",
- "name": "2l",
+ "variant": 320,
+ "channel": 1,
"currency": "USD",
- "price_amount": "7.00",
- "product": 76,
- "track_inventory": true,
- "cost_price_amount": "2.00",
- "weight": "2.0:kg"
+ "price_amount": "9.990",
+ "cost_price_amount": null
}
},
{
- "model": "product.productvariant",
- "pk": 217,
+ "model": "product.productvariantchannellisting",
+ "pk": 127,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "70058446",
- "name": "500ml",
+ "variant": 317,
+ "channel": 1,
"currency": "USD",
- "price_amount": "5.00",
- "product": 77,
- "track_inventory": true,
- "cost_price_amount": "1.00",
- "weight": "1.0:kg",
- "default": true
+ "price_amount": "9.990",
+ "cost_price_amount": null
}
},
{
- "model": "product.productvariant",
- "pk": 218,
+ "model": "product.productvariantchannellisting",
+ "pk": 128,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "94044081",
- "name": "1l",
+ "variant": 318,
+ "channel": 1,
"currency": "USD",
- "price_amount": "5.00",
- "product": 77,
- "track_inventory": true,
- "cost_price_amount": "1.50",
- "weight": "1.0:kg"
+ "price_amount": "9.990",
+ "cost_price_amount": null
}
},
{
- "model": "product.productvariant",
- "pk": 219,
+ "model": "product.productvariantchannellisting",
+ "pk": 129,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "80696397",
- "name": "2l",
+ "variant": 316,
+ "channel": 1,
"currency": "USD",
- "price_amount": "7.00",
- "product": 77,
- "track_inventory": true,
- "cost_price_amount": "2.00",
- "weight": "2.0:kg"
+ "price_amount": "9.990",
+ "cost_price_amount": null
}
},
{
- "model": "product.productvariant",
- "pk": 220,
+ "model": "product.productvariantchannellisting",
+ "pk": 130,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "60752428",
- "name": "500ml",
+ "variant": 321,
+ "channel": 1,
"currency": "USD",
- "price_amount": "5.00",
- "product": 78,
- "track_inventory": true,
- "cost_price_amount": "1.00",
- "weight": "1.0:kg",
- "default": true
+ "price_amount": "9.990",
+ "cost_price_amount": null
}
},
{
- "model": "product.productvariant",
- "pk": 221,
+ "model": "product.productvariantchannellisting",
+ "pk": 131,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "81470859",
- "name": "1l",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 78,
- "track_inventory": true,
- "cost_price_amount": "1.50",
- "weight": "1.0:kg"
+ "variant": 203,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "6.000"
}
},
{
- "model": "product.productvariant",
- "pk": 222,
+ "model": "product.productvariantchannellisting",
+ "pk": 132,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "30635751",
- "name": "2l",
- "currency": "USD",
- "price_amount": "7.00",
- "product": 78,
- "track_inventory": true,
- "cost_price_amount": "2.00",
- "weight": "2.0:kg"
+ "variant": 204,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "28.000",
+ "cost_price_amount": "8.000"
}
},
{
- "model": "product.productvariant",
- "pk": 223,
+ "model": "product.productvariantchannellisting",
+ "pk": 133,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "57211177",
- "name": "500ml",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 79,
- "track_inventory": true,
- "cost_price_amount": "1.00",
- "weight": "1.0:kg",
- "default": true
+ "variant": 202,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "4.000"
}
},
{
- "model": "product.productvariant",
- "pk": 224,
+ "model": "product.productvariantchannellisting",
+ "pk": 134,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "57423879",
- "name": "1l",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 79,
- "track_inventory": true,
- "cost_price_amount": "1.50",
- "weight": "1.0:kg"
+ "variant": 209,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "6.000"
}
},
{
- "model": "product.productvariant",
- "pk": 225,
+ "model": "product.productvariantchannellisting",
+ "pk": 135,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "21438542",
- "name": "2l",
- "currency": "USD",
- "price_amount": "7.00",
- "product": 79,
- "track_inventory": true,
- "cost_price_amount": "2.00",
- "weight": "2.0:kg"
+ "variant": 210,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "28.000",
+ "cost_price_amount": "8.000"
}
},
{
- "model": "product.productvariant",
- "pk": 242,
+ "model": "product.productvariantchannellisting",
+ "pk": 136,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "398323583",
- "name": "39",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 87,
- "track_inventory": true,
- "cost_price_amount": "20.00",
- "weight": "0.0:kg",
- "default": true
+ "variant": 208,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "4.000"
}
},
{
- "model": "product.productvariant",
- "pk": 243,
+ "model": "product.productvariantchannellisting",
+ "pk": 137,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "398323584",
- "name": "40",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 87,
- "track_inventory": true,
- "cost_price_amount": "20.00",
- "weight": "0.0:kg"
+ "variant": 319,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "39.960",
+ "cost_price_amount": null
}
},
{
- "model": "product.productvariant",
- "pk": 244,
+ "model": "product.productvariantchannellisting",
+ "pk": 138,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "398323585",
- "name": "41",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 87,
- "track_inventory": true,
- "cost_price_amount": "20.00",
- "weight": "0.0:kg"
+ "variant": 225,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "28.000",
+ "cost_price_amount": "8.000"
}
},
{
- "model": "product.productvariant",
- "pk": 245,
+ "model": "product.productvariantchannellisting",
+ "pk": 139,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "398323586",
- "name": "42",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 87,
- "track_inventory": true,
- "cost_price_amount": "20.00",
- "weight": "0.0:kg"
+ "variant": 223,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "4.000"
}
},
{
- "model": "product.productvariant",
- "pk": 246,
+ "model": "product.productvariantchannellisting",
+ "pk": 140,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "398323588",
- "name": "43",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 87,
- "track_inventory": true,
- "cost_price_amount": "20.00",
- "weight": "0.0:kg"
+ "variant": 224,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "6.000"
}
},
{
- "model": "product.productvariant",
- "pk": 247,
+ "model": "product.productvariantchannellisting",
+ "pk": 141,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "993223583",
- "name": "40",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 88,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "1.0:kg",
- "default": true
+ "variant": 299,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "40.000"
}
},
{
- "model": "product.productvariant",
- "pk": 248,
+ "model": "product.productvariantchannellisting",
+ "pk": 142,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "978223582",
- "name": "41",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 88,
- "track_inventory": true,
- "cost_price_amount": "20.00",
- "weight": "1.0:kg"
+ "variant": 298,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "40.000"
}
},
{
- "model": "product.productvariant",
- "pk": 249,
+ "model": "product.productvariantchannellisting",
+ "pk": 143,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "918323583",
- "name": "40",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 88,
- "track_inventory": true,
- "cost_price_amount": null,
- "weight": "2.0:kg"
+ "variant": 300,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "40.000"
}
},
{
- "model": "product.productvariant",
- "pk": 250,
+ "model": "product.productvariantchannellisting",
+ "pk": 144,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "918223582",
- "name": "45",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 88,
- "track_inventory": true,
- "cost_price_amount": "20.00",
- "weight": "2.0:kg"
+ "variant": 296,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "40.000"
}
},
{
- "model": "product.productvariant",
- "pk": 251,
+ "model": "product.productvariantchannellisting",
+ "pk": 145,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "988323583",
- "name": "S",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 89,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg",
- "default": true
+ "variant": 297,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "40.000"
}
},
{
- "model": "product.productvariant",
- "pk": 252,
+ "model": "product.productvariantchannellisting",
+ "pk": 146,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "338223582",
- "name": "M",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 89,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 301,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "40.000"
}
},
{
- "model": "product.productvariant",
- "pk": 253,
+ "model": "product.productvariantchannellisting",
+ "pk": 147,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "118223591",
- "name": "L",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 89,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 302,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "40.000"
}
},
{
- "model": "product.productvariant",
- "pk": 254,
+ "model": "product.productvariantchannellisting",
+ "pk": 148,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "448323583",
- "name": "XL",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 89,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 305,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "40.000"
}
},
{
- "model": "product.productvariant",
- "pk": 255,
+ "model": "product.productvariantchannellisting",
+ "pk": 149,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "3128223583",
- "name": "XXL",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 89,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 304,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "40.000"
}
},
{
- "model": "product.productvariant",
- "pk": 256,
+ "model": "product.productvariantchannellisting",
+ "pk": 150,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "29716755",
- "name": "S",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 107,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg",
- "default": true
+ "variant": 303,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "40.000"
}
},
{
- "model": "product.productvariant",
- "pk": 257,
+ "model": "product.productvariantchannellisting",
+ "pk": 151,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "66594736",
- "name": "M",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 107,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 206,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "6.000"
}
},
{
- "model": "product.productvariant",
- "pk": 258,
+ "model": "product.productvariantchannellisting",
+ "pk": 152,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "50269944",
- "name": "L",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 107,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 207,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "28.000",
+ "cost_price_amount": "8.000"
}
},
{
- "model": "product.productvariant",
- "pk": 259,
+ "model": "product.productvariantchannellisting",
+ "pk": 153,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "31352185",
- "name": "XL",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 107,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 205,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "4.000"
}
},
{
- "model": "product.productvariant",
- "pk": 260,
+ "model": "product.productvariantchannellisting",
+ "pk": 154,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "85364796",
- "name": "XXL",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 107,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 214,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "4.000"
}
},
{
- "model": "product.productvariant",
- "pk": 261,
+ "model": "product.productvariantchannellisting",
+ "pk": 155,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "44026421",
- "name": "S",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 108,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg",
- "default": true
+ "variant": 215,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "6.000"
}
},
{
- "model": "product.productvariant",
- "pk": 262,
+ "model": "product.productvariantchannellisting",
+ "pk": 156,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "90892602",
- "name": "M",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 108,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 216,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "28.000",
+ "cost_price_amount": "8.000"
}
},
{
- "model": "product.productvariant",
- "pk": 263,
+ "model": "product.productvariantchannellisting",
+ "pk": 157,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "59014392",
- "name": "L",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 108,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 253,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "40.000"
}
},
{
- "model": "product.productvariant",
- "pk": 264,
+ "model": "product.productvariantchannellisting",
+ "pk": 158,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "43659438",
- "name": "XL",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 108,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 255,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "40.000"
}
},
{
- "model": "product.productvariant",
- "pk": 265,
+ "model": "product.productvariantchannellisting",
+ "pk": 159,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "60597697",
- "name": "XXL",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 108,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 252,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "40.000"
}
},
{
- "model": "product.productvariant",
- "pk": 266,
+ "model": "product.productvariantchannellisting",
+ "pk": 160,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "26592266",
- "name": "S",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 109,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg",
- "default": true
+ "variant": 254,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "40.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 161,
+ "fields": {
+ "variant": 251,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "40.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 162,
+ "fields": {
+ "variant": 198,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "48.000"
}
},
{
- "model": "product.productvariant",
- "pk": 267,
+ "model": "product.productvariantchannellisting",
+ "pk": 163,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "36260498",
- "name": "M",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 109,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 197,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "80.000",
+ "cost_price_amount": "44.000"
}
},
{
- "model": "product.productvariant",
- "pk": 268,
+ "model": "product.productvariantchannellisting",
+ "pk": 164,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "37558859",
- "name": "L",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 109,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 222,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "28.000",
+ "cost_price_amount": "8.000"
}
},
{
- "model": "product.productvariant",
- "pk": 269,
+ "model": "product.productvariantchannellisting",
+ "pk": 165,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "19402012",
- "name": "XL",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 109,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 220,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "4.000"
}
},
{
- "model": "product.productvariant",
- "pk": 270,
+ "model": "product.productvariantchannellisting",
+ "pk": 166,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "17570141",
- "name": "XXL",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 109,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 221,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "6.000"
}
},
{
- "model": "product.productvariant",
- "pk": 271,
+ "model": "product.productvariantchannellisting",
+ "pk": 167,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "98530976",
- "name": "S",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 110,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg",
- "default": true
+ "variant": 183,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "60.000",
+ "cost_price_amount": "20.000"
}
},
{
- "model": "product.productvariant",
- "pk": 272,
+ "model": "product.productvariantchannellisting",
+ "pk": 168,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "46806935",
- "name": "M",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 110,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 184,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "120.000",
+ "cost_price_amount": "40.000"
}
},
{
- "model": "product.productvariant",
- "pk": 273,
+ "model": "product.productvariantchannellisting",
+ "pk": 169,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "71103052",
- "name": "L",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 110,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 185,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "196.000",
+ "cost_price_amount": "60.000"
}
},
{
- "model": "product.productvariant",
- "pk": 274,
+ "model": "product.productvariantchannellisting",
+ "pk": 170,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "84812015",
- "name": "XL",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 110,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 320,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "39.960",
+ "cost_price_amount": null
}
},
{
- "model": "product.productvariant",
- "pk": 275,
+ "model": "product.productvariantchannellisting",
+ "pk": 171,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "89820261",
- "name": "XXL",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 110,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 317,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "39.960",
+ "cost_price_amount": null
}
},
{
- "model": "product.productvariant",
- "pk": 276,
+ "model": "product.productvariantchannellisting",
+ "pk": 172,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "81115323",
- "name": "S",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 111,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg",
- "default": true
+ "variant": 180,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "60.000",
+ "cost_price_amount": "20.000"
}
},
{
- "model": "product.productvariant",
- "pk": 277,
+ "model": "product.productvariantchannellisting",
+ "pk": 173,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "38254631",
- "name": "M",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 111,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 181,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "120.000",
+ "cost_price_amount": "40.000"
}
},
{
- "model": "product.productvariant",
- "pk": 278,
+ "model": "product.productvariantchannellisting",
+ "pk": 174,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "11511539",
- "name": "L",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 111,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 182,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "196.000",
+ "cost_price_amount": "60.000"
}
},
{
- "model": "product.productvariant",
- "pk": 279,
+ "model": "product.productvariantchannellisting",
+ "pk": 175,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "84192227",
- "name": "XL",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 111,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 306,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "40.000"
}
},
{
- "model": "product.productvariant",
- "pk": 280,
+ "model": "product.productvariantchannellisting",
+ "pk": 176,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "91642659",
- "name": "XXL",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 111,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 310,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "40.000"
}
},
{
- "model": "product.productvariant",
- "pk": 281,
+ "model": "product.productvariantchannellisting",
+ "pk": 177,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "76491340",
- "name": "S",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 112,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg",
- "default": true
+ "variant": 308,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "40.000"
}
},
{
- "model": "product.productvariant",
- "pk": 282,
+ "model": "product.productvariantchannellisting",
+ "pk": 178,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "55101176",
- "name": "M",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 112,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 307,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "40.000"
}
},
{
- "model": "product.productvariant",
- "pk": 283,
+ "model": "product.productvariantchannellisting",
+ "pk": 179,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "28094954",
- "name": "L",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 112,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 309,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "40.000"
}
},
{
- "model": "product.productvariant",
- "pk": 284,
+ "model": "product.productvariantchannellisting",
+ "pk": 180,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "40232182",
- "name": "XL",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 112,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 171,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "60.000",
+ "cost_price_amount": "20.000"
}
},
{
- "model": "product.productvariant",
- "pk": 285,
+ "model": "product.productvariantchannellisting",
+ "pk": 181,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "21522631",
- "name": "XXL",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 112,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 172,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "140.000",
+ "cost_price_amount": "40.000"
}
},
{
- "model": "product.productvariant",
- "pk": 286,
+ "model": "product.productvariantchannellisting",
+ "pk": 182,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "29810068",
- "name": "S",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 113,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg",
- "default": true
+ "variant": 173,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "196.000",
+ "cost_price_amount": "80.000"
}
},
{
- "model": "product.productvariant",
- "pk": 287,
+ "model": "product.productvariantchannellisting",
+ "pk": 183,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "57917658",
- "name": "M",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 113,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 318,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "39.960",
+ "cost_price_amount": null
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 184,
+ "fields": {
+ "variant": 191,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "6.000"
}
},
{
- "model": "product.productvariant",
- "pk": 288,
+ "model": "product.productvariantchannellisting",
+ "pk": 185,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "42680611",
- "name": "L",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 113,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 192,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "28.000",
+ "cost_price_amount": "8.000"
}
},
{
- "model": "product.productvariant",
- "pk": 289,
+ "model": "product.productvariantchannellisting",
+ "pk": 186,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "72289815",
- "name": "XL",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 113,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 190,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "4.000"
}
},
{
- "model": "product.productvariant",
- "pk": 290,
+ "model": "product.productvariantchannellisting",
+ "pk": 187,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "98653891",
- "name": "XXL",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 113,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 211,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "4.000"
}
},
{
- "model": "product.productvariant",
- "pk": 291,
+ "model": "product.productvariantchannellisting",
+ "pk": 188,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "77306807",
- "name": "S",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 114,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg",
- "default": true
+ "variant": 213,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "28.000",
+ "cost_price_amount": "8.000"
}
},
{
- "model": "product.productvariant",
- "pk": 292,
+ "model": "product.productvariantchannellisting",
+ "pk": 189,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "68848129",
- "name": "M",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 114,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 212,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "6.000"
}
},
{
- "model": "product.productvariant",
- "pk": 293,
+ "model": "product.productvariantchannellisting",
+ "pk": 190,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "35342696",
- "name": "L",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 114,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 256,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "40.000"
}
},
{
- "model": "product.productvariant",
- "pk": 294,
+ "model": "product.productvariantchannellisting",
+ "pk": 191,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "98935349",
- "name": "XL",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 114,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 259,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "40.000"
}
},
{
- "model": "product.productvariant",
- "pk": 295,
+ "model": "product.productvariantchannellisting",
+ "pk": 192,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "45179543",
- "name": "XXL",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 114,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 258,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "40.000"
}
},
{
- "model": "product.productvariant",
- "pk": 296,
+ "model": "product.productvariantchannellisting",
+ "pk": 193,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "62783187",
- "name": "S",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 115,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg",
- "default": true
+ "variant": 257,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "40.000"
}
},
{
- "model": "product.productvariant",
- "pk": 297,
+ "model": "product.productvariantchannellisting",
+ "pk": 194,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "91406604",
- "name": "M",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 115,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 260,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "40.000"
}
},
{
- "model": "product.productvariant",
- "pk": 298,
+ "model": "product.productvariantchannellisting",
+ "pk": 195,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "22119503",
- "name": "L",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 115,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 264,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "40.000"
}
},
{
- "model": "product.productvariant",
- "pk": 299,
+ "model": "product.productvariantchannellisting",
+ "pk": 196,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "19230637",
- "name": "XL",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 115,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 261,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "40.000"
}
},
{
- "model": "product.productvariant",
- "pk": 300,
+ "model": "product.productvariantchannellisting",
+ "pk": 197,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "61630747",
- "name": "XXL",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 115,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 263,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "40.000"
}
},
{
- "model": "product.productvariant",
- "pk": 301,
+ "model": "product.productvariantchannellisting",
+ "pk": 198,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "15744278",
- "name": "S",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 116,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg",
- "default": true
+ "variant": 265,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "40.000"
}
},
{
- "model": "product.productvariant",
- "pk": 302,
+ "model": "product.productvariantchannellisting",
+ "pk": 199,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "21599567",
- "name": "M",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 116,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 262,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "40.000"
}
},
{
- "model": "product.productvariant",
- "pk": 303,
+ "model": "product.productvariantchannellisting",
+ "pk": 200,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "65363253",
- "name": "L",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 116,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 270,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "40.000"
}
},
{
- "model": "product.productvariant",
- "pk": 304,
+ "model": "product.productvariantchannellisting",
+ "pk": 201,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "51987722",
- "name": "XL",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 116,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 269,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "40.000"
}
},
{
- "model": "product.productvariant",
- "pk": 305,
+ "model": "product.productvariantchannellisting",
+ "pk": 202,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "43313080",
- "name": "XXL",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 116,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 266,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "40.000"
}
},
{
- "model": "product.productvariant",
- "pk": 306,
+ "model": "product.productvariantchannellisting",
+ "pk": 203,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "33963052",
- "name": "S",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 117,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg",
- "default": true
+ "variant": 267,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "40.000"
}
},
{
- "model": "product.productvariant",
- "pk": 307,
+ "model": "product.productvariantchannellisting",
+ "pk": 204,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "66846240",
- "name": "M",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 117,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 268,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "40.000"
}
},
{
- "model": "product.productvariant",
- "pk": 308,
+ "model": "product.productvariantchannellisting",
+ "pk": 205,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "55365141",
- "name": "L",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 117,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 272,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "40.000"
+ }
+ },
+ {
+ "model": "product.productvariantchannellisting",
+ "pk": 206,
+ "fields": {
+ "variant": 273,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "40.000"
}
},
{
- "model": "product.productvariant",
- "pk": 309,
+ "model": "product.productvariantchannellisting",
+ "pk": 207,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "73186143",
- "name": "XL",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 117,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 274,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "40.000"
}
},
{
- "model": "product.productvariant",
- "pk": 310,
+ "model": "product.productvariantchannellisting",
+ "pk": 208,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "42651772",
- "name": "XXL",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 117,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 275,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "40.000"
}
},
{
- "model": "product.productvariant",
- "pk": 311,
+ "model": "product.productvariantchannellisting",
+ "pk": 209,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "70760297",
- "name": "S",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 118,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg",
- "default": true
+ "variant": 271,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "40.000"
}
},
{
- "model": "product.productvariant",
- "pk": 312,
+ "model": "product.productvariantchannellisting",
+ "pk": 210,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "36334412",
- "name": "M",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 118,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 217,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "4.000"
}
},
{
- "model": "product.productvariant",
- "pk": 313,
+ "model": "product.productvariantchannellisting",
+ "pk": 211,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "35994675",
- "name": "L",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 118,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 219,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "28.000",
+ "cost_price_amount": "8.000"
}
},
{
- "model": "product.productvariant",
- "pk": 314,
+ "model": "product.productvariantchannellisting",
+ "pk": 212,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "10404946",
- "name": "XL",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 118,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 218,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": "6.000"
}
},
{
- "model": "product.productvariant",
- "pk": 315,
+ "model": "product.productvariantchannellisting",
+ "pk": 213,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "45507483",
- "name": "XXL",
- "currency": "USD",
- "price_amount": "5.00",
- "product": 118,
- "track_inventory": true,
- "cost_price_amount": "10.00",
- "weight": "0.0:kg"
+ "variant": 177,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "60.000",
+ "cost_price_amount": "20.000"
}
},
{
- "model": "product.productvariant",
- "pk": 316,
+ "model": "product.productvariantchannellisting",
+ "pk": 214,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "sea-lullabies-mp3",
- "name": "MP3",
- "currency": "USD",
- "price_amount": "9.99",
- "product": 119,
- "track_inventory": true,
- "cost_price_amount": null,
- "weight": null,
- "default": true
+ "variant": 178,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "100.000",
+ "cost_price_amount": "40.000"
}
},
{
- "model": "product.productvariant",
- "pk": 317,
+ "model": "product.productvariantchannellisting",
+ "pk": 215,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "lake-tunes-mp3",
- "name": "MP3",
- "currency": "USD",
- "price_amount": "9.99",
- "product": 120,
- "track_inventory": true,
- "cost_price_amount": null,
- "weight": null,
- "default": true
+ "variant": 179,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "196.000",
+ "cost_price_amount": "80.000"
}
},
{
- "model": "product.productvariant",
- "pk": 318,
+ "model": "product.productvariantchannellisting",
+ "pk": 216,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "ocean-poems-mp3",
- "name": "MP3",
- "currency": "USD",
- "price_amount": "9.99",
- "product": 121,
- "track_inventory": true,
- "cost_price_amount": null,
- "weight": null,
- "default": true
+ "variant": 193,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": null
}
},
{
- "model": "product.productvariant",
- "pk": 319,
+ "model": "product.productvariantchannellisting",
+ "pk": 217,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "bathroom-songs-mp3",
- "name": "MP3",
- "currency": "USD",
- "price_amount": "9.99",
- "product": 122,
- "track_inventory": true,
- "cost_price_amount": null,
- "weight": null,
- "default": true
+ "variant": 316,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "39.960",
+ "cost_price_amount": null
}
},
{
- "model": "product.productvariant",
- "pk": 320,
+ "model": "product.productvariantchannellisting",
+ "pk": 218,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "lagoon-chants-mp3",
- "name": "MP3",
- "currency": "USD",
- "price_amount": "9.99",
- "product": 123,
- "track_inventory": true,
- "cost_price_amount": null,
- "weight": null,
- "default": true
+ "variant": 196,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": null
}
},
{
- "model": "product.productvariant",
- "pk": 321,
+ "model": "product.productvariantchannellisting",
+ "pk": 219,
"fields": {
- "private_metadata": {},
- "metadata": {},
- "sku": "waterfall-ballads-mp3",
- "name": "MP3",
- "currency": "USD",
- "price_amount": "9.99",
- "product": 124,
- "track_inventory": true,
- "cost_price_amount": null,
- "weight": null,
- "default": true
+ "variant": 195,
+ "channel": 2,
+ "currency": "PLN",
+ "price_amount": "20.000",
+ "cost_price_amount": null
}
},
{
@@ -7308,12 +10004,46 @@
"product": 110
}
},
+ {
+ "model": "product.collectionproduct",
+ "pk": 5,
+ "fields": {
+ "sort_order": null,
+ "collection": 3,
+ "product": 83
+ }
+ },
+ {
+ "model": "product.collectionproduct",
+ "pk": 6,
+ "fields": {
+ "sort_order": null,
+ "collection": 3,
+ "product": 84
+ }
+ },
+ {
+ "model": "product.collectionproduct",
+ "pk": 7,
+ "fields": {
+ "sort_order": null,
+ "collection": 3,
+ "product": 61
+ }
+ },
+ {
+ "model": "product.collectionproduct",
+ "pk": 8,
+ "fields": {
+ "sort_order": null,
+ "collection": 3,
+ "product": 110
+ }
+ },
{
"model": "product.collection",
"pk": 1,
"fields": {
- "publication_date": "2020-01-01",
- "is_published": true,
"private_metadata": {},
"metadata": {},
"seo_title": null,
@@ -7337,8 +10067,6 @@
"model": "product.collection",
"pk": 2,
"fields": {
- "publication_date": "2020-01-01",
- "is_published": true,
"private_metadata": {},
"metadata": {},
"seo_title": null,
@@ -7357,5 +10085,92 @@
}]
}
}
+ },
+ {
+ "model": "product.collection",
+ "pk": 3,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "seo_title": null,
+ "seo_description": null,
+ "name": "Featured Products",
+ "slug": "featured-products",
+ "background_image": "collection-backgrounds/clothing_R7nkNxS.jpg",
+ "background_image_alt": "",
+ "description": "Featured Products. Literally, they are not real products, but the Saleor demo store is a genuine e-commerce leader.",
+ "description_json": {
+ "blocks": [{
+ "key": "",
+ "data": {},
+ "text": "Featured Products. Literally, they are not real products, but the Saleor demo store is a genuine e-commerce leader.",
+ "type": "unstyled",
+ "depth": 0,
+ "entityRanges": [],
+ "inlineStyleRanges": []
+ }],
+ "entityMap": {}
+ }
+ }
+ },
+ {
+ "model": "product.collectionchannellisting",
+ "pk": 1,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "collection": 1,
+ "channel": 1
+ }
+ },
+ {
+ "model": "product.collectionchannellisting",
+ "pk": 2,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "collection": 2,
+ "channel": 1
+ }
+ },
+ {
+ "model": "product.collectionchannellisting",
+ "pk": 3,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "collection": 1,
+ "channel": 2
+ }
+ },
+ {
+ "model": "product.collectionchannellisting",
+ "pk": 4,
+ "fields": {
+ "publication_date": null,
+ "is_published": false,
+ "collection": 2,
+ "channel": 2
+ }
+ },
+ {
+ "model": "product.collectionchannellisting",
+ "pk": 5,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "collection": 3,
+ "channel": 1
+ }
+ },
+ {
+ "model": "product.collectionchannellisting",
+ "pk": 6,
+ "fields": {
+ "publication_date": "2020-01-01",
+ "is_published": true,
+ "collection": 3,
+ "channel": 2
+ }
}
]
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 6e252de3c6..d6bf97427a 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -36,8 +36,10 @@ from ..csv.models import ExportEvent, ExportFile
from ..discount import DiscountInfo, DiscountValueType, VoucherType
from ..discount.models import (
Sale,
+ SaleChannelListing,
SaleTranslation,
Voucher,
+ VoucherChannelListing,
VoucherCustomer,
VoucherTranslation,
)
@@ -65,20 +67,24 @@ from ..product.models import (
Category,
CategoryTranslation,
Collection,
+ CollectionChannelListing,
CollectionTranslation,
DigitalContent,
DigitalContentUrl,
Product,
+ ProductChannelListing,
ProductImage,
ProductTranslation,
ProductType,
ProductVariant,
+ ProductVariantChannelListing,
ProductVariantTranslation,
)
from ..product.tests.utils import create_image
from ..product.utils.attributes import associate_attribute_values_to_instance
from ..shipping.models import (
ShippingMethod,
+ ShippingMethodChannelListing,
ShippingMethodTranslation,
ShippingMethodType,
ShippingZone,
@@ -234,8 +240,10 @@ def site_settings(db, settings) -> SiteSettings:
@pytest.fixture
-def checkout(db):
- checkout = Checkout.objects.create(currency="USD")
+def checkout(db, channel_USD):
+ checkout = Checkout.objects.create(
+ currency=channel_USD.currency_code, channel=channel_USD
+ )
checkout.set_country("US", commit=True)
return checkout
@@ -248,6 +256,24 @@ def checkout_with_item(checkout, product):
return checkout
+def checkouts_list(channel_USD, channel_PLN):
+ checkouts_usd = Checkout.objects.bulk_create(
+ [
+ Checkout(currency=channel_USD.currency_code, channel=channel_USD),
+ Checkout(currency=channel_USD.currency_code, channel=channel_USD),
+ Checkout(currency=channel_USD.currency_code, channel=channel_USD),
+ ]
+ )
+ checkouts_pln = Checkout.objects.bulk_create(
+ [
+ Checkout(currency=channel_PLN.currency_code, channel=channel_PLN),
+ Checkout(currency=channel_PLN.currency_code, channel=channel_PLN),
+ ]
+ )
+ return [*checkouts_pln, *checkouts_usd]
+
+
@pytest.fixture
def checkout_ready_to_complete(checkout_with_item, address, shipping_method, gift_card):
checkout = checkout_with_item
@@ -281,14 +307,17 @@ def checkout_with_shipping_required(checkout_with_item, product):
@pytest.fixture
-def other_shipping_method(shipping_zone):
- return ShippingMethod.objects.create(
- name="DPD",
+def other_shipping_method(shipping_zone, channel_USD):
+ method = ShippingMethod.objects.create(
+ name="DPD", type=ShippingMethodType.PRICE_BASED, shipping_zone=shipping_zone,
+ )
+ ShippingMethodChannelListing.objects.create(
+ channel=channel_USD,
+ shipping_method=method,
minimum_order_price=Money(0, "USD"),
- type=ShippingMethodType.PRICE_BASED,
price=Money(9, "USD"),
- shipping_zone=shipping_zone,
)
+ return method
@pytest.fixture
@@ -461,9 +490,10 @@ def customer_user(address): # pylint: disable=W0613
@pytest.fixture
-def user_checkout(customer_user):
+def user_checkout(customer_user, channel_USD):
checkout = Checkout.objects.create(
user=customer_user,
+ channel=channel_USD,
billing_address=customer_user.default_billing_address,
shipping_address=customer_user.default_shipping_address,
note="Test notes",
@@ -482,10 +512,12 @@ def user_checkout_with_items(user_checkout, product_list):
@pytest.fixture
-def order(customer_user):
+def order(customer_user, channel_USD):
address = customer_user.default_billing_address.get_copy()
return Order.objects.create(
billing_address=address,
+ channel=channel_USD,
+ currency=channel_USD.currency_code,
shipping_address=address,
user_email=customer_user.email,
user=customer_user,
@@ -532,67 +564,112 @@ def staff_users(staff_user):
@pytest.fixture
-def shipping_zone(db): # pylint: disable=W0613
+def shipping_zone(db, channel_USD): # pylint: disable=W0613
shipping_zone = ShippingZone.objects.create(
name="Europe", countries=[code for code, name in countries]
)
- shipping_zone.shipping_methods.create(
- name="DHL",
- minimum_order_price=Money(0, "USD"),
- type=ShippingMethodType.PRICE_BASED,
- price=Money(10, "USD"),
- shipping_zone=shipping_zone,
+ method = shipping_zone.shipping_methods.create(
+ name="DHL", type=ShippingMethodType.PRICE_BASED, shipping_zone=shipping_zone,
+ )
+ ShippingMethodChannelListing.objects.create(
+ channel=channel_USD,
+ currency=channel_USD.currency_code,
+ shipping_method=method,
+ minimum_order_price=Money(0, channel_USD.currency_code),
+ price=Money(10, channel_USD.currency_code),
)
return shipping_zone
@pytest.fixture
-def shipping_zones(db):
+def shipping_zones(db, channel_USD, channel_PLN):
shipping_zone_poland, shipping_zone_usa = ShippingZone.objects.bulk_create(
[
ShippingZone(name="Poland", countries=["PL"]),
ShippingZone(name="USA", countries=["US"]),
]
)
- shipping_zone_poland.shipping_methods.create(
- name="DHL",
- minimum_order_price=Money(0, "USD"),
- type=ShippingMethodType.PRICE_BASED,
- price=Money(10, "USD"),
- shipping_zone=shipping_zone,
+ method = shipping_zone_poland.shipping_methods.create(
+ name="DHL", type=ShippingMethodType.PRICE_BASED, shipping_zone=shipping_zone,
)
- shipping_zone_usa.shipping_methods.create(
- name="DHL",
- minimum_order_price=Money(0, "USD"),
- type=ShippingMethodType.PRICE_BASED,
- price=Money(10, "USD"),
- shipping_zone=shipping_zone,
+ second_method = shipping_zone_usa.shipping_methods.create(
+ name="DHL", type=ShippingMethodType.PRICE_BASED, shipping_zone=shipping_zone,
+ )
+ ShippingMethodChannelListing.objects.bulk_create(
+ [
+ ShippingMethodChannelListing(
+ channel=channel_USD,
+ shipping_method=method,
+ minimum_order_price=Money(0, "USD"),
+ price=Money(10, "USD"),
+ currency=channel_USD.currency_code,
+ ),
+ ShippingMethodChannelListing(
+ channel=channel_USD,
+ shipping_method=second_method,
+ minimum_order_price=Money(0, "USD"),
+ currency=channel_USD.currency_code,
+ ),
+ ShippingMethodChannelListing(
+ channel=channel_PLN,
+ shipping_method=method,
+ minimum_order_price=Money(0, "PLN"),
+ price=Money(40, "PLN"),
+ currency=channel_PLN.currency_code,
+ ),
+ ShippingMethodChannelListing(
+ channel=channel_PLN,
+ shipping_method=second_method,
+ minimum_order_price=Money(0, "PLN"),
+ currency=channel_PLN.currency_code,
+ ),
+ ]
)
return [shipping_zone_poland, shipping_zone_usa]
@pytest.fixture
-def shipping_zone_without_countries(db): # pylint: disable=W0613
+def shipping_zone_without_countries(db, channel_USD): # pylint: disable=W0613
shipping_zone = ShippingZone.objects.create(name="Europe", countries=[])
- shipping_zone.shipping_methods.create(
- name="DHL",
+ method = shipping_zone.shipping_methods.create(
+ name="DHL", type=ShippingMethodType.PRICE_BASED, shipping_zone=shipping_zone,
+ )
+ ShippingMethodChannelListing.objects.create(
+ channel=channel_USD,
+ shipping_method=method,
minimum_order_price=Money(0, "USD"),
- type=ShippingMethodType.PRICE_BASED,
price=Money(10, "USD"),
- shipping_zone=shipping_zone,
)
return shipping_zone
@pytest.fixture
-def shipping_method(shipping_zone):
- return ShippingMethod.objects.create(
- name="DHL",
+def shipping_method(shipping_zone, channel_USD):
+ method = ShippingMethod.objects.create(
+ name="DHL", type=ShippingMethodType.PRICE_BASED, shipping_zone=shipping_zone,
+ )
+ ShippingMethodChannelListing.objects.create(
+ shipping_method=method,
+ channel=channel_USD,
minimum_order_price=Money(0, "USD"),
- type=ShippingMethodType.PRICE_BASED,
price=Money(10, "USD"),
- shipping_zone=shipping_zone,
)
+ return method
+
+
+def shipping_method_channel_PLN(shipping_zone, channel_PLN):
+ method = ShippingMethod.objects.create(
+ name="DHL", type=ShippingMethodType.PRICE_BASED, shipping_zone=shipping_zone,
+ )
+ ShippingMethodChannelListing.objects.create(
+ shipping_method=method,
+ channel=channel_PLN,
+ minimum_order_price=Money(0, channel_PLN.currency_code),
+ price=Money(10, channel_PLN.currency_code),
+ currency=channel_PLN.currency_code,
+ )
+ return method
@pytest.fixture
@@ -668,7 +745,7 @@ def category_with_image(db, image, media_root): # pylint: disable=W0613
@pytest.fixture
-def categories_tree(db, product_type): # pylint: disable=W0613
+def categories_tree(db, product_type, channel_USD): # pylint: disable=W0613
parent = Category.objects.create(name="Parent", slug="parent")
parent.children.create(name="Child", slug="child")
child = parent.children.first()
@@ -681,6 +758,10 @@ def categories_tree(db, product_type): # pylint: disable=W0613
slug="test-product-10",
product_type=product_type,
category=child,
+ )
+ ProductChannelListing.objects.create(
+ product=product,
+ channel=channel_USD,
is_published=True,
visible_in_listings=True,
)
@@ -690,7 +771,9 @@ def categories_tree(db, product_type): # pylint: disable=W0613
@pytest.fixture
-def categories_tree_with_published_products(categories_tree, product):
+def categories_tree_with_published_products(
+ categories_tree, product, channel_USD, channel_PLN
+):
parent = categories_tree
parent_product = product
parent_product.category = parent
@@ -698,10 +781,29 @@ def categories_tree_with_published_products(categories_tree, product):
child = parent.children.first()
child_product = child.products.first()
- for product in [child_product, parent_product]:
- product.publication_date = datetime.date.today()
- product.is_published = True
+ product_list = [child_product, parent_product]
+
+ ProductChannelListing.objects.filter(product__in=product_list).delete()
+ product_channel_listings = []
+ for product in product_list:
product.save()
+ product_channel_listings.append(
+ ProductChannelListing(
+ product=product,
+ channel=channel_USD,
+ publication_date=datetime.date.today(),
+ is_published=True,
+ )
+ )
+ product_channel_listings.append(
+ ProductChannelListing(
+ product=product,
+ channel=channel_PLN,
+ publication_date=datetime.date.today(),
+ is_published=True,
+ )
+ )
+ ProductChannelListing.objects.bulk_create(product_channel_listings)
return parent
@@ -762,19 +864,25 @@ def product_type_without_variant():
@pytest.fixture
-def product(product_type, category, warehouse):
+def product(product_type, category, warehouse, channel_USD):
product_attr = product_type.product_attributes.first()
product_attr_value = product_attr.values.first()
product = Product.objects.create(
name="Test product",
slug="test-product-11",
- minimal_variant_price_amount=Decimal(10),
product_type=product_type,
category=category,
+ )
+
+ ProductChannelListing.objects.create(
+ product=product,
+ channel=channel_USD,
is_published=True,
- available_for_purchase=datetime.date(1999, 1, 1),
+ discounted_price_amount="10.00",
+ currency=channel_USD.currency_code,
visible_in_listings=True,
+ available_for_purchase=datetime.date(1999, 1, 1),
)
associate_attribute_values_to_instance(product, product_attr, product_attr_value)
@@ -782,11 +890,13 @@ def product(product_type, category, warehouse):
variant_attr = product_type.variant_attributes.first()
variant_attr_value = variant_attr.values.first()
- variant = ProductVariant.objects.create(
- product=product,
- sku="123",
- cost_price=Money("1.00", "USD"),
+ variant = ProductVariant.objects.create(product=product, sku="123")
+ ProductVariantChannelListing.objects.create(
+ variant=variant,
+ channel=channel_USD,
price_amount=Decimal(10),
+ cost_price_amount=Decimal(1),
+ currency=channel_USD.currency_code,
)
Stock.objects.create(warehouse=warehouse, product_variant=variant, quantity=10)
@@ -795,48 +905,80 @@ def product(product_type, category, warehouse):
@pytest.fixture
-def product_with_single_variant(product_type, category, warehouse):
+def product_available_in_many_channels(product, channel_PLN):
+ ProductChannelListing.objects.create(
+ product=product, channel=channel_PLN, is_published=True,
+ )
+ variant = product.variants.get()
+ ProductVariantChannelListing.objects.create(
+ variant=variant,
+ channel=channel_PLN,
+ price_amount=Decimal(50),
+ cost_price_amount=Decimal(1),
+ currency=channel_PLN.currency_code,
+ )
+ return product
+
+
+def product_with_single_variant(product_type, category, warehouse, channel_USD):
product = Product.objects.create(
name="Test product with single variant",
slug="test-product-with-single-variant",
product_type=product_type,
category=category,
+ )
+ ProductChannelListing.objects.create(
+ product=product,
+ channel=channel_USD,
is_published=True,
- available_for_purchase=datetime.date(1999, 1, 1),
visible_in_listings=True,
+ available_for_purchase=datetime.date(1999, 1, 1),
)
- variant = ProductVariant.objects.create(
- product=product,
- sku="SKU_SINGLE_VARIANT",
- cost_price=Money("1.00", "USD"),
- price_amount=1.99,
+ variant = ProductVariant.objects.create(product=product, sku="SKU_SINGLE_VARIANT")
+ ProductVariantChannelListing.objects.create(
+ variant=variant,
+ channel=channel_USD,
+ price_amount=Decimal(1.99),
+ cost_price_amount=Decimal(1),
+ currency=channel_USD.currency_code,
)
Stock.objects.create(product_variant=variant, warehouse=warehouse, quantity=101)
return product
@pytest.fixture
-def product_with_two_variants(product_type, category, warehouse):
+def product_with_two_variants(product_type, category, warehouse, channel_USD):
product = Product.objects.create(
name="Test product with two variants",
slug="test-product-with-two-variant",
product_type=product_type,
category=category,
+ )
+
+ ProductChannelListing.objects.create(
+ product=product,
+ channel=channel_USD,
is_published=True,
- available_for_purchase=datetime.date(1999, 1, 1),
visible_in_listings=True,
+ available_for_purchase=datetime.date(1999, 1, 1),
)
variants = [
- ProductVariant(
- product=product,
- sku=f"Product variant #{i}",
- cost_price=Money("1.00", "USD"),
+ ProductVariant(product=product, sku=f"Product variant #{i}",) for i in (1, 2)
+ ]
+ ProductVariant.objects.bulk_create(variants)
+ variants_channel_listing = [
+ ProductVariantChannelListing(
+ variant=variant,
+ channel=channel_USD,
price_amount=Decimal(10),
+ cost_price_amount=Decimal(1),
+ currency=channel_USD.currency_code,
)
- for i in (1, 2)
+ for variant in variants
]
- ProductVariant.objects.bulk_create(variants)
+ ProductVariantChannelListing.objects.bulk_create(variants_channel_listing)
Stock.objects.bulk_create(
[
Stock(warehouse=warehouse, product_variant=variant, quantity=10,)
@@ -849,7 +991,7 @@ def product_with_two_variants(product_type, category, warehouse):
@pytest.fixture
def product_with_variant_with_two_attributes(
- color_attribute, size_attribute, category, warehouse
+ color_attribute, size_attribute, category, warehouse, channel_USD
):
product_type = ProductType.objects.create(
name="Type with two variants",
@@ -865,16 +1007,23 @@ def product_with_variant_with_two_attributes(
slug="test-product-with-two-variant",
product_type=product_type,
category=category,
+ )
+ ProductChannelListing.objects.create(
+ product=product,
+ channel=channel_USD,
is_published=True,
- available_for_purchase=datetime.date(1999, 1, 1),
+ currency=channel_USD.currency_code,
visible_in_listings=True,
+ available_for_purchase=datetime.date(1999, 1, 1),
)
- variant = ProductVariant.objects.create(
- product=product,
- sku="prodVar1",
- cost_price=Money("1.00", "USD"),
+ variant = ProductVariant.objects.create(product=product, sku="prodVar1")
+ ProductVariantChannelListing.objects.create(
+ variant=variant,
+ channel=channel_USD,
price_amount=Decimal(10),
+ cost_price_amount=Decimal(1),
+ currency=channel_USD.currency_code,
)
associate_attribute_values_to_instance(
@@ -909,18 +1058,31 @@ def product_with_multiple_values_attributes(product, product_type, category) ->
@pytest.fixture
-def product_with_default_variant(product_type_without_variant, category, warehouse):
+def product_with_default_variant(
+ product_type_without_variant, category, warehouse, channel_USD
+):
product = Product.objects.create(
name="Test product",
slug="test-product-3",
product_type=product_type_without_variant,
category=category,
+ )
+ ProductChannelListing.objects.create(
+ product=product,
+ channel=channel_USD,
is_published=True,
- available_for_purchase=datetime.date(1999, 1, 1),
visible_in_listings=True,
+ available_for_purchase=datetime.date(1999, 1, 1),
)
variant = ProductVariant.objects.create(
- product=product, sku="1234", track_inventory=True, price_amount=Decimal(10)
+ product=product, sku="1234", track_inventory=True
+ )
+ ProductVariantChannelListing.objects.create(
+ variant=variant,
+ channel=channel_USD,
+ price_amount=Decimal(10),
+ cost_price_amount=Decimal(1),
+ currency=channel_USD.currency_code,
)
Stock.objects.create(warehouse=warehouse, product_variant=variant, quantity=100)
return product
@@ -928,35 +1090,44 @@ def product_with_default_variant(product_type_without_variant, category, warehou
@pytest.fixture
def variant_without_inventory_tracking(
- product_type_without_variant, category, warehouse
+ product_type_without_variant, category, warehouse, channel_USD
):
product = Product.objects.create(
name="Test product without inventory tracking",
slug="test-product-without-tracking",
product_type=product_type_without_variant,
category=category,
+ )
+ ProductChannelListing.objects.create(
+ product=product,
+ channel=channel_USD,
is_published=True,
- available_for_purchase=datetime.date.today(),
visible_in_listings=True,
+ available_for_purchase=datetime.date.today(),
)
variant = ProductVariant.objects.create(
- product=product,
- sku="tracking123",
- track_inventory=False,
+ product=product, sku="tracking123", track_inventory=False,
+ )
+ ProductVariantChannelListing.objects.create(
+ variant=variant,
+ channel=channel_USD,
price_amount=Decimal(10),
+ cost_price_amount=Decimal(1),
+ currency=channel_USD.currency_code,
)
Stock.objects.create(warehouse=warehouse, product_variant=variant, quantity=0)
return variant
@pytest.fixture
-def variant(product) -> ProductVariant:
- product_variant = ProductVariant.objects.create(
- product=product,
- sku="SKU_A",
- cost_price=Money(1, "USD"),
+def variant(product, channel_USD) -> ProductVariant:
+ product_variant = ProductVariant.objects.create(product=product, sku="SKU_A")
+ ProductVariantChannelListing.objects.create(
+ variant=product_variant,
+ channel=channel_USD,
price_amount=Decimal(10),
- price=Money(10, "USD"),
+ cost_price_amount=Decimal(1),
+ currency=channel_USD.currency_code,
)
return product_variant
@@ -988,20 +1159,46 @@ def variant_with_many_stocks_different_shipping_zones(
@pytest.fixture
-def product_variant_list(product):
- return list(
+def product_variant_list(product, channel_USD):
+ variants = list(
ProductVariant.objects.bulk_create(
[
- ProductVariant(product=product, sku="1", price_amount=Decimal(10)),
- ProductVariant(product=product, sku="2", price_amount=Decimal(10)),
- ProductVariant(product=product, sku="3", price_amount=Decimal(10)),
+ ProductVariant(product=product, sku="1"),
+ ProductVariant(product=product, sku="2"),
+ ProductVariant(product=product, sku="3"),
]
)
)
+ ProductVariantChannelListing.objects.bulk_create(
+ [
+ ProductVariantChannelListing(
+ variant=variants[0],
+ channel=channel_USD,
+ cost_price_amount=Decimal(1),
+ price_amount=Decimal(10),
+ currency=channel_USD.currency_code,
+ ),
+ ProductVariantChannelListing(
+ variant=variants[1],
+ channel=channel_USD,
+ cost_price_amount=Decimal(1),
+ price_amount=Decimal(10),
+ currency=channel_USD.currency_code,
+ ),
+ ProductVariantChannelListing(
+ variant=variants[2],
+ channel=channel_USD,
+ cost_price_amount=Decimal(1),
+ price_amount=Decimal(10),
+ currency=channel_USD.currency_code,
+ ),
+ ]
+ )
+ return variants
@pytest.fixture
-def product_without_shipping(category, warehouse):
+def product_without_shipping(category, warehouse, channel_USD):
product_type = ProductType.objects.create(
name="Type with no shipping",
slug="no-shipping",
@@ -1013,11 +1210,20 @@ def product_without_shipping(category, warehouse):
slug="test-product-4",
product_type=product_type,
category=category,
+ )
+ ProductChannelListing.objects.create(
+ product=product,
+ channel=channel_USD,
is_published=True,
visible_in_listings=True,
)
- variant = ProductVariant.objects.create(
- product=product, sku="SKU_B", price_amount=Decimal(10)
+ variant = ProductVariant.objects.create(product=product, sku="SKU_B")
+ ProductVariantChannelListing.objects.create(
+ variant=variant,
+ channel=channel_USD,
+ price_amount=Decimal(10),
+ cost_price_amount=Decimal(1),
+ currency=channel_USD.currency_code,
)
Stock.objects.create(product_variant=variant, warehouse=warehouse, quantity=1)
return product
@@ -1026,13 +1232,13 @@ def product_without_shipping(category, warehouse):
@pytest.fixture
def product_without_category(product):
product.category = None
- product.is_published = False
product.save()
+ product.channel_listings.all().update(is_published=False)
return product
@pytest.fixture
-def product_list(product_type, category, warehouse):
+def product_list(product_type, category, warehouse, channel_USD, channel_PLN):
product_attr = product_type.product_attributes.first()
attr_value = product_attr.values.first()
@@ -1045,8 +1251,6 @@ def product_list(product_type, category, warehouse):
slug="test-product-a",
category=category,
product_type=product_type,
- is_published=True,
- visible_in_listings=True,
),
Product(
pk=1487,
@@ -1054,8 +1258,6 @@ def product_list(product_type, category, warehouse):
slug="test-product-b",
category=category,
product_type=product_type,
- is_published=True,
- visible_in_listings=True,
),
Product(
pk=1489,
@@ -1063,12 +1265,38 @@ def product_list(product_type, category, warehouse):
slug="test-product-c",
category=category,
product_type=product_type,
- is_published=True,
- visible_in_listings=True,
),
]
)
)
+ ProductChannelListing.objects.bulk_create(
+ [
+ ProductChannelListing(
+ product=products[0],
+ channel=channel_USD,
+ is_published=True,
+ discounted_price_amount=10,
+ currency=channel_USD.currency_code,
+ visible_in_listings=True,
+ ),
+ ProductChannelListing(
+ product=products[1],
+ channel=channel_USD,
+ is_published=True,
+ discounted_price_amount=20,
+ currency=channel_USD.currency_code,
+ visible_in_listings=True,
+ ),
+ ProductChannelListing(
+ product=products[2],
+ channel=channel_USD,
+ is_published=True,
+ discounted_price_amount=30,
+ currency=channel_USD.currency_code,
+ visible_in_listings=True,
+ ),
+ ]
+ )
variants = list(
ProductVariant.objects.bulk_create(
[
@@ -1076,23 +1304,45 @@ def product_list(product_type, category, warehouse):
product=products[0],
sku=str(uuid.uuid4()).replace("-", ""),
track_inventory=True,
- price_amount=Decimal(10),
),
ProductVariant(
product=products[1],
sku=str(uuid.uuid4()).replace("-", ""),
track_inventory=True,
- price_amount=Decimal(20),
),
ProductVariant(
product=products[2],
sku=str(uuid.uuid4()).replace("-", ""),
track_inventory=True,
- price_amount=Decimal(30),
),
]
)
)
+ ProductVariantChannelListing.objects.bulk_create(
+ [
+ ProductVariantChannelListing(
+ variant=variants[0],
+ channel=channel_USD,
+ cost_price_amount=Decimal(1),
+ price_amount=Decimal(10),
+ currency=channel_USD.currency_code,
+ ),
+ ProductVariantChannelListing(
+ variant=variants[1],
+ channel=channel_USD,
+ cost_price_amount=Decimal(1),
+ price_amount=Decimal(20),
+ currency=channel_USD.currency_code,
+ ),
+ ProductVariantChannelListing(
+ variant=variants[2],
+ channel=channel_USD,
+ cost_price_amount=Decimal(1),
+ price_amount=Decimal(30),
+ currency=channel_USD.currency_code,
+ ),
+ ]
+ )
stocks = []
for variant in variants:
stocks.append(Stock(warehouse=warehouse, product_variant=variant, quantity=100))
@@ -1105,26 +1355,157 @@ def product_list(product_type, category, warehouse):
@pytest.fixture
-def product_list_unpublished(product_list):
+def product_list_with_variants_many_channel(
+ product_type, category, channel_USD, channel_PLN
+):
+ products = list(
+ Product.objects.bulk_create(
+ [
+ Product(
+ pk=1486,
+ name="Test product 1",
+ slug="test-product-a",
+ category=category,
+ product_type=product_type,
+ ),
+ Product(
+ pk=1487,
+ name="Test product 2",
+ slug="test-product-b",
+ category=category,
+ product_type=product_type,
+ ),
+ Product(
+ pk=1489,
+ name="Test product 3",
+ slug="test-product-c",
+ category=category,
+ product_type=product_type,
+ ),
+ ]
+ )
+ )
+ ProductChannelListing.objects.bulk_create(
+ [
+ # Channel: USD
+ ProductChannelListing(
+ product=products[0],
+ channel=channel_USD,
+ is_published=True,
+ currency=channel_USD.currency_code,
+ visible_in_listings=True,
+ ),
+ # Channel: PLN
+ ProductChannelListing(
+ product=products[1],
+ channel=channel_PLN,
+ is_published=True,
+ currency=channel_PLN.currency_code,
+ visible_in_listings=True,
+ ),
+ ProductChannelListing(
+ product=products[2],
+ channel=channel_PLN,
+ is_published=True,
+ currency=channel_PLN.currency_code,
+ visible_in_listings=True,
+ ),
+ ]
+ )
+ variants = list(
+ ProductVariant.objects.bulk_create(
+ [
+ ProductVariant(
+ product=products[0],
+ sku=str(uuid.uuid4()).replace("-", ""),
+ track_inventory=True,
+ ),
+ ProductVariant(
+ product=products[1],
+ sku=str(uuid.uuid4()).replace("-", ""),
+ track_inventory=True,
+ ),
+ ProductVariant(
+ product=products[2],
+ sku=str(uuid.uuid4()).replace("-", ""),
+ track_inventory=True,
+ ),
+ ]
+ )
+ )
+ ProductVariantChannelListing.objects.bulk_create(
+ [
+ # Channel: USD
+ ProductVariantChannelListing(
+ variant=variants[0],
+ channel=channel_USD,
+ cost_price_amount=Decimal(1),
+ price_amount=Decimal(10),
+ currency=channel_USD.currency_code,
+ ),
+ # Channel: PLN
+ ProductVariantChannelListing(
+ variant=variants[1],
+ channel=channel_PLN,
+ cost_price_amount=Decimal(1),
+ price_amount=Decimal(20),
+ currency=channel_PLN.currency_code,
+ ),
+ ProductVariantChannelListing(
+ variant=variants[2],
+ channel=channel_PLN,
+ cost_price_amount=Decimal(1),
+ price_amount=Decimal(30),
+ currency=channel_PLN.currency_code,
+ ),
+ ]
+ )
+
+
+def product_list_with_many_channels(product_list, channel_PLN):
+ ProductChannelListing.objects.bulk_create(
+ [
+ ProductChannelListing(
+ product=product_list[0], channel=channel_PLN, is_published=True,
+ ),
+ ProductChannelListing(
+ product=product_list[1], channel=channel_PLN, is_published=True,
+ ),
+ ProductChannelListing(
+ product=product_list[2], channel=channel_PLN, is_published=True,
+ ),
+ ]
+ )
+ return product_list
+
+
+def product_list_unpublished(product_list, channel_USD):
products = Product.objects.filter(pk__in=[product.pk for product in product_list])
- products.update(is_published=False)
+ ProductChannelListing.objects.filter(
+ product__in=products, channel=channel_USD
+ ).update(is_published=False)
return products
@pytest.fixture
-def product_list_published(product_list):
+def product_list_published(product_list, channel_USD):
products = Product.objects.filter(pk__in=[product.pk for product in product_list])
- products.update(is_published=True)
+ ProductChannelListing.objects.filter(
+ product__in=products, channel=channel_USD
+ ).update(is_published=True)
return products
@pytest.fixture
-def order_list(customer_user):
+def order_list(customer_user, channel_USD):
address = customer_user.default_billing_address.get_copy()
data = {
"billing_address": address,
"user": customer_user,
"user_email": customer_user.email,
+ "channel": channel_USD,
}
order = Order.objects.create(**data)
order1 = Order.objects.create(**data)
@@ -1140,34 +1521,47 @@ def product_with_image(product, image, media_root):
@pytest.fixture
-def unavailable_product(product_type, category):
+def unavailable_product(product_type, category, channel_USD):
product = Product.objects.create(
name="Test product",
slug="test-product-5",
product_type=product_type,
- is_published=False,
category=category,
+ )
+ ProductChannelListing.objects.create(
+ product=product,
+ channel=channel_USD,
+ is_published=False,
visible_in_listings=False,
)
return product
@pytest.fixture
-def unavailable_product_with_variant(product_type, category, warehouse):
+def unavailable_product_with_variant(product_type, category, warehouse, channel_USD):
product = Product.objects.create(
name="Test product",
slug="test-product-6",
product_type=product_type,
+ category=category,
+ )
+ ProductChannelListing.objects.create(
+ product=product,
+ channel=channel_USD,
is_published=False,
visible_in_listings=False,
- category=category,
)
variant_attr = product_type.variant_attributes.first()
variant_attr_value = variant_attr.values.first()
- variant = ProductVariant.objects.create(
- product=product, sku="123", cost_price=Money(1, "USD"), price_amount=Decimal(10)
+ variant = ProductVariant.objects.create(product=product, sku="123",)
+ ProductVariantChannelListing.objects.create(
+ variant=variant,
+ channel=channel_USD,
+ price_amount=Decimal(10),
+ cost_price_amount=Decimal(1),
+ currency=channel_USD.currency_code,
)
Stock.objects.create(product_variant=variant, warehouse=warehouse, quantity=10)
@@ -1176,12 +1570,16 @@ def unavailable_product_with_variant(product_type, category, warehouse):
@pytest.fixture
-def product_with_images(product_type, category, media_root):
+def product_with_images(product_type, category, media_root, channel_USD):
product = Product.objects.create(
name="Test product",
slug="test-product-7",
product_type=product_type,
category=category,
+ )
+ ProductChannelListing.objects.create(
+ product=product,
+ channel=channel_USD,
is_published=True,
visible_in_listings=True,
)
@@ -1195,17 +1593,42 @@ def product_with_images(product_type, category, media_root):
@pytest.fixture
-def voucher(db): # pylint: disable=W0613
- return Voucher.objects.create(code="mirumee", discount_value=20)
+def voucher_without_channel(db):
+ return Voucher.objects.create(code="mirumee")
+
+
+def voucher(voucher_without_channel, channel_USD):
+ VoucherChannelListing.objects.create(
+ voucher=voucher_without_channel,
+ channel=channel_USD,
+ discount=Money(20, channel_USD.currency_code),
+ )
+ return voucher_without_channel
@pytest.fixture
-def voucher_percentage(db):
- return Voucher.objects.create(
- code="mirumee",
+def voucher_with_many_channels(voucher, channel_PLN):
+ VoucherChannelListing.objects.create(
+ voucher=voucher,
+ channel=channel_PLN,
+ discount=Money(80, channel_PLN.currency_code),
+ )
+ return voucher
+
+
+def voucher_percentage(channel_USD):
+ voucher = Voucher.objects.create(
+ code="saleor", discount_value_type=DiscountValueType.PERCENTAGE,
+ )
+ VoucherChannelListing.objects.create(
+ voucher=voucher,
+ channel=channel_USD,
discount_value=10,
- discount_value_type=DiscountValueType.PERCENTAGE,
+ currency=channel_USD.currency_code,
)
+ return voucher
@pytest.fixture
@@ -1216,24 +1639,38 @@ def voucher_specific_product_type(voucher_percentage):
@pytest.fixture
-def voucher_with_high_min_spent_amount():
- return Voucher.objects.create(
- code="mirumee", discount_value=10, min_spent=Money(1_000_000, "USD")
+def voucher_with_high_min_spent_amount(channel_USD):
+ voucher = Voucher.objects.create(code="mirumee")
+ VoucherChannelListing.objects.create(
+ voucher=voucher,
+ channel=channel_USD,
+ discount=Money(10, channel_USD.currency_code),
+ min_spent_amount=1_000_000,
)
+ return voucher
@pytest.fixture
-def voucher_shipping_type():
- return Voucher.objects.create(
- code="mirumee", discount_value=10, type=VoucherType.SHIPPING, countries="IS"
+def voucher_shipping_type(channel_USD):
+ voucher = Voucher.objects.create(
+ code="mirumee", type=VoucherType.SHIPPING, countries="IS"
+ )
+ VoucherChannelListing.objects.create(
+ voucher=voucher,
+ channel=channel_USD,
+ discount=Money(10, channel_USD.currency_code),
)
+ return voucher
@pytest.fixture
-def voucher_free_shipping(voucher_percentage):
+def voucher_free_shipping(voucher_percentage, channel_USD):
voucher_percentage.type = VoucherType.SHIPPING
- voucher_percentage.discount_value = 100
+ voucher_percentage.name = "Free shipping"
voucher_percentage.save()
+ voucher_percentage.channel_listings.filter(channel=channel_USD).update(
+ discount_value=100
+ )
return voucher_percentage
@@ -1245,7 +1682,8 @@ def voucher_customer(voucher, customer_user):
@pytest.fixture
def order_line(order, variant):
- net = variant.get_price()
+ channel_slug = order.channel.slug
+ net = variant.get_price(channel_slug)
gross = Money(amount=net.amount * Decimal(1.23), currency=net.currency)
return order.lines.create(
product_name=str(variant.product),
@@ -1260,16 +1698,22 @@ def order_line(order, variant):
@pytest.fixture
-def order_line_with_allocation_in_many_stocks(customer_user, variant_with_many_stocks):
+def order_line_with_allocation_in_many_stocks(
+ customer_user, variant_with_many_stocks, channel_USD
+):
address = customer_user.default_billing_address.get_copy()
variant = variant_with_many_stocks
stocks = variant.stocks.all().order_by("pk")
order = Order.objects.create(
- billing_address=address, user_email=customer_user.email, user=customer_user
+ billing_address=address,
+ user_email=customer_user.email,
+ user=customer_user,
+ channel=channel_USD,
)
- net = variant.get_price()
+ channel_slug = order.channel.slug
+ net = variant.get_price(channel_slug)
gross = Money(amount=net.amount * Decimal(1.23), currency=net.currency)
order_line = order.lines.create(
product_name=str(variant.product),
@@ -1293,16 +1737,21 @@ def order_line_with_allocation_in_many_stocks(customer_user, variant_with_many_s
@pytest.fixture
-def order_line_with_one_allocation(customer_user, variant_with_many_stocks):
+def order_line_with_one_allocation(
+ customer_user, variant_with_many_stocks, channel_USD
+):
address = customer_user.default_billing_address.get_copy()
variant = variant_with_many_stocks
stocks = variant.stocks.all().order_by("pk")
order = Order.objects.create(
- billing_address=address, user_email=customer_user.email, user=customer_user
+ billing_address=address,
+ user_email=customer_user.email,
+ user=customer_user,
+ channel=channel_USD,
)
- net = variant.get_price()
+ net = variant.get_price(order.channel.slug)
gross = Money(amount=net.amount * Decimal(1.23), currency=net.currency)
order_line = order.lines.create(
product_name=str(variant.product),
@@ -1351,26 +1800,34 @@ def gift_card_created_by_staff(staff_user):
@pytest.fixture
-def order_with_lines(order, product_type, category, shipping_zone, warehouse):
+def order_with_lines(
+ order, product_type, category, shipping_zone, warehouse, channel_USD
+):
product = Product.objects.create(
name="Test product",
slug="test-product-8",
product_type=product_type,
category=category,
+ )
+ ProductChannelListing.objects.create(
+ product=product,
+ channel=channel_USD,
is_published=True,
- available_for_purchase=datetime.date.today(),
visible_in_listings=True,
+ available_for_purchase=datetime.date.today(),
)
- variant = ProductVariant.objects.create(
- product=product,
- sku="SKU_A",
- cost_price=Money(1, "USD"),
+ variant = ProductVariant.objects.create(product=product, sku="SKU_AA")
+ ProductVariantChannelListing.objects.create(
+ variant=variant,
+ channel=channel_USD,
price_amount=Decimal(10),
+ cost_price_amount=Decimal(1),
+ currency=channel_USD.currency_code,
)
stock = Stock.objects.create(
warehouse=warehouse, product_variant=variant, quantity=5
)
- net = variant.get_price()
+ net = variant.get_price(channel_USD.slug)
gross = Money(amount=net.amount * Decimal(1.23), currency=net.currency)
line = order.lines.create(
product_name=str(variant.product),
@@ -1391,18 +1848,143 @@ def order_with_lines(order, product_type, category, shipping_zone, warehouse):
slug="test-product-9",
product_type=product_type,
category=category,
+ )
+ ProductChannelListing.objects.create(
+ product=product,
+ channel=channel_USD,
is_published=True,
+ visible_in_listings=True,
available_for_purchase=datetime.date.today(),
+ )
+ variant = ProductVariant.objects.create(product=product, sku="SKU_B")
+ ProductVariantChannelListing.objects.create(
+ variant=variant,
+ channel=channel_USD,
+ price_amount=Decimal(20),
+ cost_price_amount=Decimal(2),
+ currency=channel_USD.currency_code,
+ )
+ stock = Stock.objects.create(
+ product_variant=variant, warehouse=warehouse, quantity=2
+ )
+
+ net = variant.get_price(channel_USD.slug)
+ gross = Money(amount=net.amount * Decimal(1.23), currency=net.currency)
+ line = order.lines.create(
+ product_name=str(variant.product),
+ variant_name=str(variant),
+ product_sku=variant.sku,
+ is_shipping_required=variant.is_shipping_required(),
+ quantity=2,
+ variant=variant,
+ unit_price=TaxedMoney(net=net, gross=gross),
+ tax_rate=23,
+ )
+ Allocation.objects.create(
+ order_line=line, stock=stock, quantity_allocated=line.quantity
+ )
+
+ order.shipping_address = order.billing_address.get_copy()
+ order.channel = channel_USD
+ shipping_method = shipping_zone.shipping_methods.first()
+ shipping_price = shipping_method.channel_listings.get(channel_id=channel_USD.id)
+ order.shipping_method_name = shipping_method.name
+ order.shipping_method = shipping_method
+
+ net = shipping_price.get_total()
+ gross = Money(amount=net.amount * Decimal(1.23), currency=net.currency)
+ order.shipping_price = TaxedMoney(net=net, gross=gross)
+ order.save()
+
+ recalculate_order(order)
+
+ order.refresh_from_db()
+ return order
+
+
+def order_with_lines_channel_PLN(
+ customer_user,
+ product_type,
+ category,
+ shipping_method_channel_PLN,
+ warehouse,
+ channel_PLN,
+):
+ address = customer_user.default_billing_address.get_copy()
+ order = Order.objects.create(
+ billing_address=address,
+ channel=channel_PLN,
+ shipping_address=address,
+ user_email=customer_user.email,
+ user=customer_user,
+ )
+ product = Product.objects.create(
+ name="Test product in PLN channel",
+ slug="test-product-8-pln",
+ product_type=product_type,
+ category=category,
+ )
+ ProductChannelListing.objects.create(
+ product=product,
+ channel=channel_PLN,
+ is_published=True,
visible_in_listings=True,
+ available_for_purchase=datetime.date.today(),
)
- variant = ProductVariant.objects.create(
- product=product, sku="SKU_B", cost_price=Money(2, "USD"), price_amount=20
+ variant = ProductVariant.objects.create(product=product, sku="SKU_A_PLN")
+ ProductVariantChannelListing.objects.create(
+ variant=variant,
+ channel=channel_PLN,
+ price_amount=Decimal(10),
+ cost_price_amount=Decimal(1),
+ currency=channel_PLN.currency_code,
+ )
+ stock = Stock.objects.create(
+ warehouse=warehouse, product_variant=variant, quantity=5
+ )
+ net = variant.get_price(channel_PLN.slug)
+ gross = Money(amount=net.amount * Decimal(1.23), currency=net.currency)
+ line = order.lines.create(
+ product_name=str(variant.product),
+ variant_name=str(variant),
+ product_sku=variant.sku,
+ is_shipping_required=variant.is_shipping_required(),
+ quantity=3,
+ variant=variant,
+ unit_price=TaxedMoney(net=net, gross=gross),
+ tax_rate=23,
+ )
+ Allocation.objects.create(
+ order_line=line, stock=stock, quantity_allocated=line.quantity
+ )
+
+ product = Product.objects.create(
+ name="Test product 2 in PLN channel",
+ slug="test-product-9-pln",
+ product_type=product_type,
+ category=category,
+ )
+ ProductChannelListing.objects.create(
+ product=product,
+ channel=channel_PLN,
+ is_published=True,
+ visible_in_listings=True,
+ available_for_purchase=datetime.date.today(),
+ )
+ variant = ProductVariant.objects.create(product=product, sku="SKU_B_PLN")
+ ProductVariantChannelListing.objects.create(
+ variant=variant,
+ channel=channel_PLN,
+ price_amount=Decimal(20),
+ cost_price_amount=Decimal(2),
+ currency=channel_PLN.currency_code,
)
stock = Stock.objects.create(
product_variant=variant, warehouse=warehouse, quantity=2
)
- net = variant.get_price()
+ net = variant.get_price(channel_PLN.slug)
gross = Money(amount=net.amount * Decimal(1.23), currency=net.currency)
line = order.lines.create(
product_name=str(variant.product),
@@ -1419,11 +2001,13 @@ def order_with_lines(order, product_type, category, shipping_zone, warehouse):
)
order.shipping_address = order.billing_address.get_copy()
- method = shipping_zone.shipping_methods.first()
- order.shipping_method_name = method.name
- order.shipping_method = method
+ order.channel = channel_PLN
+ shipping_method = shipping_method_channel_PLN
+ shipping_price = shipping_method.channel_listings.get(channel_id=channel_PLN.id,)
+ order.shipping_method_name = shipping_method.name
+ order.shipping_method = shipping_method
- net = method.get_total()
+ net = shipping_price.get_total()
gross = Money(amount=net.amount * Decimal(1.23), currency=net.currency)
order.shipping_price = TaxedMoney(net=net, gross=gross)
order.save()
@@ -1439,7 +2023,7 @@ def order_with_line_without_inventory_tracking(
order, variant_without_inventory_tracking
):
variant = variant_without_inventory_tracking
- net = variant.get_price()
+ net = variant.get_price(order.channel.slug)
gross = Money(amount=net.amount * Decimal(1.23), currency=net.currency)
line = order.lines.create(
product_name=str(variant.product),
@@ -1555,6 +2139,7 @@ def payment_txn_preauth(order_with_lines, payment_dummy):
payment.transactions.create(
amount=payment.total,
+ currency=payment.currency,
kind=TransactionKind.AUTH,
gateway_response={},
is_success=True,
@@ -1573,6 +2158,7 @@ def payment_txn_captured(order_with_lines, payment_dummy):
payment.transactions.create(
amount=payment.total,
+ currency=payment.currency,
kind=TransactionKind.CAPTURE,
gateway_response={},
is_success=True,
@@ -1590,6 +2176,7 @@ def payment_txn_to_confirm(order_with_lines, payment_dummy):
payment.transactions.create(
amount=payment.total,
+ currency=payment.currency,
kind=TransactionKind.ACTION_TO_CONFIRM,
gateway_response={},
is_success=True,
@@ -1609,6 +2196,7 @@ def payment_txn_refunded(order_with_lines, payment_dummy):
payment.transactions.create(
amount=payment.total,
+ currency=payment.currency,
kind=TransactionKind.REFUND,
gateway_response={},
is_success=True,
@@ -1649,8 +2237,47 @@ def dummy_payment_data(payment_dummy):
@pytest.fixture
-def sale(product, category, collection):
- sale = Sale.objects.create(name="Sale", value=5)
+def new_sale(category, channel_USD):
+ sale = Sale.objects.create(name="Sale")
+ SaleChannelListing.objects.create(
+ sale=sale,
+ channel=channel_USD,
+ discount_value=5,
+ currency=channel_USD.currency_code,
+ )
+ return sale
+
+
+def sale(product, category, collection, channel_USD):
+ sale = Sale.objects.create(name="Sale")
+ SaleChannelListing.objects.create(
+ sale=sale,
+ channel=channel_USD,
+ discount_value=5,
+ currency=channel_USD.currency_code,
+ )
+ sale.products.add(product)
+ sale.categories.add(category)
+ sale.collections.add(collection)
+ return sale
+
+
+def sale_with_many_channels(product, category, collection, channel_USD, channel_PLN):
+ sale = Sale.objects.create(name="Sale")
+ SaleChannelListing.objects.create(
+ sale=sale,
+ channel=channel_USD,
+ discount_value=5,
+ currency=channel_USD.currency_code,
+ )
+ SaleChannelListing.objects.create(
+ sale=sale,
+ channel=channel_PLN,
+ discount_value=5,
+ currency=channel_PLN.currency_code,
+ )
sale.products.add(product)
sale.categories.add(category)
sale.collections.add(collection)
@@ -1658,9 +2285,12 @@ def sale(product, category, collection):
@pytest.fixture
-def discount_info(category, collection, sale):
+def discount_info(category, collection, sale, channel_USD):
+ sale_channel_listing = sale.channel_listings.get(channel=channel_USD)
+
return DiscountInfo(
sale=sale,
+ channel_listings={channel_USD.slug: sale_channel_listing},
product_ids=set(),
category_ids={category.id}, # assumes this category does not have children
collection_ids={collection.id},
@@ -1727,6 +2357,16 @@ def permission_manage_translations():
return Permission.objects.get(codename="manage_translations")
+def permission_manage_webhooks():
+ return Permission.objects.get(codename="manage_webhooks")
+
+
+def permission_manage_channels():
+ return Permission.objects.get(codename="manage_channels")
+
+
@pytest.fixture
def permission_group_manage_users(permission_manage_users, staff_users):
group = Group.objects.create(name="Manage user groups.")
@@ -1739,39 +2379,98 @@ def permission_group_manage_users(permission_manage_users, staff_users):
@pytest.fixture
def collection(db):
collection = Collection.objects.create(
- name="Collection",
- slug="collection",
+ name="Collection", slug="collection", description="Test description",
+ )
+ return collection
+
+
+def published_collection(db, channel_USD):
+ collection = Collection.objects.create(
+ name="Collection USD", slug="collection-usd", description="Test description",
+ )
+ CollectionChannelListing.objects.create(
+ channel=channel_USD,
+ collection=collection,
is_published=True,
+ publication_date=datetime.date.today(),
+ )
+ return collection
+
+
+def published_collection_PLN(db, channel_PLN):
+ collection = Collection.objects.create(
+ name="Collection PLN", slug="collection-pln", description="Test description",
+ )
+ CollectionChannelListing.objects.create(
+ channel=channel_PLN,
+ collection=collection,
+ is_published=True,
+ publication_date=datetime.date.today(),
+ )
+ return collection
+
+
+def unpublished_collection(db, channel_USD):
+ collection = Collection.objects.create(
+ name="Unpublished Collection",
+ slug="unpublished-collection",
description="Test description",
)
+ CollectionChannelListing.objects.create(
+ channel=channel_USD, collection=collection, is_published=False
+ )
return collection
@pytest.fixture
-def collection_with_products(db, collection, product_list_published):
- collection.products.set(list(product_list_published))
+def unpublished_collection_PLN(db, channel_PLN):
+ collection = Collection.objects.create(
+ name="Collection", slug="collection", description="Test description",
+ )
+ CollectionChannelListing.objects.create(
+ channel=channel_PLN, collection=collection, is_published=False
+ )
+ return collection
+
+
+def collection_with_products(db, published_collection, product_list_published):
+ published_collection.products.set(list(product_list_published))
return product_list_published
@pytest.fixture
-def collection_with_image(db, image, media_root):
+def collection_with_image(db, image, media_root, channel_USD):
collection = Collection.objects.create(
name="Collection",
slug="collection",
description="Test description",
background_image=image,
- is_published=True,
+ )
+ CollectionChannelListing.objects.create(
+ channel=channel_USD, collection=collection, is_published=False
)
return collection
@pytest.fixture
-def collection_list(db):
+def collection_list(db, channel_USD):
collections = Collection.objects.bulk_create(
[
- Collection(name="Collection 1", slug="collection-1", is_published="True"),
- Collection(name="Collection 2", slug="collection-2", is_published="True"),
- Collection(name="Collection 3", slug="collection-3", is_published="True"),
+ Collection(name="Collection 1", slug="collection-1"),
+ Collection(name="Collection 2", slug="collection-2"),
+ Collection(name="Collection 3", slug="collection-3"),
+ ]
+ )
+ CollectionChannelListing.objects.bulk_create(
+ [
+ CollectionChannelListing(
+ channel=channel_USD, collection=collection, is_published=True
+ )
+ for collection in collections
]
)
return collections
@@ -1794,14 +2493,6 @@ def draft_collection(db):
return collection
-def unpublished_collection():
- collection = Collection.objects.create(
- name="Unpublished collection", slug="unpublished-collection", is_published=False
- )
- return collection
-
-
@pytest.fixture
def page(db):
data = {
@@ -1930,10 +2621,10 @@ def variant_translation_fr(variant):
@pytest.fixture
-def collection_translation_fr(collection):
+def collection_translation_fr(published_collection):
return CollectionTranslation.objects.create(
language_code="fr",
- collection=collection,
+ collection=published_collection,
name="French collection name",
description="French description",
)
@@ -1994,7 +2685,7 @@ def payment_dummy(db, order_with_lines):
cc_exp_month=12,
cc_exp_year=2027,
total=order_with_lines.total.gross.amount,
- currency=order_with_lines.total.gross.currency,
+ currency=order_with_lines.currency,
billing_first_name=order_with_lines.billing_address.first_name,
billing_last_name=order_with_lines.billing_address.last_name,
billing_company_name=order_with_lines.billing_address.company_name,
@@ -2035,7 +2726,7 @@ def payment_dummy_credit_card(db, order_with_lines):
@pytest.fixture
-def digital_content(category, media_root, warehouse) -> DigitalContent:
+def digital_content(category, media_root, warehouse, channel_USD) -> DigitalContent:
product_type = ProductType.objects.create(
name="Digital Type",
slug="digital-type",
@@ -2048,15 +2739,21 @@ def digital_content(category, media_root, warehouse) -> DigitalContent:
slug="test-digital-product",
product_type=product_type,
category=category,
+ )
+ ProductChannelListing.objects.create(
+ product=product,
+ channel=channel_USD,
is_published=True,
- available_for_purchase=datetime.date(1999, 1, 1),
visible_in_listings=True,
+ available_for_purchase=datetime.date(1999, 1, 1),
)
- product_variant = ProductVariant.objects.create(
- product=product,
- sku="SKU_554",
- cost_price=Money(1, "USD"),
+ product_variant = ProductVariant.objects.create(product=product, sku="SKU_554")
+ ProductVariantChannelListing.objects.create(
+ variant=product_variant,
+ channel=channel_USD,
price_amount=Decimal(10),
+ cost_price_amount=Decimal(1),
+ currency=channel_USD.currency_code,
)
Stock.objects.create(
product_variant=product_variant, warehouse=warehouse, quantity=5,
@@ -2348,9 +3045,9 @@ def allocation(order_line, stock):
@pytest.fixture
-def allocations(order_list, stock):
+def allocations(order_list, stock, channel_USD):
variant = stock.product_variant
- net = variant.get_price()
+ net = variant.get_price(channel_USD)
gross = Money(amount=net.amount * Decimal(1.23), currency=net.currency)
lines = OrderLine.objects.bulk_create(
[
diff --git a/saleor/tests/settings.py b/saleor/tests/settings.py
index c6e7d84494..38a85b8121 100644
--- a/saleor/tests/settings.py
+++ b/saleor/tests/settings.py
@@ -55,3 +55,5 @@ PATTERNS_IGNORED_IN_QUERY_CAPTURES: List[Union[Pattern, SimpleLazyObject]] = [
INSTALLED_APPS.append("saleor.tests") # noqa: F405
JWT_EXPIRE = True
+
+DEFAULT_CHANNEL_SLUG = "main"
diff --git a/saleor/urls.py b/saleor/urls.py
index 179be8baff..6566970fb4 100644
--- a/saleor/urls.py
+++ b/saleor/urls.py
@@ -4,7 +4,6 @@ from django.conf.urls.static import static
from django.contrib.staticfiles.views import serve
from django.views.decorators.csrf import csrf_exempt
-from .data_feeds.urls import urlpatterns as feed_urls
from .graphql.api import schema
from .graphql.views import GraphQLView
from .plugins.views import handle_plugin_webhook
@@ -12,7 +11,6 @@ from .product.views import digital_product
urlpatterns = [
url(r"^graphql/", csrf_exempt(GraphQLView.as_view(schema=schema)), name="api"),
- url(r"^feeds/", include((feed_urls, "data_feeds"), namespace="data_feeds")),
url(
r"^digital-download/(?P<token>[0-9A-Za-z_\-]+)/$",
digital_product,
@@ -38,7 +36,9 @@ if settings.DEBUG:
settings.py should already have warned the user about it."
)
else:
- urlpatterns += [url(r"^__debug__/", include(debug_toolbar.urls))]
+ urlpatterns += [
+ url(r"^__debug__/", include(debug_toolbar.urls)) # type: ignore
+ ]
urlpatterns += static("/media/", document_root=settings.MEDIA_ROOT) + [
url(r"^static/(?P<path>.*)$", serve),
diff --git a/saleor/warehouse/availability.py b/saleor/warehouse/availability.py
index 8e44399bd4..a021a81961 100644
--- a/saleor/warehouse/availability.py
+++ b/saleor/warehouse/availability.py
@@ -1,7 +1,5 @@
-from collections import defaultdict
-from typing import TYPE_CHECKING, Dict
+from typing import TYPE_CHECKING
-from django.conf import settings
from django.db.models import Sum
from django.db.models.functions import Coalesce
@@ -52,41 +50,6 @@ def get_available_quantity(variant: "ProductVariant", country_code: str) -> int:
return _get_available_quantity(stocks)
-def get_available_quantity_for_customer(
- variant: "ProductVariant", country_code: str = None
-) -> int:
- """Return maximum checkout line quantity.
-
- Returns maximum checkout quantity for the given variant and country code.
- If country code is provided, the function returns the exact variant quantity
- available in warehouses operating in shipping zones containing this country.
- Otherwise, it returns the maximum quantity from all shipping zones.
-
- The returned value is limited by `MAX_CHECKOUT_LINE_QUANTITY` setting to
- limit the quantity of a variant that can be added in one checkout line.
- """
- if not variant.track_inventory:
- return settings.MAX_CHECKOUT_LINE_QUANTITY
-
- stocks = Stock.objects.filter(product_variant=variant)
- if country_code:
- stocks = stocks.for_country(country_code)
- stocks = stocks.annotate_available_quantity()
- stocks = stocks.values_list("warehouse__shipping_zones", "available_quantity")
-
- if not stocks:
- return 0
-
- available_quantity_in_shipping_zones: Dict = defaultdict(int)
- for shipping_zone_pk, available_quantity in stocks:
- available_quantity_in_shipping_zones[shipping_zone_pk] += available_quantity
-
- max_available_quantity = max(
- available_quantity_in_shipping_zones.items(), key=lambda x: x[1]
- )[1]
- return min(max_available_quantity, settings.MAX_CHECKOUT_LINE_QUANTITY)
-
-
def get_quantity_allocated(variant: "ProductVariant", country_code: str) -> int:
stocks = Stock.objects.get_variant_stocks_for_country(country_code, variant)
if not stocks:
@@ -94,12 +57,6 @@ def get_quantity_allocated(variant: "ProductVariant", country_code: str) -> int:
return _get_quantity_allocated(stocks)
-def is_variant_in_stock(variant: "ProductVariant", country_code: str) -> bool:
- """Check if variant is available in given country."""
- quantity_available = get_available_quantity_for_customer(variant, country_code)
- return quantity_available > 0
-
-
def is_product_in_stock(product: "Product", country_code: str) -> bool:
"""Check if there is any variant of given product available in given country."""
stocks = Stock.objects.get_product_stocks_for_country(
diff --git a/saleor/warehouse/tests/test_stock_availability.py b/saleor/warehouse/tests/test_stock_availability.py
index 19b4d9fc07..247d14b8b6 100644
--- a/saleor/warehouse/tests/test_stock_availability.py
+++ b/saleor/warehouse/tests/test_stock_availability.py
@@ -1,15 +1,13 @@
import pytest
-from django.test import override_settings
from ...core.exceptions import InsufficientStock
from ..availability import (
are_all_product_variants_in_stock,
check_stock_quantity,
get_available_quantity,
- get_available_quantity_for_customer,
get_quantity_allocated,
)
-from ..models import Allocation, Stock
+from ..models import Allocation
COUNTRY_CODE = "US"
@@ -75,74 +73,6 @@ def test_get_available_quantity_without_stocks(variant_with_many_stocks):
assert available_quantity == 0
-@override_settings(MAX_CHECKOUT_LINE_QUANTITY=15)
-def test_get_available_quantity_for_customer(variant_with_many_stocks, settings):
- stock = variant_with_many_stocks.stocks.first()
- stock.quantity = 16
- stock.save(update_fields=["quantity"])
- available_quantity = get_available_quantity_for_customer(
- variant_with_many_stocks, COUNTRY_CODE
- )
- assert available_quantity == settings.MAX_CHECKOUT_LINE_QUANTITY
-
-
-def test_get_available_quantity_for_customer_without_stocks(variant_with_many_stocks):
- variant_with_many_stocks.stocks.all().delete()
- available_quantity = get_available_quantity_for_customer(
- variant_with_many_stocks, COUNTRY_CODE
- )
- assert available_quantity == 0
-
-
-@override_settings(MAX_CHECKOUT_LINE_QUANTITY=2)
-def test_get_available_quantity_for_customer_with_max(
- variant_with_many_stocks, settings
-):
- available_quantity = get_available_quantity_for_customer(
- variant_with_many_stocks, COUNTRY_CODE
- )
- assert available_quantity == settings.MAX_CHECKOUT_LINE_QUANTITY
-
-
-def test_get_available_quantity_for_customer_with_allocations(
- variant_with_many_stocks,
- order_line_with_allocation_in_many_stocks,
- order_line_with_one_allocation,
-):
- available_quantity = get_available_quantity_for_customer(
- variant_with_many_stocks, COUNTRY_CODE
- )
- assert available_quantity == 3
-
-
-@override_settings(MAX_CHECKOUT_LINE_QUANTITY=15)
-def test_get_available_quantity_for_customer_without_inventory_tracking(
- variant_with_many_stocks, settings
-):
- variant_with_many_stocks.track_inventory = False
- variant_with_many_stocks.save(update_fields=["track_inventory"])
- available_quantity = get_available_quantity_for_customer(
- variant_with_many_stocks, COUNTRY_CODE
- )
- assert available_quantity == settings.MAX_CHECKOUT_LINE_QUANTITY
-
-
-def test_get_available_quantity_for_customer_without_country(
- variant_with_many_stocks,
- warehouse_no_shipping_zone,
- shipping_zone_without_countries,
-):
- warehouse_no_shipping_zone.shipping_zones.add(shipping_zone_without_countries)
- Stock.objects.create(
- warehouse=warehouse_no_shipping_zone,
- product_variant=variant_with_many_stocks,
- quantity=12,
- )
-
- available_quantity = get_available_quantity_for_customer(variant_with_many_stocks)
- assert available_quantity == 12
-
-
def test_get_quantity_allocated(
variant_with_many_stocks, order_line_with_allocation_in_many_stocks
):
diff --git a/saleor/webhook/payloads.py b/saleor/webhook/payloads.py
index 85f5d02532..9797855ef2 100644
--- a/saleor/webhook/payloads.py
+++ b/saleor/webhook/payloads.py
@@ -205,7 +205,6 @@ def generate_product_payload(product: "Product"):
"name",
"description_json",
"currency",
- "minimal_variant_price_amount",
"attributes",
"updated_at",
"charge_taxes",
diff --git a/saleor/webhook/serializers.py b/saleor/webhook/serializers.py
index 3d83e7d54c..3f32a83e32 100644
--- a/saleor/webhook/serializers.py
+++ b/saleor/webhook/serializers.py
@@ -7,6 +7,7 @@ if TYPE_CHECKING:
def serialize_checkout_lines(checkout: "Checkout") -> List[dict]:
data = []
+ channel = checkout.channel
for line in checkout.lines.prefetch_related("variant__product").all():
variant = line.variant
product = variant.product
@@ -14,8 +15,8 @@ def serialize_checkout_lines(checkout: "Checkout") -> List[dict]:
{
"sku": variant.sku,
"quantity": line.quantity,
- "base_price": str(variant.price.amount),
- "currency": variant.currency,
+ "base_price": str(variant.get_price(channel.slug).amount),
+ "currency": channel.currency_code,
"full_name": variant.display_product(),
"product_name": product.name,
"variant_name": variant.name,
diff --git a/saleor/wishlist/error_codes.py b/saleor/wishlist/error_codes.py
index 5f77c477ea..909156ee4c 100644
--- a/saleor/wishlist/error_codes.py
+++ b/saleor/wishlist/error_codes.py
@@ -7,3 +7,4 @@ class WishlistErrorCode(str, Enum):
NOT_FOUND = "not_found"
REQUIRED = "required"
UNIQUE = "unique"
+ CANNOT_MANAGE_PRODUCT_WITHOUT_VARIANT = "CANNOT_MANAGE_PRODUCT_WITHOUT_VARIANT"