Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add default country to channel (#7907)
Marcin Gębalaf813a9fd37d3
diff --git a/saleor/channel/migrations/0002_channel_default_country.py b/saleor/channel/migrations/0002_channel_default_country.pynew file mode 100644index 0000000000..f7a48c083e--- /dev/null+++ b/saleor/channel/migrations/0002_channel_default_country.py@@ -0,0 +1,19 @@+# Generated by Django 3.2.6 on 2021-08-19 11:08++import django_countries.fields+from django.db import migrations+++class Migration(migrations.Migration):++ dependencies = [+ ("channel", "0001_initial"),+ ]++ operations = [+ migrations.AddField(+ model_name="channel",+ name="default_country",+ field=django_countries.fields.CountryField(max_length=2, null=True),+ ),+ ]diff --git a/saleor/channel/migrations/0003_alter_channel_default_country.py b/saleor/channel/migrations/0003_alter_channel_default_country.pynew file mode 100644index 0000000000..47f21eab25--- /dev/null+++ b/saleor/channel/migrations/0003_alter_channel_default_country.py@@ -0,0 +1,43 @@+# Generated by Django 3.2.6 on 2021-08-19 11:13++import django_countries.fields+from django.conf import settings+from django.db import migrations+++def set_default_country_for_channels(apps, schema_editor):+ Warehouse = apps.get_model("warehouse", "Warehouse")+ Channel = apps.get_model("channel", "Channel")++ channels = Channel.objects.all()+ for channel in channels:+ # For each channel get the first available warehouse and use it's country code+ warehouse = Warehouse.objects.filter(+ shipping_zones__channels=channel.pk+ ).first()+ if warehouse and warehouse.address and warehouse.address.country:+ country = warehouse.address.country.code+ else:+ country = settings.DEFAULT_COUNTRY++ channel.default_country = country+ channel.save(update_fields=["default_country"])+++class Migration(migrations.Migration):++ dependencies = [+ ("channel", "0002_channel_default_country"),+ ("shipping", "0029_shippingzone_channels"),+ ]++ operations = [+ migrations.RunPython(+ set_default_country_for_channels, reverse_code=migrations.RunPython.noop+ ),+ migrations.AlterField(+ model_name="channel",+ name="default_country",+ field=django_countries.fields.CountryField(max_length=2),+ ),+ ]diff --git a/saleor/channel/models.py b/saleor/channel/models.pyindex 08760bdddc..85fe55e616 100644--- a/saleor/channel/models.py+++ b/saleor/channel/models.py@@ -1,5 +1,6 @@from django.conf import settingsfrom django.db import models+from django_countries.fields import CountryFieldfrom ..core.permissions import ChannelPermissions@@ -9,6 +10,7 @@ class Channel(models.Model):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)+ default_country = CountryField()class Meta:ordering = ("slug",)diff --git a/saleor/graphql/channel/mutations.py b/saleor/graphql/channel/mutations.pyindex 3e93be3767..3db23f9d14 100644--- a/saleor/graphql/channel/mutations.py+++ b/saleor/graphql/channel/mutations.py@@ -11,6 +11,7 @@ from ...core.permissions import ChannelPermissionsfrom ...core.tracing import traced_atomic_transactionfrom ...order.models import Orderfrom ...shipping.tasks import drop_invalid_shipping_methods_relations_for_given_channels+from ..account.enums import CountryCodeEnumfrom ..core.mutations import BaseMutation, ModelDeleteMutation, ModelMutationfrom ..core.types.common import ChannelError, ChannelErrorCodefrom ..core.utils import get_duplicated_values, get_duplicates_ids@@ -28,6 +29,14 @@ class ChannelCreateInput(ChannelInput):currency_code = graphene.String(description="Currency of the channel.", required=True)+ default_country = CountryCodeEnum(+ description=(+ "Default country for the channel. Default country can be used in checkout "+ "to determine the stock quantities or calculate taxes when the country was "+ "not explicitly provided."+ ),+ required=True,+ )add_shipping_zones = graphene.List(graphene.NonNull(graphene.ID),description="List of shipping zones to assign to the channel.",@@ -73,6 +82,13 @@ class ChannelCreate(ModelMutation):class ChannelUpdateInput(ChannelInput):name = graphene.String(description="Name of the channel.")slug = graphene.String(description="Slug of the channel.")+ default_country = CountryCodeEnum(+ description=(+ "Default country for the channel. Default country can be used in checkout "+ "to determine the stock quantities or calculate taxes when the country was "+ "not explicitly provided."+ )+ )add_shipping_zones = graphene.List(graphene.NonNull(graphene.ID),description="List of shipping zones to assign to the channel.",diff --git a/saleor/graphql/channel/tests/fixtures.py b/saleor/graphql/channel/tests/fixtures.pyindex cfbe3ec7f5..f16bc61c6a 100644--- a/saleor/graphql/channel/tests/fixtures.py+++ b/saleor/graphql/channel/tests/fixtures.py@@ -8,19 +8,31 @@ from ....channel.models import Channeldef channel_USD(db):slug = settings.DEFAULT_CHANNEL_SLUGreturn Channel.objects.create(- name="Main Channel", slug=slug, currency_code="USD", is_active=True+ name="Main Channel",+ slug=slug,+ currency_code="USD",+ default_country="US",+ is_active=True,)@pytest.fixturedef other_channel_USD(db):return Channel.objects.create(- name="Other Channel USD", slug="other-usd", currency_code="USD", is_active=True+ name="Other Channel USD",+ slug="other-usd",+ currency_code="USD",+ default_country="US",+ is_active=True,)@pytest.fixturedef channel_PLN(db):return Channel.objects.create(- name="Channel PLN", slug="c-pln", currency_code="PLN", is_active=True+ name="Channel PLN",+ slug="c-pln",+ currency_code="PLN",+ default_country="PL",+ is_active=True,)diff --git a/saleor/graphql/channel/tests/test_channel_create_mutations.py b/saleor/graphql/channel/tests/test_channel_create_mutations.pyindex 6e5bd31783..c41f8e1cd7 100644--- a/saleor/graphql/channel/tests/test_channel_create_mutations.py+++ b/saleor/graphql/channel/tests/test_channel_create_mutations.py@@ -13,6 +13,10 @@ CHANNEL_CREATE_MUTATION = """nameslugcurrencyCode+ defaultCountry {+ code+ country+ }}errors{field@@ -32,7 +36,15 @@ def test_channel_create_mutation_as_staff_user(name = "testName"slug = "test_slug"currency_code = "USD"- variables = {"input": {"name": name, "slug": slug, "currencyCode": currency_code}}+ default_country = "US"+ variables = {+ "input": {+ "name": name,+ "slug": slug,+ "currencyCode": currency_code,+ "defaultCountry": default_country,+ }+ }# whenresponse = staff_api_client.post_graphql(@@ -50,6 +62,11 @@ def test_channel_create_mutation_as_staff_user(assert channel_data["name"] == channel.name == nameassert channel_data["slug"] == channel.slug == slugassert channel_data["currencyCode"] == channel.currency_code == currency_code+ assert (+ channel_data["defaultCountry"]["code"]+ == channel.default_country.code+ == default_country+ )def test_channel_create_mutation_as_app(@@ -60,7 +77,15 @@ def test_channel_create_mutation_as_app(name = "testName"slug = "test_slug"currency_code = "USD"- variables = {"input": {"name": name, "slug": slug, "currencyCode": currency_code}}+ default_country = "US"+ variables = {+ "input": {+ "name": name,+ "slug": slug,+ "currencyCode": currency_code,+ "defaultCountry": default_country,+ }+ }# whenresponse = app_api_client.post_graphql(@@ -78,6 +103,11 @@ def test_channel_create_mutation_as_app(assert channel_data["name"] == channel.name == nameassert channel_data["slug"] == channel.slug == slugassert channel_data["currencyCode"] == channel.currency_code == currency_code+ assert (+ channel_data["defaultCountry"]["code"]+ == channel.default_country.code+ == default_country+ )def test_channel_create_mutation_as_customer(user_api_client):@@ -85,7 +115,15 @@ def test_channel_create_mutation_as_customer(user_api_client):name = "testName"slug = "test_slug"currency_code = "USD"- variables = {"input": {"name": name, "slug": slug, "currencyCode": currency_code}}+ default_country = "US"+ variables = {+ "input": {+ "name": name,+ "slug": slug,+ "currencyCode": currency_code,+ "defaultCountry": default_country,+ }+ }# whenresponse = user_api_client.post_graphql(@@ -103,7 +141,15 @@ def test_channel_create_mutation_as_anonymous(api_client):name = "testName"slug = "test_slug"currency_code = "USD"- variables = {"input": {"name": name, "slug": slug, "currencyCode": currency_code}}+ default_country = "US"+ variables = {+ "input": {+ "name": name,+ "slug": slug,+ "currencyCode": currency_code,+ "defaultCountry": default_country,+ }+ }# whenresponse = api_client.post_graphql(@@ -124,7 +170,15 @@ def test_channel_create_mutation_slugify_slug_field(name = "testName"slug = "Invalid slug"currency_code = "USD"- variables = {"input": {"name": name, "slug": slug, "currencyCode": currency_code}}+ default_country = "US"+ variables = {+ "input": {+ "name": name,+ "slug": slug,+ "currencyCode": currency_code,+ "defaultCountry": default_country,+ }+ }# whenresponse = staff_api_client.post_graphql(@@ -146,7 +200,15 @@ def test_channel_create_mutation_with_duplicated_slug(name = "New Channel"slug = channel_USD.slugcurrency_code = "USD"- variables = {"input": {"name": name, "slug": slug, "currencyCode": currency_code}}+ default_country = "US"+ variables = {+ "input": {+ "name": name,+ "slug": slug,+ "currencyCode": currency_code,+ "defaultCountry": default_country,+ }+ }# whenresponse = staff_api_client.post_graphql(@@ -171,6 +233,7 @@ def test_channel_create_mutation_with_shipping_zones(name = "testName"slug = "test_slug"currency_code = "USD"+ default_country = "US"shipping_zones_ids = [graphene.Node.to_global_id("ShippingZone", zone.pk) for zone in shipping_zones]@@ -180,6 +243,7 @@ def test_channel_create_mutation_with_shipping_zones("slug": slug,"currencyCode": currency_code,"addShippingZones": shipping_zones_ids,+ "defaultCountry": default_country,}}diff --git a/saleor/graphql/channel/tests/test_channel_queries.py b/saleor/graphql/channel/tests/test_channel_queries.pyindex 0e96902f3b..38db61eb75 100644--- a/saleor/graphql/channel/tests/test_channel_queries.py+++ b/saleor/graphql/channel/tests/test_channel_queries.py@@ -12,6 +12,10 @@ query {nameslugcurrencyCode+ defaultCountry {+ code+ country+ }}}"""@@ -31,11 +35,19 @@ def test_query_channels_as_staff_user(staff_api_client, channel_USD, channel_PLN"slug": channel_PLN.slug,"name": channel_PLN.name,"currencyCode": channel_PLN.currency_code,+ "defaultCountry": {+ "code": channel_PLN.default_country.code,+ "country": channel_PLN.default_country.name,+ },} in channelsassert {"slug": channel_USD.slug,"name": channel_USD.name,"currencyCode": channel_USD.currency_code,+ "defaultCountry": {+ "code": channel_USD.default_country.code,+ "country": channel_USD.default_country.name,+ },} in channels@@ -53,11 +65,19 @@ def test_query_channels_as_app(app_api_client, channel_USD, channel_PLN):"slug": channel_PLN.slug,"name": channel_PLN.name,"currencyCode": channel_PLN.currency_code,+ "defaultCountry": {+ "code": channel_PLN.default_country.code,+ "country": channel_PLN.default_country.name,+ },} in channelsassert {"slug": channel_USD.slug,"name": channel_USD.name,"currencyCode": channel_USD.currency_code,+ "defaultCountry": {+ "code": channel_USD.default_country.code,+ "country": channel_USD.default_country.name,+ },} in channelsdiff --git a/saleor/graphql/channel/tests/test_channel_update_mutations.py b/saleor/graphql/channel/tests/test_channel_update_mutations.pyindex 7fef333936..0c2eabdedd 100644--- a/saleor/graphql/channel/tests/test_channel_update_mutations.py+++ b/saleor/graphql/channel/tests/test_channel_update_mutations.py@@ -14,6 +14,10 @@ CHANNEL_UPDATE_MUTATION = """nameslugcurrencyCode+ defaultCountry {+ code+ country+ }}errors{field@@ -33,7 +37,11 @@ def test_channel_update_mutation_as_staff_user(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}}+ default_country = "FR"+ variables = {+ "id": channel_id,+ "input": {"name": name, "slug": slug, "defaultCountry": default_country},+ }# whenresponse = staff_api_client.post_graphql(@@ -51,6 +59,11 @@ def test_channel_update_mutation_as_staff_user(assert channel_data["name"] == channel_USD.name == nameassert channel_data["slug"] == channel_USD.slug == slugassert channel_data["currencyCode"] == channel_USD.currency_code == "USD"+ assert (+ channel_data["defaultCountry"]["code"]+ == channel_USD.default_country.code+ == default_country+ )def test_channel_update_mutation_as_app(diff --git a/saleor/graphql/channel/types.py b/saleor/graphql/channel/types.pyindex ec9febe973..7662177df0 100644--- a/saleor/graphql/channel/types.py+++ b/saleor/graphql/channel/types.py@@ -5,6 +5,7 @@ from graphene_django import DjangoObjectTypefrom ...channel import modelsfrom ...core.permissions import ChannelPermissionsfrom ..core.connection import CountableDjangoObjectType+from ..core.types import CountryDisplayfrom ..decorators import permission_requiredfrom ..meta.types import ObjectWithMetadatafrom ..translations.resolvers import resolve_translation@@ -64,6 +65,15 @@ class Channel(CountableDjangoObjectType):has_orders = graphene.Boolean(required=True, description="Whether a channel has associated orders.")+ default_country = graphene.Field(+ CountryDisplay,+ description=(+ "Default country for the channel. Default country can be used in checkout "+ "to determine the stock quantities or calculate taxes when the country was "+ "not explicitly provided."+ ),+ required=True,+ )class Meta:description = "Represents channel."@@ -79,3 +89,9 @@ class Channel(CountableDjangoObjectType):.load(root.id).then(lambda channel: channel.has_orders))++ @staticmethod+ def resolve_default_country(root: models.Channel, _info):+ return CountryDisplay(+ code=root.default_country.code, country=root.default_country.name+ )diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.pyindex afe57a960b..f154c460de 100644--- a/saleor/graphql/checkout/mutations.py+++ b/saleor/graphql/checkout/mutations.py@@ -37,7 +37,6 @@ from ...product import models as product_modelsfrom ...product.models import ProductChannelListingfrom ...shipping import models as shipping_modelsfrom ...warehouse.availability import check_stock_quantity_bulk-from ...warehouse.models import Warehousefrom ..account.i18n import I18nMixinfrom ..account.types import AddressInputfrom ..channel.utils import clean_channel@@ -323,12 +322,7 @@ class CheckoutCreate(ModelMutation, I18nMixin):if shipping_address:country = shipping_address.country.codeelse:- warehouse = Warehouse.objects.get_first_warehouse_for_channel(channel.pk)- if warehouse:- country = warehouse.address.country.code- else:- # fallback when channel has no warehouses- country = settings.DEFAULT_COUNTRY+ country = channel.default_country# Resolve and process the lines, retrieving the variants and quantitieslines = data.pop("lines", None)diff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.pyindex 9ab3b45535..c401f3ab38 100644--- a/saleor/graphql/checkout/tests/test_checkout.py+++ b/saleor/graphql/checkout/tests/test_checkout.py@@ -31,7 +31,7 @@ from ....plugins.manager import PluginsManager, get_plugins_managerfrom ....plugins.tests.sample_plugins import ActiveDummyPaymentGatewayfrom ....product.models import ProductChannelListing, ProductVariantfrom ....shipping import models as shipping_models-from ....warehouse.models import Stock, Warehouse+from ....warehouse.models import Stockfrom ...tests.utils import assert_no_permission, get_graphql_contentfrom ..mutations import (clean_shipping_method,@@ -1030,11 +1030,10 @@ def test_checkout_create_sets_country_when_no_shipping_address_is_given(}assert not Checkout.objects.exists()- # should set address of a first warehouse in the channel+ # should set channel's default_countryapi_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)checkout = Checkout.objects.first()- first_warehouse = Warehouse.objects.get_first_warehouse_for_channel(channel_USD.pk)- assert checkout.country == first_warehouse.address.country+ assert checkout.country == channel_USD.default_country@override_settings(DEFAULT_COUNTRY="DE")diff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.pyindex 0f3750e447..a3da289413 100644--- a/saleor/graphql/product/tests/test_product.py+++ b/saleor/graphql/product/tests/test_product.py@@ -40,6 +40,7 @@ from ....product.models import ()from ....product.tasks import update_variants_namesfrom ....product.tests.utils import create_image, create_pdf_file_with_image_ext+from ....product.utils.availability import get_variant_availabilityfrom ....product.utils.costs import get_product_costs_datafrom ....tests.utils import dummy_editorjsfrom ....warehouse.models import Allocation, Stock, Warehouse@@ -8995,13 +8996,11 @@ QUERY_GET_PRODUCT_VARIANTS_PRICING = """"""[email protected]("saleor.graphql.product.types.products.WarehouseCountryCodeByChannelLoader")@pytest.mark.parametrize("variant_price_amount, api_variant_price",[(200, 200), (0, 0)],)def test_product_variant_price(- warehouse_country_code_loader,variant_price_amount,api_variant_price,user_api_client,@@ -9027,7 +9026,6 @@ def test_product_variant_price(data = content["data"]["product"]variant_price = data["variants"][0]["pricing"]["priceUndiscounted"]["gross"]assert variant_price["amount"] == api_variant_price- assert warehouse_country_code_loader.calleddef test_product_variant_without_price_as_user(@@ -9087,6 +9085,44 @@ def test_product_variant_without_price_as_staff(assert len(variants_data) == 2+QUERY_GET_PRODUCT_VARIANTS_PRICING_NO_ADDRESS = """+ query getProductVariants($id: ID!, $channel: String) {+ product(id: $id, channel: $channel) {+ variants {+ id+ pricing {+ priceUndiscounted {+ gross {+ amount+ }+ }+ }+ }+ }+ }+"""+++ "saleor.graphql.product.types.products.get_variant_availability",+ wraps=get_variant_availability,+)+def test_product_variant_price_no_address(+ mock_get_variant_availability, user_api_client, variant, stock, channel_USD+):+ channel_USD.default_country = "FR"+ channel_USD.save()+ product_id = graphene.Node.to_global_id("Product", variant.product.id)+ variables = {"id": product_id, "channel": channel_USD.slug}+ user_api_client.post_graphql(+ QUERY_GET_PRODUCT_VARIANTS_PRICING_NO_ADDRESS, variables+ )+ assert (+ mock_get_variant_availability.call_args[1]["country"]+ == channel_USD.default_country+ )++QUERY_REPORT_PRODUCT_SALES = """query TopProducts($period: ReportingPeriod!, $channel: String!) {reportProductSales(period: $period, first: 20, channel: $channel) {diff --git a/saleor/graphql/product/tests/test_product_channel_listings_queries.py b/saleor/graphql/product/tests/test_product_channel_listings_queries.pyindex 27c3717b1e..a49e7b936e 100644--- a/saleor/graphql/product/tests/test_product_channel_listings_queries.py+++ b/saleor/graphql/product/tests/test_product_channel_listings_queries.py@@ -2,6 +2,7 @@ from unittest import mockimport graphene+from ....product.utils.availability import get_product_availabilityfrom ....warehouse.models import Warehousefrom ...tests.utils import get_graphql_content@@ -9,16 +10,6 @@ QUERY_PRICING_ON_PRODUCT_CHANNEL_LISTING = """fragment Pricing on ProductPricingInfo {priceRangeUndiscounted {start {- net {- amount- currency- }- gross {- amount- currency- }- }- stop {gross {amountcurrency@@ -32,9 +23,6 @@ query FetchProduct($id: ID, $channel: String, $address: AddressInput) {pricing(address: $address) {...Pricing}- pricingNoAddress: pricing {- ...Pricing- }channelListings {channel {slug@@ -42,18 +30,13 @@ query FetchProduct($id: ID, $channel: String, $address: AddressInput) {pricing(address: $address) {...Pricing}- pricingNoAddress: pricing {- ...Pricing- }}}}"""[email protected]("saleor.graphql.product.types.channels.WarehouseCountryCodeByChannelLoader")def test_product_channel_listing_pricing_field(- warehouse_country_code_loader,address_usa,staff_api_client,permission_manage_products,@@ -88,4 +71,65 @@ def test_product_channel_listing_pricing_field(product_data = content["data"]["product"]product_channel_listing_data = product_data["channelListings"][0]assert product_data["pricing"] == product_channel_listing_data["pricing"]- assert warehouse_country_code_loader.called+++QUERY_PRICING_ON_PRODUCT_CHANNEL_LISTING_NO_ADDRESS = """+fragment Pricing on ProductPricingInfo {+ priceRangeUndiscounted {+ start {+ gross {+ amount+ currency+ }+ }+ }+}+query FetchProduct($id: ID, $channel: String) {+ product(id: $id, channel: $channel) {+ id+ pricing {+ ...Pricing+ }+ channelListings {+ pricing {+ ...Pricing+ }+ }+ }+}+"""+++ "saleor.graphql.product.types.products.get_product_availability",+ wraps=get_product_availability,+)+def test_product_channel_listing_pricing_field_no_address(+ mock_get_product_availability,+ staff_api_client,+ permission_manage_products,+ channel_USD,+ product,+):+ # given+ channel_USD.default_country = "FR"+ channel_USD.save()+ variables = {+ "id": graphene.Node.to_global_id("Product", product.pk),+ "channel": channel_USD.slug,+ }+ product.channel_listings.exclude(channel__slug=channel_USD.slug).delete()++ # when+ staff_api_client.post_graphql(+ QUERY_PRICING_ON_PRODUCT_CHANNEL_LISTING_NO_ADDRESS,+ variables=variables,+ permissions=(permission_manage_products,),+ check_no_permissions=False,+ )++ # then+ assert (+ mock_get_product_availability.call_args[1]["country"]+ == channel_USD.default_country+ )diff --git a/saleor/graphql/product/tests/test_variant_pricing.py b/saleor/graphql/product/tests/test_variant_pricing.pyindex 0c44c5e5b6..b16b191236 100644--- a/saleor/graphql/product/tests/test_variant_pricing.py+++ b/saleor/graphql/product/tests/test_variant_pricing.py@@ -1,4 +1,3 @@-from unittest import mockfrom unittest.mock import Mockfrom django_countries.fields import Country@@ -80,10 +79,7 @@ def test_get_variant_pricing_on_sale(api_client, sale, product, channel_USD):assert pricing["price"]["net"]["amount"] == discounted_price[email protected]("saleor.graphql.product.types.products.WarehouseCountryCodeByChannelLoader")-def test_get_variant_pricing_not_on_sale(- warehouse_country_code_loader, api_client, product, channel_USD-):+def test_get_variant_pricing_not_on_sale(api_client, product, channel_USD):price = product.variants.first().channel_listings.get().pricevariables = {"channel": channel_USD.slug, "address": {"country": "US"}}@@ -109,9 +105,6 @@ def test_get_variant_pricing_not_on_sale(assert pricing["price"]["currency"] == price.currencyassert pricing["price"]["net"]["amount"] == price.amount- # check that country_code loader was called for pricing without address- assert warehouse_country_code_loader.called-def test_variant_pricing(variant: ProductVariant, monkeypatch, settings, stock, channel_USDdiff --git a/saleor/graphql/product/types/channels.py b/saleor/graphql/product/types/channels.pyindex ddf4169ded..ec19b1c459 100644--- a/saleor/graphql/product/types/channels.py+++ b/saleor/graphql/product/types/channels.py@@ -18,7 +18,6 @@ from ...channel.dataloaders import ChannelByIdLoaderfrom ...core.connection import CountableDjangoObjectTypefrom ...decorators import permission_requiredfrom ...discount.dataloaders import DiscountsByDateTimeLoader-from ...warehouse.dataloaders import WarehouseCountryCodeByChannelLoaderfrom ..dataloaders import (CollectionsByProductIdLoader,ProductByIdLoader,@@ -161,7 +160,7 @@ class ProductChannelListing(CountableDjangoObjectType):def resolve_pricing(root: models.ProductChannelListing, info, address=None):context = info.context- country_code = address.country if address is not None else None+ address_country = address.country if address is not None else Nonedef calculate_pricing_info(discounts):def calculate_pricing_with_channel(channel):@@ -171,41 +170,30 @@ class ProductChannelListing(CountableDjangoObjectType):variants_channel_listing,):def calculate_pricing_with_collections(collections):- def calculate_pricing_with_country_code(country_code):- if not variants_channel_listing:- return None-- vc_listing = variants_channel_listing- local_currency = None- if country_code:- local_currency = get_currency_for_country(- country_code- )-- availability = get_product_availability(- product=product,- product_channel_listing=root,- variants=variants,- variants_channel_listing=vc_listing,- collections=collections,- discounts=discounts,- channel=channel,- manager=context.plugins,- country=Country(country_code),- local_currency=local_currency,- )- from .products import ProductPricingInfo-- return ProductPricingInfo(**asdict(availability))-- if not country_code:- return (- WarehouseCountryCodeByChannelLoader(context)- .load(channel.slug)- .then(calculate_pricing_with_country_code)- )-- return calculate_pricing_with_country_code(country_code)+ if not variants_channel_listing:+ return None++ country_code = (+ address_country or channel.default_country.code+ )+ local_currency = None+ local_currency = get_currency_for_country(country_code)++ availability = get_product_availability(+ product=product,+ product_channel_listing=root,+ variants=variants,+ variants_channel_listing=variants_channel_listing,+ collections=collections,+ discounts=discounts,+ channel=channel,+ manager=context.plugins,+ country=Country(country_code),+ local_currency=local_currency,+ )+ from .products import ProductPricingInfo++ return ProductPricingInfo(**asdict(availability))return (CollectionsByProductIdLoader(context)diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.pyindex 6fbb9ad727..b58bc8ae62 100644--- a/saleor/graphql/product/types/products.py+++ b/saleor/graphql/product/types/products.py@@ -66,7 +66,6 @@ from ...utils.filters import reporting_period_to_datefrom ...warehouse.dataloaders import (AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader,StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChannelLoader,- WarehouseCountryCodeByChannelLoader,)from ...warehouse.types import Stockfrom ..dataloaders import (@@ -356,74 +355,64 @@ class ProductVariant(ChannelContextTypeWithMetadata, CountableDjangoObjectType):collections = CollectionsByProductIdLoader(context).load(root.node.product_id)channel = ChannelBySlugLoader(context).load(channel_slug)- country_code = address.country if address is not None else None+ address_country = address.country if address is not None else None++ def calculate_pricing_info(discounts):+ 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):+ if (+ not variant_channel_listing+ or not product_channel_listing+ ):+ return None++ country_code = (+ address_country or channel.default_country.code+ )- def calculate_discounts(country_code):- def calculate_pricing_info(discounts):- 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):- if (- not variant_channel_listing- or not product_channel_listing- ):- return None-- local_currency = None- if country_code:- local_currency = get_currency_for_country(- country_code- )-- 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=Country(country_code),- local_currency=local_currency,- plugins=context.plugins,- )- return VariantPricingInfo(**asdict(availability))-- return collections.then(- calculate_pricing_with_collections+ local_currency = None+ local_currency = get_currency_for_country(country_code)++ 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=Country(country_code),+ local_currency=local_currency,+ plugins=context.plugins,)+ return VariantPricingInfo(**asdict(availability))- return product_channel_listing.then(- calculate_pricing_with_product_channel_listings- )+ return collections.then(calculate_pricing_with_collections)- return product.then(calculate_pricing_with_product)+ return product_channel_listing.then(+ calculate_pricing_with_product_channel_listings+ )- return variant_channel_listing.then(- calculate_pricing_with_product_variant_channel_listings- )+ return product.then(calculate_pricing_with_product)- return channel.then(calculate_pricing_with_channel)+ return variant_channel_listing.then(+ calculate_pricing_with_product_variant_channel_listings+ )- return (- DiscountsByDateTimeLoader(context)- .load(info.context.request_time)- .then(calculate_pricing_info)- )+ return channel.then(calculate_pricing_with_channel)- if not country_code:- return (- WarehouseCountryCodeByChannelLoader(context)- .load(channel_slug)- .then(calculate_discounts)- )- return calculate_discounts(country_code)+ return (+ DiscountsByDateTimeLoader(context)+ .load(info.context.request_time)+ .then(calculate_pricing_info)+ )@staticmethoddef resolve_product(root: ChannelContext[models.ProductVariant], info):@@ -681,72 +670,60 @@ class Product(ChannelContextTypeWithMetadata, CountableDjangoObjectType):collections = CollectionsByProductIdLoader(context).load(root.node.id)channel = ChannelBySlugLoader(context).load(channel_slug)- country_code = address.country if address is not None else None-- def calculate_discounts(country_code):- def calculate_pricing_info(discounts):- 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):- if not variants_channel_listing:- return None-- vc_listing = variants_channel_listing- local_currency = None- if country_code:- local_currency = get_currency_for_country(- country_code- )-- availability = get_product_availability(- product=root.node,- product_channel_listing=product_channel_listing,- variants=variants,- variants_channel_listing=vc_listing,- collections=collections,- discounts=discounts,- channel=channel,- manager=context.plugins,- country=Country(country_code),- local_currency=local_currency,- )- return ProductPricingInfo(**asdict(availability))-- return collections.then(- calculate_pricing_with_collections+ address_country = address.country if address is not None else None++ def calculate_pricing_info(discounts):+ 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):+ if not variants_channel_listing:+ return None++ local_currency = None+ country_code = (+ address_country or channel.default_country.code+ )+ local_currency = get_currency_for_country(country_code)++ 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,+ manager=context.plugins,+ country=Country(country_code),+ local_currency=local_currency,)+ return ProductPricingInfo(**asdict(availability))- return variants_channel_listing.then(- calculate_pricing_with_variants_channel_listings- )+ return collections.then(calculate_pricing_with_collections)- return variants.then(calculate_pricing_with_variants)+ return variants_channel_listing.then(+ calculate_pricing_with_variants_channel_listings+ )- return product_channel_listing.then(- calculate_pricing_with_product_channel_listings- )+ return variants.then(calculate_pricing_with_variants)- return channel.then(calculate_pricing_with_channel)+ return product_channel_listing.then(+ calculate_pricing_with_product_channel_listings+ )- return (- DiscountsByDateTimeLoader(context)- .load(info.context.request_time)- .then(calculate_pricing_info)- )+ return channel.then(calculate_pricing_with_channel)- if not country_code:- return (- WarehouseCountryCodeByChannelLoader(context)- .load(channel_slug)- .then(calculate_discounts)- )- return calculate_discounts(country_code)+ return (+ DiscountsByDateTimeLoader(context)+ .load(info.context.request_time)+ .then(calculate_pricing_info)+ )@staticmethod@traced_resolverdiff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 2309de6243..a622ad4462 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -906,6 +906,7 @@ type Channel implements Node {slug: String!currencyCode: String!hasOrders: Boolean!+ defaultCountry: CountryDisplay!}type ChannelActivate {@@ -925,6 +926,7 @@ input ChannelCreateInput {name: String!slug: String!currencyCode: String!+ defaultCountry: CountryCode!addShippingZones: [ID!]}@@ -973,6 +975,7 @@ input ChannelUpdateInput {isActive: Booleanname: Stringslug: String+ defaultCountry: CountryCodeaddShippingZones: [ID!]removeShippingZones: [ID!]}diff --git a/saleor/graphql/warehouse/dataloaders.py b/saleor/graphql/warehouse/dataloaders.pyindex 05d55c2bd8..2868137dfe 100644--- a/saleor/graphql/warehouse/dataloaders.py+++ b/saleor/graphql/warehouse/dataloaders.py@@ -7,8 +7,6 @@ from django.db.models import Exists, OuterReffrom ...channel.models import Channelfrom ...warehouse.models import ShippingZone, Stock, Warehouse-from ..account.dataloaders import AddressByIdLoader-from ..channel.dataloaders import ChannelBySlugLoaderfrom ..core.dataloaders import DataLoaderCountryCode = Optional[str]@@ -214,47 +212,3 @@ class WarehouseByIdLoader(DataLoader):def batch_load(self, keys):warehouses = Warehouse.objects.in_bulk(keys)return [warehouses.get(UUID(warehouse_uuid)) for warehouse_uuid in keys]---class WarehouseCountryCodeByChannelLoader(DataLoader):- """Loads country code of a first available warehouse that is found for a channel."""-- context_key = "warehouse_country_code_by_channel"-- def batch_load(self, keys):- def with_channels(channels):- address_id_by_channel_slug = dict()- for channel in channels:- first_warehouse = Warehouse.objects.get_first_warehouse_for_channel(- channel.id- )- if first_warehouse:- address_id_by_channel_slug[- channel.slug- ] = first_warehouse.address_id-- def with_addresses(addresses):- address_by_id = {address.pk: address for address in addresses}- country_codes = []- for key in keys:- address_id = address_id_by_channel_slug.get(key)- address = address_by_id.get(address_id) if address_id else None- if address and address.country:- country_code = address.country.code- else:- # Fallback when warehouse address has no country set. API has- # validation to prevent from adding such addresses, so this is- # added only to handle an edge-case if a warehouse would be- # added with bypassing the API (for instance with a migration).- country_code = settings.DEFAULT_COUNTRY- country_codes.append(country_code)- return country_codes-- address_ids = address_id_by_channel_slug.values()- return (- AddressByIdLoader(self.context)- .load_many(address_ids)- .then(with_addresses)- )-- return ChannelBySlugLoader(self.context).load_many(keys).then(with_channels)diff --git a/saleor/graphql/warehouse/tests/test_dataloaders.py b/saleor/graphql/warehouse/tests/test_dataloaders.pydeleted file mode 100644index 1015694821..0000000000--- a/saleor/graphql/warehouse/tests/test_dataloaders.py+++ /dev/null@@ -1,31 +0,0 @@-from unittest.mock import Mock--from ..dataloaders import WarehouseCountryCodeByChannelLoader---def test_warehouse_country_code_loader(channel_USD, shipping_zone):- warehouse = channel_USD.shipping_zones.first().warehouses.first()- request = Mock(dataloaders={})-- def with_country_code(country_code):- assert country_code == warehouse.address.country.code-- WarehouseCountryCodeByChannelLoader(request).load(channel_USD.slug).then(- with_country_code- )---def test_warehouse_country_code_loader_fallback_to_settings_country_no_warehouse(- channel_USD, settings-):- # Change the DEFAULT_COUNTRY for test purpose to a country that is different than- # fixtures' addresses.- settings.DEFAULT_COUNTRY = "TH"- request = Mock(dataloaders={})-- def with_country_code(country_code):- assert country_code == "TH"-- WarehouseCountryCodeByChannelLoader(request).load(channel_USD.slug).then(- with_country_code- )diff --git a/saleor/warehouse/models.py b/saleor/warehouse/models.pyindex 7aba6769da..f2e8955db1 100644--- a/saleor/warehouse/models.py+++ b/saleor/warehouse/models.py@@ -25,9 +25,6 @@ class WarehouseQueryset(models.QuerySet):.order_by("pk"))- def get_first_warehouse_for_channel(self, channel_pk: int):- return self.filter(shipping_zones__channels=channel_pk).first()-class Warehouse(ModelWithMetadata):id = models.UUIDField(default=uuid.uuid4, primary_key=True)diff --git a/saleor/warehouse/tests/test_warehouse.py b/saleor/warehouse/tests/test_warehouse.pydeleted file mode 100644index d06c25508b..0000000000--- a/saleor/warehouse/tests/test_warehouse.py+++ /dev/null@@ -1,23 +0,0 @@-from ...shipping.models import ShippingZone-from ..models import Warehouse---def test_get_first_warehouse_for_channel_no_shipping_zone(- warehouses_with_different_shipping_zone, channel_USD-):- for shipping_zone in ShippingZone.objects.all():- shipping_zone.channels.all().delete()- # At this point warehouse has no shipping zones; getting the first warehouse for- # channel should return None.- warehouse = Warehouse.objects.get_first_warehouse_for_channel(channel_USD.pk)- assert warehouse is None---def test_get_first_warehouse_for_channel(warehouses, channel_USD):- warehouse_usa = warehouses[1]- shipping_zone = ShippingZone.objects.create(name="USA", countries=["US"])- shipping_zone.channels.add(channel_USD)- warehouse_usa.shipping_zones.add(shipping_zone)-- first_warehouse = Warehouse.objects.get_first_warehouse_for_channel(channel_USD.pk)- assert first_warehouse == warehouse_usa