Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
[RFC] Sorting warehouses within channel (#10416)
Iga Karbowiakc464bf733d0d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c89e270e2e..99f4e80243 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,12 @@ All notable, unreleased changes to this project will be documented in this file.# 3.7.0 [Unreleased]+### GraphQL API+- Sorting warehouses within channel - #10416 by @IKarbowiak+ - Add `channelReorderWarehouses` mutation+ - Extend the `Channel` type with `stockSettings` field+ - Extend `ChannelCreateInput` and `ChannelUpdateInput` with `stockSettings`+### Other changes- Fix situation when Payment Gateway try to save to long error message - #10402 by @fowczarekdiff --git a/saleor/channel/__init__.py b/saleor/channel/__init__.pyindex e69de29bb2..c498e4774c 100644--- a/saleor/channel/__init__.py+++ b/saleor/channel/__init__.py@@ -0,0 +1,16 @@+class AllocationStrategy:+ """Determine the allocation strategy for the channel.++ PRIORITIZE_SORTING_ORDER - allocate stocks according to the warehouses' order+ within the channel++ PRIORITIZE_HIGH_STOCK - allocate stock in a warehouse with the most stock+ """++ PRIORITIZE_SORTING_ORDER = "prioritize-sorting-order"+ PRIORITIZE_HIGH_STOCK = "prioritize-high-stock"++ CHOICES = [+ (PRIORITIZE_SORTING_ORDER, "Prioritize sorting order"),+ (PRIORITIZE_HIGH_STOCK, "Prioritize high stock"),+ ]diff --git a/saleor/channel/migrations/0005_channel_allocation_strategy.py b/saleor/channel/migrations/0005_channel_allocation_strategy.pynew file mode 100644index 0000000000..71e6aa260b--- /dev/null+++ b/saleor/channel/migrations/0005_channel_allocation_strategy.py@@ -0,0 +1,38 @@+# Generated by Django 3.2.14 on 2022-08-21 09:52++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("channel", "0004_create_default_channel"),+ ]++ operations = [+ migrations.AddField(+ model_name="channel",+ name="allocation_strategy",+ field=models.CharField(+ choices=[+ ("prioritize-sorting-order", "Prioritize sorting order"),+ ("prioritize-high-stock", "Prioritize high stock"),+ ],+ default="prioritize-high-stock",+ max_length=255,+ ),+ preserve_default=False,+ ),+ migrations.AlterField(+ model_name="channel",+ name="allocation_strategy",+ field=models.CharField(+ choices=[+ ("prioritize-sorting-order", "Prioritize sorting order"),+ ("prioritize-high-stock", "Prioritize high stock"),+ ],+ default="prioritize-sorting-order",+ max_length=255,+ ),+ ),+ ]diff --git a/saleor/channel/models.py b/saleor/channel/models.pyindex 85fe55e616..f6f99f276c 100644--- a/saleor/channel/models.py+++ b/saleor/channel/models.py@@ -3,6 +3,7 @@ from django.db import modelsfrom django_countries.fields import CountryFieldfrom ..core.permissions import ChannelPermissions+from . import AllocationStrategyclass Channel(models.Model):@@ -11,6 +12,11 @@ class Channel(models.Model):slug = models.SlugField(max_length=255, unique=True)currency_code = models.CharField(max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH)default_country = CountryField()+ allocation_strategy = models.CharField(+ max_length=255,+ choices=AllocationStrategy.CHOICES,+ default=AllocationStrategy.PRIORITIZE_SORTING_ORDER,+ )class Meta:ordering = ("slug",)diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.pyindex d43fb36c67..090bd1c43c 100644--- a/saleor/checkout/complete_checkout.py+++ b/saleor/checkout/complete_checkout.py@@ -540,7 +540,7 @@ def _create_order(allocate_stocks(order_lines_info,country_code,- checkout_info.channel.slug,+ checkout_info.channel,manager,checkout_info.delivery_method_info.warehouse_pk,additional_warehouse_lookup,@@ -915,7 +915,7 @@ def _handle_allocations_of_order_lines(allocate_stocks(order_lines_info,country_code,- checkout_info.channel.slug,+ checkout_info.channel,manager,checkout_info.delivery_method_info.warehouse_pk,additional_warehouse_lookup,diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex f88ac12b6f..b4e01f9e7f 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -192,7 +192,7 @@ def add_variants_to_checkout(checkout,variants,checkout_lines_data,- channel_slug,+ channel,replace=False,replace_reservations=False,reservation_length: Optional[int] = None,@@ -243,7 +243,7 @@ def add_variants_to_checkout(to_reserve,variants,country_code,- channel_slug,+ channel,reservation_length,replace=replace_reservations,)diff --git a/saleor/graphql/channel/enums.py b/saleor/graphql/channel/enums.pynew file mode 100644index 0000000000..6a97b7661b--- /dev/null+++ b/saleor/graphql/channel/enums.py@@ -0,0 +1,8 @@+from ...channel import AllocationStrategy+from ..core.enums import to_enum++AllocationStrategyEnum = to_enum(+ AllocationStrategy,+ type_name="AllocationStrategyEnum",+ description=AllocationStrategy.__doc__,+)diff --git a/saleor/graphql/channel/mutations.py b/saleor/graphql/channel/mutations.pyindex 2145e50cee..e5c5e25e0a 100644--- a/saleor/graphql/channel/mutations.py+++ b/saleor/graphql/channel/mutations.py@@ -1,4 +1,5 @@import datetime+from collections import defaultdictfrom typing import DefaultDict, Dict, Iterable, Listimport graphene@@ -14,17 +15,36 @@ from ...core.utils.date_time import convert_to_utc_date_timefrom ...order.models import Orderfrom ...shipping.tasks import drop_invalid_shipping_methods_relations_for_given_channelsfrom ..account.enums import CountryCodeEnum-from ..core.descriptions import ADDED_IN_31, ADDED_IN_35, PREVIEW_FEATURE+from ..core.descriptions import ADDED_IN_31, ADDED_IN_35, ADDED_IN_37, PREVIEW_FEATURE+from ..core.inputs import ReorderInputfrom ..core.mutations import BaseMutation, ModelDeleteMutation, ModelMutationfrom ..core.types import ChannelError, ChannelErrorCode, NonNullListfrom ..core.utils import get_duplicated_values, get_duplicates_items+from ..core.utils.reordering import perform_reorderingfrom ..utils.validators import check_for_duplicates+from ..warehouse.types import Warehouse+from .enums import AllocationStrategyEnumfrom .types import Channelfrom .utils import delete_invalid_warehouse_to_shipping_zone_relations+class StockSettingsInput(graphene.InputObjectType):+ allocation_strategy = AllocationStrategyEnum(+ description=(+ "Allocation strategy options. Strategy defines the preference "+ "of warehouses for allocations and reservations."+ ),+ required=True,+ )++class ChannelInput(graphene.InputObjectType):is_active = graphene.Boolean(description="isActive flag.")+ stock_settings = graphene.Field(+ StockSettingsInput,+ description=("The channel stock settings." + ADDED_IN_37 + PREVIEW_FEATURE),+ required=False,+ )add_shipping_zones = NonNullList(graphene.ID,description="List of shipping zones to assign to the channel.",@@ -81,6 +101,8 @@ class ChannelCreate(ModelMutation):slug = cleaned_input.get("slug")if slug:cleaned_input["slug"] = slugify(slug)+ if stock_settings := cleaned_input.get("stock_settings"):+ cleaned_input["allocation_strategy"] = stock_settings["allocation_strategy"]return cleaned_input@@ -161,6 +183,8 @@ class ChannelUpdate(ModelMutation):slug = cleaned_input.get("slug")if slug:cleaned_input["slug"] = slugify(slug)+ if stock_settings := cleaned_input.get("stock_settings"):+ cleaned_input["allocation_strategy"] = stock_settings["allocation_strategy"]return cleaned_input@@ -508,3 +532,82 @@ class ChannelDeactivate(BaseMutation):channel.save(update_fields=["is_active"])info.context.plugins.channel_status_changed(channel)return ChannelDeactivate(channel=channel)+++class ChannelReorderWarehouses(BaseMutation):+ channel = graphene.Field(+ Channel, description="Channel within the warehouses are reordered."+ )++ class Arguments:+ channel_id = graphene.ID(+ description="ID of a channel.",+ required=True,+ )+ moves = NonNullList(+ ReorderInput,+ required=True,+ description=(+ "The list of reordering operations for the given channel warehouses."+ ),+ )++ class Meta:+ description = (+ "Reorder the warehouses of a channel." + ADDED_IN_37 + PREVIEW_FEATURE+ )+ permissions = (ChannelPermissions.MANAGE_CHANNELS,)+ error_type_class = ChannelError++ @classmethod+ def perform_mutation(cls, _root, info, channel_id, moves):+ channel = cls.get_node_or_error(+ info, channel_id, field="channel_id", only_type=Channel+ )++ warehouses_m2m = channel.channelwarehouse+ operations = cls.get_operations(moves, warehouses_m2m)++ with traced_atomic_transaction():+ perform_reordering(warehouses_m2m, operations)++ return ChannelReorderWarehouses(channel=channel)++ @classmethod+ def get_operations(cls, moves, channel_warehouses_m2m):+ warehouse_ids = [move["id"] for move in moves]+ warehouse_pks = cls.get_global_ids_or_error(+ warehouse_ids, only_type=Warehouse, field="moves"+ )++ warehouses_m2m = channel_warehouses_m2m.filter(warehouse_id__in=warehouse_pks)++ if warehouses_m2m.count() != len(set(warehouse_pks)):+ pks = {+ str(pk) for pk in warehouses_m2m.values_list("warehouse_id", flat=True)+ }+ invalid_values = set(warehouse_pks) - pks+ invalid_ids = [+ graphene.Node.to_global_id("Warehouse", warehouse_id)+ for warehouse_id in invalid_values+ ]+ raise ValidationError(+ {+ "moves": ValidationError(+ "Couldn't resolve to a warehouse",+ code=ChannelErrorCode.NOT_FOUND,+ params={"warehouses": invalid_ids},+ )+ }+ )++ warehouse_id_to_warehouse_m2m_id = {+ str(warehouse_data["warehouse_id"]): warehouse_data["id"]+ for warehouse_data in warehouses_m2m.values("id", "warehouse_id")+ }+ operations = defaultdict(int)+ for warehouse_pk, move in zip(warehouse_pks, moves):+ warehouse_m2m_id = warehouse_id_to_warehouse_m2m_id[warehouse_pk]+ operations[warehouse_m2m_id] += move.sort_order++ return dict(operations)diff --git a/saleor/graphql/channel/schema.py b/saleor/graphql/channel/schema.pyindex 7c73db3f46..7ee5e215fb 100644--- a/saleor/graphql/channel/schema.py+++ b/saleor/graphql/channel/schema.py@@ -9,6 +9,7 @@ from .mutations import (ChannelCreate,ChannelDeactivate,ChannelDelete,+ ChannelReorderWarehouses,ChannelUpdate,)from .resolvers import resolve_channel, resolve_channels@@ -52,3 +53,4 @@ class ChannelMutations(graphene.ObjectType):channel_delete = ChannelDelete.Field()channel_activate = ChannelActivate.Field()channel_deactivate = ChannelDeactivate.Field()+ channel_reorder_warehouses = ChannelReorderWarehouses.Field()diff --git a/saleor/graphql/channel/tests/fixtures.py b/saleor/graphql/channel/tests/fixtures.pyindex 2f6bf9d253..91dfa83896 100644--- a/saleor/graphql/channel/tests/fixtures.py+++ b/saleor/graphql/channel/tests/fixtures.py@@ -1,6 +1,7 @@import pytestfrom django.conf import settings+from ....channel import AllocationStrategyfrom ....channel.models import Channel@@ -13,6 +14,7 @@ def channel_USD(db):currency_code="USD",default_country="US",is_active=True,+ allocation_strategy=AllocationStrategy.PRIORITIZE_HIGH_STOCK,)@@ -24,6 +26,7 @@ def other_channel_USD(db):currency_code="USD",default_country="US",is_active=True,+ allocation_strategy=AllocationStrategy.PRIORITIZE_HIGH_STOCK,)@@ -35,6 +38,7 @@ def channel_PLN(db):currency_code="PLN",default_country="PL",is_active=True,+ allocation_strategy=AllocationStrategy.PRIORITIZE_HIGH_STOCK,)@@ -46,4 +50,5 @@ def channel_JPY(db):currency_code="JPY",default_country="JP",is_active=True,+ allocation_strategy=AllocationStrategy.PRIORITIZE_HIGH_STOCK,)diff --git a/saleor/graphql/channel/tests/test_channel_create_mutations.py b/saleor/graphql/channel/tests/test_channel_create_mutations.pyindex 620c80cf7b..3a72fe37a1 100644--- a/saleor/graphql/channel/tests/test_channel_create_mutations.py+++ b/saleor/graphql/channel/tests/test_channel_create_mutations.py@@ -12,6 +12,7 @@ from ....core.utils.json_serializer import CustomJsonEncoderfrom ....webhook.event_types import WebhookEventAsyncTypefrom ....webhook.payloads import generate_meta, generate_requestorfrom ...tests.utils import assert_no_permission, get_graphql_content+from ..enums import AllocationStrategyEnumCHANNEL_CREATE_MUTATION = """mutation CreateChannel($input: ChannelCreateInput!){@@ -28,6 +29,9 @@ CHANNEL_CREATE_MUTATION = """warehouses {slug}+ stockSettings {+ allocationStrategy+ }}errors{field@@ -48,12 +52,14 @@ def test_channel_create_mutation_as_staff_user(slug = "test_slug"currency_code = "USD"default_country = "US"+ allocation_strategy = AllocationStrategyEnum.PRIORITIZE_HIGH_STOCK.namevariables = {"input": {"name": name,"slug": slug,"currencyCode": currency_code,"defaultCountry": default_country,+ "stockSettings": {"allocationStrategy": allocation_strategy},}}@@ -78,6 +84,7 @@ def test_channel_create_mutation_as_staff_user(== channel.default_country.code== default_country)+ assert channel_data["stockSettings"]["allocationStrategy"] == allocation_strategydef test_channel_create_mutation_as_app(@@ -119,6 +126,10 @@ def test_channel_create_mutation_as_app(== channel.default_country.code== default_country)+ assert (+ channel_data["stockSettings"]["allocationStrategy"]+ == AllocationStrategyEnum.PRIORITIZE_SORTING_ORDER.name+ )def test_channel_create_mutation_as_customer(user_api_client):@@ -127,12 +138,14 @@ def test_channel_create_mutation_as_customer(user_api_client):slug = "test_slug"currency_code = "USD"default_country = "US"+ allocation_strategy = AllocationStrategyEnum.PRIORITIZE_SORTING_ORDER.namevariables = {"input": {"name": name,"slug": slug,"currencyCode": currency_code,"defaultCountry": default_country,+ "stockSettings": {"allocationStrategy": allocation_strategy},}}@@ -212,12 +225,14 @@ def test_channel_create_mutation_with_duplicated_slug(slug = channel_USD.slugcurrency_code = "USD"default_country = "US"+ allocation_strategy = AllocationStrategyEnum.PRIORITIZE_SORTING_ORDER.namevariables = {"input": {"name": name,"slug": slug,"currencyCode": currency_code,"defaultCountry": default_country,+ "stockSettings": {"allocationStrategy": allocation_strategy},}}@@ -248,6 +263,7 @@ def test_channel_create_mutation_with_shipping_zones(shipping_zones_ids = [graphene.Node.to_global_id("ShippingZone", zone.pk) for zone in shipping_zones]+ allocation_strategy = AllocationStrategyEnum.PRIORITIZE_SORTING_ORDER.namevariables = {"input": {"name": name,@@ -255,6 +271,7 @@ def test_channel_create_mutation_with_shipping_zones("currencyCode": currency_code,"addShippingZones": shipping_zones_ids,"defaultCountry": default_country,+ "stockSettings": {"allocationStrategy": allocation_strategy},}}@@ -278,6 +295,7 @@ def test_channel_create_mutation_with_shipping_zones(assert channel_data["currencyCode"] == channel.currency_code == currency_codefor shipping_zone in shipping_zones:shipping_zone.channels.get(slug=slug)+ assert channel_data["stockSettings"]["allocationStrategy"] == allocation_strategydef test_channel_create_mutation_with_warehouses(@@ -294,6 +312,7 @@ def test_channel_create_mutation_with_warehouses(graphene.Node.to_global_id("Warehouse", warehouse.pk)for warehouse in warehouses]+ allocation_strategy = AllocationStrategyEnum.PRIORITIZE_SORTING_ORDER.namevariables = {"input": {"name": name,@@ -301,6 +320,7 @@ def test_channel_create_mutation_with_warehouses("currencyCode": currency_code,"addWarehouses": warehouses_ids,"defaultCountry": default_country,+ "stockSettings": {"allocationStrategy": allocation_strategy},}}@@ -325,6 +345,7 @@ def test_channel_create_mutation_with_warehouses(assert {warehouse_data["slug"] for warehouse_data in channel_data["warehouses"]} == {warehouse.slug for warehouse in warehouses}+ assert channel_data["stockSettings"]["allocationStrategy"] == allocation_strategy@freeze_time("2022-05-12 12:00:00")@@ -346,12 +367,14 @@ def test_channel_create_mutation_trigger_webhook(slug = "test_slug"currency_code = "USD"default_country = "US"+ allocation_strategy = AllocationStrategyEnum.PRIORITIZE_SORTING_ORDER.namevariables = {"input": {"name": name,"slug": slug,"currencyCode": currency_code,"defaultCountry": default_country,+ "stockSettings": {"allocationStrategy": allocation_strategy},}}diff --git a/saleor/graphql/channel/tests/test_channel_queries.py b/saleor/graphql/channel/tests/test_channel_queries.pyindex 29455d1186..3ff6342ffd 100644--- a/saleor/graphql/channel/tests/test_channel_queries.py+++ b/saleor/graphql/channel/tests/test_channel_queries.py@@ -7,6 +7,7 @@ from ...tests.utils import (get_graphql_content,get_graphql_content_from_response,)+from ..enums import AllocationStrategyEnumQUERY_CHANNELS = """query {@@ -164,6 +165,9 @@ QUERY_CHANNEL = """nameslugcurrencyCode+ stockSettings{+ allocationStrategy+ }}}"""@@ -184,6 +188,11 @@ def test_query_channel_as_staff_user(staff_api_client, channel_USD):assert channel_data["name"] == channel_USD.nameassert channel_data["slug"] == channel_USD.slugassert channel_data["currencyCode"] == channel_USD.currency_code+ allocation_strategy = channel_data["stockSettings"]["allocationStrategy"]+ assert (+ AllocationStrategyEnum[allocation_strategy].value+ == channel_USD.allocation_strategy+ )def test_query_channel_as_app(app_api_client, channel_USD):@@ -201,6 +210,11 @@ def test_query_channel_as_app(app_api_client, channel_USD):assert channel_data["name"] == channel_USD.nameassert channel_data["slug"] == channel_USD.slugassert channel_data["currencyCode"] == channel_USD.currency_code+ allocation_strategy = channel_data["stockSettings"]["allocationStrategy"]+ assert (+ AllocationStrategyEnum[allocation_strategy].value+ == channel_USD.allocation_strategy+ )def test_query_channel_as_customer(user_api_client, channel_USD):diff --git a/saleor/graphql/channel/tests/test_channel_reorder_warehouses.py b/saleor/graphql/channel/tests/test_channel_reorder_warehouses.pynew file mode 100644index 0000000000..754f7e1035--- /dev/null+++ b/saleor/graphql/channel/tests/test_channel_reorder_warehouses.py@@ -0,0 +1,194 @@+import uuid++import graphene+import pytest++from ....channel.error_codes import ChannelErrorCode+from ....warehouse.models import ChannelWarehouse+from ...tests.utils import get_graphql_content++CHANNEL_REORDER_WAREHOUSES = """+ mutation ChannelReorderWarehouses($channelId: ID!, $moves: [ReorderInput!]!) {+ channelReorderWarehouses(channelId: $channelId, moves: $moves) {+ channel {+ id+ warehouses {+ id+ slug+ }+ }+ errors {+ field+ code+ message+ warehouses+ }+ }+ }+"""+++ "moves, expected_order",+ [+ ([(0, 1), (2, -1)], [1, 2, 0]),+ ([(2, -2)], [2, 0, 1]),+ ([(0, 1), (0, -1)], [0, 1, 2]),+ ([(0, -1)], [0, 1, 2]),+ ([(2, 1)], [0, 1, 2]),+ ],+)+def test_sort_warehouses_with_channel(+ moves,+ expected_order,+ staff_api_client,+ permission_manage_channels,+ channel_USD,+ warehouses,+ warehouse,+):+ # given+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.pk)++ channel_warehouses = list(channel_USD.channelwarehouse.all())++ assert len(channel_warehouses) == 3++ channel_warehouse_1 = channel_warehouses[0]+ channel_warehouse_2 = channel_warehouses[1]+ channel_warehouse_3 = channel_warehouses[2]++ channel_warehouse_1.sort_order = 0+ channel_warehouse_2.sort_order = 1+ channel_warehouse_3.sort_order = 2++ ChannelWarehouse.objects.bulk_update(channel_warehouses, ["sort_order"])++ warehouse_1_id = graphene.Node.to_global_id(+ "Warehouse", channel_warehouse_1.warehouse_id+ )+ warehouse_2_id = graphene.Node.to_global_id(+ "Warehouse", channel_warehouse_2.warehouse_id+ )+ warehouse_3_id = graphene.Node.to_global_id(+ "Warehouse", channel_warehouse_3.warehouse_id+ )+ warehouses = [warehouse_1_id, warehouse_2_id, warehouse_3_id]++ variables = {+ "channelId": channel_id,+ "moves": [+ {"id": warehouses[index], "sortOrder": move} for index, move in moves+ ],+ }++ # when+ response = staff_api_client.post_graphql(+ CHANNEL_REORDER_WAREHOUSES, variables, permissions=[permission_manage_channels]+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["channelReorderWarehouses"]+ errors = data["errors"]+ assert not errors+ assert len(data["channel"]["warehouses"]) == 3+ expected_order = [warehouses[index] for index in expected_order]+ assert [+ warehouse_data["id"] for warehouse_data in data["channel"]["warehouses"]+ ] == expected_order+++def test_sort_warehouses_with_channel_invalid_channel_id(+ staff_api_client, warehouses, channel_USD, permission_manage_channels+):+ # given+ channel_USD.warehouses.add(*warehouses)+ moves = [+ {+ "id": graphene.Node.to_global_id("Warehouse", warehouses[-1].pk),+ "sortOrder": 1,+ }+ ]++ variables = {"channelId": graphene.Node.to_global_id("Channel", -1), "moves": moves}++ # when+ response = staff_api_client.post_graphql(+ CHANNEL_REORDER_WAREHOUSES, variables, permissions=[permission_manage_channels]+ )++ # then+ content = get_graphql_content(response)++ data = content["data"]["channelReorderWarehouses"]+ errors = data["errors"]+ assert len(errors) == 1+ assert errors[0]["field"] == "channelId"+ assert errors[0]["code"] == ChannelErrorCode.NOT_FOUND.name+++def test_sort_warehouses_with_channel_not_existing_warehouse_ids(+ staff_api_client, warehouses, channel_USD, permission_manage_channels+):+ # given+ channel_USD.warehouses.add(*warehouses)+ invalid_warehouse_id_1 = graphene.Node.to_global_id("Warehouse", uuid.uuid4())+ invalid_warehouse_id_2 = graphene.Node.to_global_id("Warehouse", uuid.uuid4())+ moves = [+ {"id": invalid_warehouse_id_1, "sortOrder": 1},+ {"id": invalid_warehouse_id_2, "sortOrder": 2},+ ]++ variables = {+ "channelId": graphene.Node.to_global_id("Channel", channel_USD.id),+ "moves": moves,+ }++ # when+ response = staff_api_client.post_graphql(+ CHANNEL_REORDER_WAREHOUSES, variables, permissions=[permission_manage_channels]+ )++ # then+ content = get_graphql_content(response)++ data = content["data"]["channelReorderWarehouses"]+ errors = data["errors"]+ assert len(errors) == 1+ assert errors[0]["field"] == "moves"+ assert errors[0]["code"] == ChannelErrorCode.NOT_FOUND.name+ assert set(errors[0]["warehouses"]) == {+ invalid_warehouse_id_1,+ invalid_warehouse_id_2,+ }+++def test_sort_warehouses_with_channel_not_invalid_warehouse_ids(+ staff_api_client, warehouses, channel_USD, permission_manage_channels+):+ # given+ channel_USD.warehouses.add(*warehouses)+ moves = [+ {"id": graphene.Node.to_global_id("Product", 1), "sortOrder": 1},+ {"id": graphene.Node.to_global_id("Product", 2), "sortOrder": 2},+ ]++ variables = {+ "channelId": graphene.Node.to_global_id("Channel", channel_USD.id),+ "moves": moves,+ }++ # when+ response = staff_api_client.post_graphql(+ CHANNEL_REORDER_WAREHOUSES, variables, permissions=[permission_manage_channels]+ )++ # then+ content = get_graphql_content(response)++ data = content["data"]["channelReorderWarehouses"]+ errors = data["errors"]+ assert len(errors) == 1+ assert errors[0]["field"] == "moves"+ assert errors[0]["code"] == ChannelErrorCode.GRAPHQL_ERROR.namediff --git a/saleor/graphql/channel/tests/test_channel_update_mutations.py b/saleor/graphql/channel/tests/test_channel_update_mutations.pyindex b2353e31b0..9d61d70a31 100644--- a/saleor/graphql/channel/tests/test_channel_update_mutations.py+++ b/saleor/graphql/channel/tests/test_channel_update_mutations.py@@ -12,6 +12,7 @@ from ....core.utils.json_serializer import CustomJsonEncoderfrom ....webhook.event_types import WebhookEventAsyncTypefrom ....webhook.payloads import generate_meta, generate_requestorfrom ...tests.utils import assert_no_permission, get_graphql_content+from ..enums import AllocationStrategyEnumCHANNEL_UPDATE_MUTATION = """mutation UpdateChannel($id: ID!,$input: ChannelUpdateInput!){@@ -28,6 +29,9 @@ CHANNEL_UPDATE_MUTATION = """warehouses {slug}+ stockSettings {+ allocationStrategy+ }}errors{field@@ -49,9 +53,15 @@ def test_channel_update_mutation_as_staff_user(name = "newName"slug = "new_slug"default_country = "FR"+ allocation_strategy = AllocationStrategyEnum.PRIORITIZE_SORTING_ORDER.namevariables = {"id": channel_id,- "input": {"name": name, "slug": slug, "defaultCountry": default_country},+ "input": {+ "name": name,+ "slug": slug,+ "defaultCountry": default_country,+ "stockSettings": {"allocationStrategy": allocation_strategy},+ },}# when@@ -75,6 +85,7 @@ def test_channel_update_mutation_as_staff_user(== channel_USD.default_country.code== default_country)+ assert channel_data["stockSettings"]["allocationStrategy"] == allocation_strategydef test_channel_update_mutation_as_app(diff --git a/saleor/graphql/channel/types.py b/saleor/graphql/channel/types.pyindex 7ba131c5a2..da35a23b45 100644--- a/saleor/graphql/channel/types.py+++ b/saleor/graphql/channel/types.py@@ -4,13 +4,20 @@ from typing import Dict, List, Type, Union, castimport graphenefrom django.db.models import Model+from graphene.types.objecttype import ObjectTypefrom graphene.types.resolver import get_default_resolverfrom promise import Promisefrom ...channel import modelsfrom ...core.permissions import AuthorizationFilters, ChannelPermissionsfrom ..account.enums import CountryCodeEnum-from ..core.descriptions import ADDED_IN_31, ADDED_IN_35, ADDED_IN_36, PREVIEW_FEATURE+from ..core.descriptions import (+ ADDED_IN_31,+ ADDED_IN_35,+ ADDED_IN_36,+ ADDED_IN_37,+ PREVIEW_FEATURE,+)from ..core.fields import PermissionsFieldfrom ..core.types import CountryDisplay, ModelObjectType, NonNullListfrom ..meta.types import ObjectWithMetadata@@ -19,6 +26,7 @@ from ..warehouse.dataloaders import WarehousesByChannelIdLoaderfrom ..warehouse.types import Warehousefrom . import ChannelContextfrom .dataloaders import ChannelWithHasOrdersByIdLoader+from .enums import AllocationStrategyEnumclass ChannelContextTypeForObjectType(graphene.ObjectType):@@ -121,6 +129,21 @@ class ChannelContextTypeWithMetadata(abstract = True+class StockSettings(ObjectType):+ allocation_strategy = AllocationStrategyEnum(+ description=(+ "Allocation strategy defines the preference of warehouses "+ "for allocations and reservations."+ ),+ required=True,+ )++ class Meta:+ description = (+ "Represents the channel stock settings." + ADDED_IN_37 + PREVIEW_FEATURE+ )++class Channel(ModelObjectType):id = graphene.GlobalID(required=True)slug = graphene.String(@@ -201,6 +224,17 @@ class Channel(ModelObjectType):+ ADDED_IN_36+ PREVIEW_FEATURE,)+ stock_settings = PermissionsField(+ StockSettings,+ description=(+ "Define the stock setting for this channel." + ADDED_IN_37 + PREVIEW_FEATURE+ ),+ required=True,+ permissions=[+ AuthorizationFilters.AUTHENTICATED_APP,+ AuthorizationFilters.AUTHENTICATED_STAFF_USER,+ ],+ )class Meta:description = "Represents channel."@@ -327,3 +361,7 @@ class Channel(ModelObjectType):)return shipping_zones_loader.then(get_shipping_methods)++ @staticmethod+ def resolve_stock_settings(root: models.Channel, _info):+ return StockSettings(allocation_strategy=root.allocation_strategy)diff --git a/saleor/graphql/checkout/mutations/checkout_create.py b/saleor/graphql/checkout/mutations/checkout_create.pyindex 918386e44c..b9a44f7174 100644--- a/saleor/graphql/checkout/mutations/checkout_create.py+++ b/saleor/graphql/checkout/mutations/checkout_create.py@@ -303,7 +303,7 @@ class CheckoutCreate(ModelMutation, I18nMixin):instance,variants,checkout_lines_data,- channel.slug,+ channel,info.context.site.settings.limit_quantity_per_checkout,reservation_length=get_reservation_length(info.context),)diff --git a/saleor/graphql/checkout/mutations/checkout_lines_add.py b/saleor/graphql/checkout/mutations/checkout_lines_add.pyindex 7412b8a5b6..2c11abd4c4 100644--- a/saleor/graphql/checkout/mutations/checkout_lines_add.py+++ b/saleor/graphql/checkout/mutations/checkout_lines_add.py@@ -141,7 +141,7 @@ class CheckoutLinesAdd(BaseMutation):checkout,variants,checkout_lines_data,- channel_slug,+ checkout_info.channel,replace=replace,replace_reservations=True,reservation_length=get_reservation_length(info.context),diff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.pyindex b50edb16d1..e8a7ff7da6 100644--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py@@ -653,7 +653,7 @@ def test_update_checkout_lines_with_reservations()for variant in variants],- channel_USD.slug,+ channel_USD,replace_reservations=True,reservation_length=5,)diff --git a/saleor/graphql/order/mutations/draft_order_complete.py b/saleor/graphql/order/mutations/draft_order_complete.pyindex 8ee3a4fc34..a1a28f3370 100644--- a/saleor/graphql/order/mutations/draft_order_complete.py+++ b/saleor/graphql/order/mutations/draft_order_complete.py@@ -93,7 +93,6 @@ class DraftOrderComplete(BaseMutation):order.save()channel = order.channel- channel_slug = channel.slugorder_lines_info = []for line in order.lines.all():if line.variant.track_inventory or line.variant.is_preorder_active():@@ -106,7 +105,7 @@ class DraftOrderComplete(BaseMutation):allocate_stocks([line_data],country,- channel_slug,+ channel,manager,check_reservations=is_reservation_enabled(info.context.site.settings@@ -114,7 +113,7 @@ class DraftOrderComplete(BaseMutation):)allocate_preorders([line_data],- channel_slug,+ channel.slug,check_reservations=is_reservation_enabled(info.context.site.settings),diff --git a/saleor/graphql/order/mutations/order_line_update.py b/saleor/graphql/order/mutations/order_line_update.pyindex acd24088f6..386692b375 100644--- a/saleor/graphql/order/mutations/order_line_update.py+++ b/saleor/graphql/order/mutations/order_line_update.py@@ -79,7 +79,7 @@ class OrderLineUpdate(EditableOrderValidationMixin, ModelMutation):line_info,instance.old_quantity,instance.quantity,- instance.order.channel.slug,+ instance.order.channel,manager,)except InsufficientStock:diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.pyindex 2782cae38c..b00ba1d8d4 100644--- a/saleor/graphql/product/mutations/products.py+++ b/saleor/graphql/product/mutations/products.py@@ -1560,7 +1560,7 @@ class ProductVariantReorder(BaseMutation):with traced_atomic_transaction():perform_reordering(variants_m2m, operations)- product.save(update_fields=["updated_at", "updated_at"])+ product.save(update_fields=["updated_at"])info.context.plugins.product_updated(product)product = ChannelContext(node=product, channel_slug=None)return ProductVariantReorder(product=product)diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex a9617ef595..265435db2a 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -3878,6 +3878,17 @@ type Channel implements Node {Note: this API is currently in Feature Preview and can be subject to changes at later point."""availableShippingMethodsPerCountry(countries: [CountryCode!]): [ShippingMethodsPerCountry!]++ """+ Define the stock setting for this channel.++ Added in Saleor 3.7.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.++ Requires one of the following permissions: AUTHENTICATED_APP, AUTHENTICATED_STAFF_USER.+ """+ stockSettings: StockSettings!}"""@@ -4267,6 +4278,33 @@ enum WeightUnitsEnum {TONNE}+"""+Represents the channel stock settings.++Added in Saleor 3.7.++Note: this API is currently in Feature Preview and can be subject to changes at later point.+"""+type StockSettings {+ """+ Allocation strategy defines the preference of warehouses for allocations and reservations.+ """+ allocationStrategy: AllocationStrategyEnum!+}++"""+Determine the allocation strategy for the channel.++ PRIORITIZE_SORTING_ORDER - allocate stocks according to the warehouses' order+ within the channel++ PRIORITIZE_HIGH_STOCK - allocate stock in a warehouse with the most stock+"""+enum AllocationStrategyEnum {+ PRIORITIZE_SORTING_ORDER+ PRIORITIZE_HIGH_STOCK+}+"""Represents shipping method postal code rule."""type ShippingMethodPostalCodeRule implements Node {"""The ID of the object."""@@ -13640,6 +13678,23 @@ type Mutation {id: ID!): ChannelDeactivate+ """+ Reorder the warehouses of a channel.++ Added in Saleor 3.7.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.++ Requires one of the following permissions: MANAGE_CHANNELS.+ """+ channelReorderWarehouses(+ """ID of a channel."""+ channelId: ID!++ """The list of reordering operations for the given channel warehouses."""+ moves: [ReorderInput!]!+ ): ChannelReorderWarehouses+"""Creates an attribute."""attributeCreate("""Fields required to create an attribute."""@@ -19852,6 +19907,15 @@ input ChannelCreateInput {"""isActive flag."""isActive: Boolean+ """+ The channel stock settings.++ Added in Saleor 3.7.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ stockSettings: StockSettingsInput+"""List of shipping zones to assign to the channel."""addShippingZones: [ID!]@@ -19883,6 +19947,13 @@ input ChannelCreateInput {defaultCountry: CountryCode!}+input StockSettingsInput {+ """+ Allocation strategy options. Strategy defines the preference of warehouses for allocations and reservations.+ """+ allocationStrategy: AllocationStrategyEnum!+}+"""Update a channel.@@ -19898,6 +19969,15 @@ input ChannelUpdateInput {"""isActive flag."""isActive: Boolean+ """+ The channel stock settings.++ Added in Saleor 3.7.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ stockSettings: StockSettingsInput+"""List of shipping zones to assign to the channel."""addShippingZones: [ID!]@@ -19976,6 +20056,21 @@ type ChannelDeactivate {errors: [ChannelError!]!}+"""+Reorder the warehouses of a channel.++Added in Saleor 3.7.++Note: this API is currently in Feature Preview and can be subject to changes at later point.++Requires one of the following permissions: MANAGE_CHANNELS.+"""+type ChannelReorderWarehouses {+ """Channel within the warehouses are reordered."""+ channel: Channel+ errors: [ChannelError!]!+}+"""Creates an attribute."""type AttributeCreate {attribute: Attributediff --git a/saleor/graphql/warehouse/dataloaders.py b/saleor/graphql/warehouse/dataloaders.pyindex aed7382a4b..3567086fa4 100644--- a/saleor/graphql/warehouse/dataloaders.py+++ b/saleor/graphql/warehouse/dataloaders.py@@ -12,6 +12,7 @@ from ...channel.models import Channelfrom ...product.models import ProductVariantChannelListingfrom ...warehouse import WarehouseClickAndCollectOptionfrom ...warehouse.models import (+ ChannelWarehouse,PreorderReservation,Reservation,ShippingZone,@@ -495,9 +496,8 @@ class WarehousesByChannelIdLoader(DataLoader):context_key = "warehouse_by_channel"def batch_load(self, keys):- WarehouseChannel = Warehouse.channels.throughwarehouse_and_channel_in_pairs = (- WarehouseChannel.objects.using(self.database_connection_name)+ ChannelWarehouse.objects.using(self.database_connection_name).filter(channel_id__in=keys).values_list("warehouse_id", "channel_id"))diff --git a/saleor/order/tests/test_order.py b/saleor/order/tests/test_order.pyindex 2b61048dcf..8f5cc744d5 100644--- a/saleor/order/tests/test_order.py+++ b/saleor/order/tests/test_order.py@@ -616,7 +616,7 @@ def test_order_weight_change_line_quantity(staff_user, lines_info):line_info,new_quantity,line_info.quantity,- order.channel.slug,+ order.channel,get_plugins_manager(),)assert order.weight == _calculate_order_weight_from_lines(order)@@ -905,7 +905,7 @@ def test_ordered_item_change_quantity(staff_user, transactional_db, lines_info):lines_info[1],lines_info[1].quantity,0,- order.channel.slug,+ order.channel,get_plugins_manager(),)change_order_line_quantity(@@ -914,7 +914,7 @@ def test_ordered_item_change_quantity(staff_user, transactional_db, lines_info):lines_info[0],lines_info[0].quantity,0,- order.channel.slug,+ order.channel,get_plugins_manager(),)assert order.get_total_quantity() == 0@@ -934,7 +934,7 @@ def test_change_order_line_quantity_changes_total_prices(line_info,line_info.quantity,new_quantity,- order.channel.slug,+ order.channel,get_plugins_manager(),)assert line_info.line.total_price == line_info.line.unit_price * new_quantitydiff --git a/saleor/order/tests/test_order_utils.py b/saleor/order/tests/test_order_utils.pyindex 6a53103edb..837343bc85 100644--- a/saleor/order/tests/test_order_utils.py+++ b/saleor/order/tests/test_order_utils.py@@ -65,7 +65,7 @@ def test_change_quantity_generates_proper_event(line_info,previous_quantity,new_quantity,- order_with_lines.channel.slug,+ order_with_lines.channel,get_plugins_manager(),)@@ -117,7 +117,7 @@ def test_change_quantity_update_line_fields(line_info,line.quantity,new_quantity,- order_with_lines.channel.slug,+ order_with_lines.channel,get_plugins_manager(),)diff --git a/saleor/order/utils.py b/saleor/order/utils.pyindex 5952d1b74a..9b279a4cbc 100644--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@ -51,6 +51,7 @@ from .models import Order, OrderLineif TYPE_CHECKING:from ..app.models import App+ from ..channel.models import Channelfrom ..checkout.fetch import CheckoutInfofrom ..plugins.manager import PluginsManager@@ -302,7 +303,7 @@ def create_order_line(warehouse_pk=None,)],- channel.slug,+ channel,manager=manager,)@@ -337,7 +338,7 @@ def add_variant_to_order(line_info,old_quantity,new_quantity,- channel.slug,+ channel,manager=manager,send_event=False,)@@ -352,7 +353,7 @@ def add_variant_to_order(warehouse_pk=None,)],- channel.slug,+ channel,manager=manager,)@@ -437,7 +438,7 @@ def _update_allocations_for_line(line_info: OrderLineInfo,old_quantity: int,new_quantity: int,- channel_slug: str,+ channel: "Channel",manager: "PluginsManager",):if old_quantity == new_quantity:@@ -448,7 +449,7 @@ def _update_allocations_for_line(if old_quantity < new_quantity:line_info.quantity = new_quantity - old_quantity- increase_allocations([line_info], channel_slug, manager)+ increase_allocations([line_info], channel, manager)else:line_info.quantity = old_quantity - new_quantitydecrease_allocations([line_info], manager)@@ -460,7 +461,7 @@ def change_order_line_quantity(line_info,old_quantity: int,new_quantity: int,- channel_slug: str,+ channel: "Channel",manager: "PluginsManager",send_event=True,):@@ -469,7 +470,7 @@ def change_order_line_quantity(if new_quantity:if line.order.is_unconfirmed():_update_allocations_for_line(- line_info, old_quantity, new_quantity, channel_slug, manager+ line_info, old_quantity, new_quantity, channel, manager)line.quantity = new_quantitytotal_price_net_amount = line.quantity * line.unit_price_net_amountdiff --git a/saleor/warehouse/management.py b/saleor/warehouse/management.pyindex 114db7d151..53f8e68b47 100644--- a/saleor/warehouse/management.py+++ b/saleor/warehouse/management.py@@ -7,6 +7,7 @@ from django.db.models import F, Sumfrom django.db.models.expressions import Exists, OuterReffrom django.db.models.functions import Coalesce+from ..channel import AllocationStrategyfrom ..checkout.models import CheckoutLinefrom ..core.exceptions import (AllocationError,@@ -21,6 +22,7 @@ from ..plugins.manager import PluginsManagerfrom ..product.models import ProductVariant, ProductVariantChannelListingfrom .models import (Allocation,+ ChannelWarehouse,PreorderAllocation,PreorderReservation,Reservation,@@ -29,6 +31,7 @@ from .models import ()if TYPE_CHECKING:+ from ..channel.models import Channelfrom ..order.models import Order@@ -39,7 +42,7 @@ StockData = namedtuple("StockData", ["pk", "quantity"])def allocate_stocks(order_lines_info: Iterable["OrderLineInfo"],country_code: str,- channel_slug: str,+ channel: "Channel",manager: PluginsManager,collection_point_pk: Optional[str] = None,additional_filter_lookup: Optional[Dict[str, Any]] = None,@@ -61,6 +64,8 @@ def allocate_stocks(if not order_lines_info:return+ channel_slug = channel.slug+variants = [line_info.variant for line_info in order_lines_info]filter_lookup = {"product_variant__in": variants}@@ -83,24 +88,9 @@ def allocate_stocks()stocks_id = (stock.pop("id") for stock in stocks)- quantity_reservation_for_stocks: Dict = defaultdict(int)-- if check_reservations:- quantity_reservation = (- Reservation.objects.filter(- stock_id__in=stocks_id,- )- .not_expired()- .exclude_checkout_lines(checkout_lines or [])- .values("stock")- .annotate(- quantity_reserved=Coalesce(Sum("quantity_reserved"), 0),- )- ) # type: ignore- for reservation in quantity_reservation:- quantity_reservation_for_stocks[reservation["stock"]] += reservation[- "quantity_reserved"- ]+ quantity_reservation_for_stocks: Dict = _prepare_stock_to_reserved_quantity_map(+ checkout_lines, check_reservations, stocks_id+ )quantity_allocation_list = list(Allocation.objects.filter(@@ -116,17 +106,13 @@ def allocate_stocks("quantity_allocated_sum"]- def sort_stocks(stock_data):- # in case of click and collect order we should allocate stocks from- # collection point warehouse at the first place- if stock_data.pop("warehouse_id") == collection_point_pk:- return math.inf- return stock_data["quantity"] - quantity_allocation_for_stocks.get(- stock_data["pk"], 0- )-- # prioritize stocks with the highest quantity available- stocks.sort(key=sort_stocks, reverse=True)+ stocks = sort_stocks(+ channel.allocation_strategy,+ stocks,+ channel,+ quantity_allocation_for_stocks,+ collection_point_pk,+ )variant_to_stocks: Dict[str, List[StockData]] = defaultdict(list)for stock_data in stocks:@@ -173,6 +159,79 @@ def allocate_stocks()+def _prepare_stock_to_reserved_quantity_map(+ checkout_lines, check_reservations, stocks_id+):+ """Prepare stock id to quantity reserved map for provided stock ids."""+ quantity_reservation_for_stocks: Dict = defaultdict(int)++ if check_reservations:+ quantity_reservation = (+ Reservation.objects.filter(+ stock_id__in=stocks_id,+ )+ .not_expired()+ .exclude_checkout_lines(checkout_lines or [])+ .values("stock")+ .annotate(+ quantity_reserved=Coalesce(Sum("quantity_reserved"), 0),+ )+ ) # type: ignore+ for reservation in quantity_reservation:+ quantity_reservation_for_stocks[reservation["stock"]] += reservation[+ "quantity_reserved"+ ]+ return quantity_reservation_for_stocks+++def sort_stocks(+ allocation_strategy: str,+ stocks: List[dict],+ channel: "Channel",+ quantity_allocation_for_stocks: Dict[int, int],+ collection_point_pk: Optional[str] = None,+):+ warehouse_ids = [stock_data["warehouse_id"] for stock_data in stocks]+ channel_warehouse_ids = ChannelWarehouse.objects.filter(+ channel_id=channel.id, warehouse_id__in=warehouse_ids+ ).values_list("warehouse_id", flat=True)++ def sort_stocks_by_highest_stocks(stock_data):+ """Sort the stocks by the highest quantity available."""+ # in case of click and collect order we should allocate stocks from+ # collection point warehouse at the first place+ if stock_data.pop("warehouse_id") == collection_point_pk:+ return math.inf+ return stock_data["quantity"] - quantity_allocation_for_stocks.get(+ stock_data["pk"], 0+ )++ def sort_stocks_by_warehouse_sorting_order(stock_data):+ """Sort the stocks based on the warehouse within channel order."""+ # get the sort order for stocks warehouses within the channel+ sorted_warehouse_list = list(channel_warehouse_ids)++ warehouse_id = stock_data.pop("warehouse_id")+ # in case of click and collect order we should allocate stocks from+ # collection point warehouse at the first place+ if warehouse_id == collection_point_pk:+ return -math.inf+ return sorted_warehouse_list.index(warehouse_id)++ allocation_strategy_to_sort_method_and_reverse_option = {+ AllocationStrategy.PRIORITIZE_HIGH_STOCK: (sort_stocks_by_highest_stocks, True),+ AllocationStrategy.PRIORITIZE_SORTING_ORDER: (+ sort_stocks_by_warehouse_sorting_order,+ False,+ ),+ }+ sort_method, reverse = allocation_strategy_to_sort_method_and_reverse_option[+ allocation_strategy+ ]+ stocks.sort(key=sort_method, reverse=reverse)+ return stocks++def _create_allocations(line_info: "OrderLineInfo",stocks: List[StockData],@@ -340,7 +399,7 @@ def increase_stock(@traced_atomic_transaction()def increase_allocations(- lines_info: Iterable["OrderLineInfo"], channel_slug: str, manager: PluginsManager+ lines_info: Iterable["OrderLineInfo"], channel: "Channel", manager: PluginsManager):"""Increase allocation for order lines with appropriate quantity."""line_pks = [info.line.pk for info in lines_info]@@ -372,7 +431,7 @@ def increase_allocations(allocate_stocks(lines_info,lines_info[0].line.order.shipping_address.country.code, # type: ignore- channel_slug,+ channel,manager,)diff --git a/saleor/warehouse/migrations/0032_alter_channel_warehouse.py b/saleor/warehouse/migrations/0032_alter_channel_warehouse.pynew file mode 100644index 0000000000..3bfb1b637f--- /dev/null+++ b/saleor/warehouse/migrations/0032_alter_channel_warehouse.py@@ -0,0 +1,83 @@+# Generated by Django 3.2.14 on 2022-08-19 07:36++from django.db import migrations, models+import django.db.models.deletion+++class Migration(migrations.Migration):++ dependencies = [+ ("channel", "0004_create_default_channel"),+ ("warehouse", "0031_create_default_warehouse"),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(+ database_operations=[+ migrations.RunSQL(+ sql=(+ "ALTER TABLE warehouse_warehouse_channels "+ "RENAME TO warehouse_channelwarehouse"+ ),+ reverse_sql=(+ "ALTER TABLE warehouse_channelwarehouse "+ "RENAME TO warehouse_warehouse_channels"+ ),+ ),+ ],+ state_operations=[+ migrations.CreateModel(+ name="ChannelWarehouse",+ fields=[+ (+ "id",+ models.AutoField(+ auto_created=True,+ primary_key=True,+ serialize=False,+ verbose_name="ID",+ ),+ ),+ (+ "channel",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="channelwarehouse",+ to="channel.channel",+ ),+ ),+ (+ "warehouse",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="channelwarehouse",+ to="warehouse.warehouse",+ ),+ ),+ ],+ ),+ migrations.AlterField(+ model_name="warehouse",+ name="channels",+ field=models.ManyToManyField(+ related_name="warehouses",+ through="warehouse.ChannelWarehouse",+ to="channel.Channel",+ ),+ ),+ ],+ ),+ migrations.AddField(+ model_name="channelwarehouse",+ name="sort_order",+ field=models.IntegerField(db_index=True, editable=False, null=True),+ ),+ migrations.AlterUniqueTogether(+ name="channelwarehouse",+ unique_together={("channel", "warehouse")},+ ),+ migrations.AlterModelOptions(+ name="channelwarehouse",+ options={"ordering": ("sort_order", "pk")},+ ),+ ]diff --git a/saleor/warehouse/models.py b/saleor/warehouse/models.pyindex 80584f5602..77552528a9 100644--- a/saleor/warehouse/models.py+++ b/saleor/warehouse/models.py@@ -12,7 +12,7 @@ from django.utils import timezonefrom ..account.models import Addressfrom ..channel.models import Channelfrom ..checkout.models import CheckoutLine-from ..core.models import ModelWithMetadata+from ..core.models import ModelWithMetadata, SortableModelfrom ..order.models import OrderLinefrom ..product.models import Product, ProductVariant, ProductVariantChannelListingfrom ..shipping.models import ShippingZone@@ -144,11 +144,29 @@ class WarehouseQueryset(models.QuerySet):)+class ChannelWarehouse(SortableModel):+ channel = models.ForeignKey(+ Channel, related_name="channelwarehouse", on_delete=models.CASCADE+ )+ warehouse = models.ForeignKey(+ "Warehouse", related_name="channelwarehouse", on_delete=models.CASCADE+ )++ class Meta:+ unique_together = (("channel", "warehouse"),)+ ordering = ("sort_order", "pk")++ def get_ordering_queryset(self):+ return self.channel.channelwarehouse.all()++class Warehouse(ModelWithMetadata):id = models.UUIDField(default=uuid.uuid4, primary_key=True)name = models.CharField(max_length=250)slug = models.SlugField(max_length=255, unique=True, allow_unicode=True)- channels = models.ManyToManyField(Channel, related_name="warehouses")+ channels = models.ManyToManyField(+ Channel, related_name="warehouses", through=ChannelWarehouse+ )shipping_zones = models.ManyToManyField(ShippingZone, blank=True, related_name="warehouses")diff --git a/saleor/warehouse/reservations.py b/saleor/warehouse/reservations.pyindex a3eed33ae3..a31ea6c9d5 100644--- a/saleor/warehouse/reservations.py+++ b/saleor/warehouse/reservations.py@@ -9,9 +9,11 @@ from django.utils import timezonefrom ..core.exceptions import InsufficientStock, InsufficientStockDatafrom ..core.tracing import traced_atomic_transactionfrom ..product.models import ProductVariant, ProductVariantChannelListing+from .management import sort_stocksfrom .models import Allocation, PreorderReservation, Reservation, Stockif TYPE_CHECKING:+ from ..channel.models import Channelfrom ..checkout.fetch import CheckoutLineStockData = namedtuple("StockData", ["pk", "quantity"])@@ -22,7 +24,7 @@ def reserve_stocks_and_preorders(checkout_lines: Iterable["CheckoutLine"],variants: Iterable["ProductVariant"],country_code: str,- channel_slug: str,+ channel: "Channel",length_in_minutes: int,*,replace: bool = True,@@ -47,7 +49,7 @@ def reserve_stocks_and_preorders(stock_lines,stock_variants,country_code,- channel_slug,+ channel,length_in_minutes,replace=replace,)@@ -57,7 +59,7 @@ def reserve_stocks_and_preorders(preorder_lines,preorder_variants,country_code,- channel_slug,+ channel.slug,length_in_minutes,replace=replace,)@@ -67,7 +69,7 @@ def reserve_stocks(checkout_lines: Iterable["CheckoutLine"],variants: Iterable["ProductVariant"],country_code: str,- channel_slug: str,+ channel: "Channel",length_in_minutes: int,*,replace: bool = True,@@ -87,9 +89,9 @@ def reserve_stocks(stocks = list(Stock.objects.select_for_update(of=("self",))- .get_variants_stocks_for_country(country_code, channel_slug, variants)+ .get_variants_stocks_for_country(country_code, channel.slug, variants).order_by("pk")- .values("id", "product_variant", "pk", "quantity")+ .values("id", "product_variant", "pk", "quantity", "warehouse_id"))stocks_id = [stock.pop("id") for stock in stocks]@@ -123,6 +125,13 @@ def reserve_stocks("quantity_reserved_sum"]+ stocks = sort_stocks(+ channel.allocation_strategy,+ stocks,+ channel,+ quantity_allocation_for_stocks,+ )+variant_to_stocks: Dict[int, List[StockData]] = defaultdict(list)for stock_data in stocks:variant = stock_data.pop("product_variant")diff --git a/saleor/warehouse/tests/test_stock_management.py b/saleor/warehouse/tests/test_stock_management.pyindex 8a650594f6..d117bf966f 100644--- a/saleor/warehouse/tests/test_stock_management.py+++ b/saleor/warehouse/tests/test_stock_management.py@@ -4,6 +4,7 @@ import pytestfrom django.db.models import Sumfrom django.db.models.functions import Coalesce+from ...channel import AllocationStrategyfrom ...core.exceptions import InsufficientStockfrom ...order.fetch import OrderLineInfofrom ...order.models import OrderLine@@ -19,7 +20,7 @@ from ..management import (increase_allocations,increase_stock,)-from ..models import Allocation, PreorderAllocation+from ..models import Allocation, ChannelWarehouse, PreorderAllocationCOUNTRY_CODE = "US"@@ -31,7 +32,7 @@ def test_allocate_stocks(order_line, stock, channel_USD):line_data = OrderLineInfo(line=order_line, variant=order_line.variant, quantity=50)allocate_stocks(- [line_data], COUNTRY_CODE, channel_USD.slug, manager=get_plugins_manager()+ [line_data], COUNTRY_CODE, channel_USD, manager=get_plugins_manager())stock.refresh_from_db()@@ -41,7 +42,9 @@ def test_allocate_stocks(order_line, stock, channel_USD):assert allocation.quantity_allocated == stock.quantity_allocated == 50-def test_allocate_stocks_multiple_lines(order_line, order, product, stock, channel_USD):+def test_allocate_stocks_multiple_lines_the_highest_stock_strategy(+ order_line, order, product, stock, channel_USD+):stock.quantity = 100stock.save(update_fields=["quantity"])@@ -68,7 +71,7 @@ def test_allocate_stocks_multiple_lines(order_line, order, product, stock, channallocate_stocks([line_data_1, line_data_2],COUNTRY_CODE,- channel_USD.slug,+ channel_USD,manager=get_plugins_manager(),)@@ -82,13 +85,15 @@ def test_allocate_stocks_multiple_lines(order_line, order, product, stock, channassert allocation.quantity_allocated == stock_2.quantity_allocated == quantity_2-def test_allocate_stock_many_stocks(order_line, variant_with_many_stocks, channel_USD):+def test_allocate_stock_many_stocks_the_highest_stock_strategy(+ order_line, variant_with_many_stocks, channel_USD+):variant = variant_with_many_stocksstocks = variant.stocks.all()line_data = OrderLineInfo(line=order_line, variant=order_line.variant, quantity=5)allocate_stocks(- [line_data], COUNTRY_CODE, channel_USD.slug, manager=get_plugins_manager()+ [line_data], COUNTRY_CODE, channel_USD, manager=get_plugins_manager())allocations = Allocation.objects.filter(order_line=order_line, stock__in=stocks)@@ -96,7 +101,132 @@ def test_allocate_stock_many_stocks(order_line, variant_with_many_stocks, channeassert allocations[1].quantity_allocated == stocks[1].quantity_allocated == 1-def test_allocate_stock_with_reservations(+def test_allocate_stocks_the_highest_stock_strategy_with_collection_point(+ order_line, variant_with_many_stocks, channel_USD, warehouse_for_cc+):+ """Ensure that when the collection point is set as delivery method,+ the stock will be allocate in this warehouse."""+ variant = variant_with_many_stocks++ quantity = 5+ cc_stock = warehouse_for_cc.stock_set.first()+ cc_stock.quantity = quantity+ cc_stock.product_variant = variant+ cc_stock.save(update_fields=["quantity", "product_variant"])++ stocks = variant.stocks.all()++ line_data = OrderLineInfo(line=order_line, variant=order_line.variant, quantity=5)+ allocate_stocks(+ [line_data],+ COUNTRY_CODE,+ channel_USD,+ manager=get_plugins_manager(),+ collection_point_pk=warehouse_for_cc.pk,+ )++ allocations = Allocation.objects.filter(order_line=order_line, stock__in=stocks)+ assert len(allocations) == 1+ assert allocations[0].stock == cc_stock+ assert allocations[0].quantity_allocated == quantity+++def test_allocate_stock_many_stocks_prioritize_sorting_order_strategy(+ order_line, variant_with_many_stocks, channel_USD+):+ # given+ channel_USD.allocation_strategy = AllocationStrategy.PRIORITIZE_SORTING_ORDER+ channel_USD.save(update_fields=["allocation_strategy"])++ variant = variant_with_many_stocks+ stock_1, stock_2 = variant.stocks.all()++ channel_warehouse_1 = stock_1.warehouse.channelwarehouse.first()+ channel_warehouse_2 = stock_2.warehouse.channelwarehouse.first()++ channel_warehouse_2.sort_order = 0+ channel_warehouse_1.sort_order = 1+ ChannelWarehouse.objects.bulk_update(+ [channel_warehouse_1, channel_warehouse_2], ["sort_order"]+ )++ quantity = 5++ line_data = OrderLineInfo(+ line=order_line, variant=order_line.variant, quantity=quantity+ )++ # when+ allocate_stocks(+ [line_data], COUNTRY_CODE, channel_USD, manager=get_plugins_manager()+ )++ # then+ allocations = Allocation.objects.filter(+ order_line=order_line, stock__in=[stock_2, stock_1]+ )+ stock_1.refresh_from_db()+ stock_2.refresh_from_db()+ assert (+ allocations[0].quantity_allocated+ == stock_2.quantity_allocated+ == stock_2.quantity+ )+ assert (+ allocations[1].quantity_allocated+ == stock_1.quantity_allocated+ == quantity - stock_2.quantity+ )+++def test_allocate_stock_prioritize_sorting_order_strategy_with_collection_point(+ order_line, variant_with_many_stocks, channel_USD, warehouse_for_cc+):+ """Ensure that when the collection point is set as delivery method,+ the stock will be allocate in this warehouse."""+ # given+ channel_USD.allocation_strategy = AllocationStrategy.PRIORITIZE_SORTING_ORDER+ channel_USD.save(update_fields=["allocation_strategy"])++ variant = variant_with_many_stocks+ stock_1, stock_2 = variant.stocks.all()++ channel_warehouse_1 = stock_1.warehouse.channelwarehouse.first()+ channel_warehouse_2 = stock_2.warehouse.channelwarehouse.first()++ channel_warehouse_2.sort_order = 0+ channel_warehouse_1.sort_order = 1+ ChannelWarehouse.objects.bulk_update(+ [channel_warehouse_1, channel_warehouse_2], ["sort_order"]+ )++ quantity = 5+ cc_stock = warehouse_for_cc.stock_set.first()+ cc_stock.quantity = quantity+ cc_stock.product_variant = variant+ cc_stock.save(update_fields=["quantity", "product_variant"])++ line_data = OrderLineInfo(+ line=order_line, variant=order_line.variant, quantity=quantity+ )++ # when+ allocate_stocks(+ [line_data],+ COUNTRY_CODE,+ channel_USD,+ manager=get_plugins_manager(),+ collection_point_pk=warehouse_for_cc.pk,+ )++ # then+ allocations = Allocation.objects.filter(order_line=order_line)+ assert len(allocations) == 1+ assert allocations[0].stock == cc_stock+ assert allocations[0].quantity_allocated == quantity+++def test_allocate_stock_with_reservations_the_highest_stock_strategy(order_line,variant_with_many_stocks,channel_USD,@@ -109,7 +239,7 @@ def test_allocate_stock_with_reservations(allocate_stocks([line_data],COUNTRY_CODE,- channel_USD.slug,+ channel_USD,manager=get_plugins_manager(),check_reservations=True,)@@ -119,6 +249,57 @@ def test_allocate_stock_with_reservations(assert allocations[1].quantity_allocated == 1+def test_allocate_stock_with_reservations_prioritize_sorting_order_strategy(+ order_line,+ variant_with_many_stocks,+ channel_USD,+ checkout_line_with_one_reservation,+):+ # given+ # set the prioritize sorting order stratefy+ channel_USD.allocation_strategy = AllocationStrategy.PRIORITIZE_SORTING_ORDER+ channel_USD.save(update_fields=["allocation_strategy"])++ variant = variant_with_many_stocks+ stock_1, stock_2 = variant.stocks.all()++ channel_warehouse_1 = stock_1.warehouse.channelwarehouse.first()+ channel_warehouse_2 = stock_2.warehouse.channelwarehouse.first()++ # set the warehouse order+ channel_warehouse_2.sort_order = 0+ channel_warehouse_1.sort_order = 1+ ChannelWarehouse.objects.bulk_update(+ [channel_warehouse_1, channel_warehouse_2], ["sort_order"]+ )++ # change the reservation stock to first in stock in order+ reservation = checkout_line_with_one_reservation.reservations.first()+ reservation.quantity_reserved = 1+ reservation.stock = stock_2+ reservation.save(update_fields=["stock", "quantity_reserved"])++ line_data = OrderLineInfo(line=order_line, variant=order_line.variant, quantity=3)++ # when+ allocate_stocks(+ [line_data],+ COUNTRY_CODE,+ channel_USD,+ manager=get_plugins_manager(),+ check_reservations=True,+ )++ # then+ allocations = Allocation.objects.filter(+ order_line=order_line, stock__in=[stock_2, stock_1]+ )+ stock_1.refresh_from_db()+ stock_2.refresh_from_db()+ assert allocations[0].quantity_allocated == 2 == stock_2.quantity_allocated+ assert allocations[1].quantity_allocated == 1 == stock_1.quantity_allocated++def test_allocate_stock_insufficient_stock_due_to_reservations(order_line,variant_with_many_stocks,@@ -134,7 +315,7 @@ def test_allocate_stock_insufficient_stock_due_to_reservations(allocate_stocks([line_data],COUNTRY_CODE,- channel_USD.slug,+ channel_USD,manager=get_plugins_manager(),check_reservations=True,)@@ -161,7 +342,7 @@ def test_allocate_stock_many_stocks_partially_allocated(# whenallocate_stocks(- [line_data], COUNTRY_CODE, channel_USD.slug, manager=get_plugins_manager()+ [line_data], COUNTRY_CODE, channel_USD, manager=get_plugins_manager())# then@@ -187,7 +368,7 @@ def test_allocate_stock_partially_allocated_insufficient_stocks(line_data = OrderLineInfo(line=order_line, variant=order_line.variant, quantity=6)with pytest.raises(InsufficientStock):allocate_stocks(- [line_data], COUNTRY_CODE, channel_USD.slug, manager=get_plugins_manager()+ [line_data], COUNTRY_CODE, channel_USD, manager=get_plugins_manager())assert not Allocation.objects.filter(@@ -204,7 +385,7 @@ def test_allocate_stocks_no_channel_shipping_zones(order_line, stock, channel_USline_data = OrderLineInfo(line=order_line, variant=order_line.variant, quantity=50)with pytest.raises(InsufficientStock):allocate_stocks(- [line_data], COUNTRY_CODE, channel_USD.slug, manager=get_plugins_manager()+ [line_data], COUNTRY_CODE, channel_USD, manager=get_plugins_manager())@@ -217,7 +398,7 @@ def test_allocate_stock_insufficient_stocks(line_data = OrderLineInfo(line=order_line, variant=order_line.variant, quantity=10)with pytest.raises(InsufficientStock):allocate_stocks(- [line_data], COUNTRY_CODE, channel_USD.slug, manager=get_plugins_manager()+ [line_data], COUNTRY_CODE, channel_USD, manager=get_plugins_manager())assert not Allocation.objects.filter(@@ -254,7 +435,7 @@ def test_allocate_stock_insufficient_stocks_for_multiple_lines(allocate_stocks([line_data_1, line_data_2],COUNTRY_CODE,- channel_USD.slug,+ channel_USD,manager=get_plugins_manager(),)@@ -431,7 +612,7 @@ def test_increase_allocations(quantity, allocation):allocation.save(update_fields=["quantity_allocated"])increase_allocations(- [order_line_info], order_line.order.channel.slug, manager=get_plugins_manager()+ [order_line_info], order_line.order.channel, manager=get_plugins_manager())stock.refresh_from_db()@@ -464,7 +645,7 @@ def test_increase_allocation_insufficient_stock(allocation):with pytest.raises(InsufficientStock):increase_allocations([order_line_info],- order_line.order.channel.slug,+ order_line.order.channel,manager=get_plugins_manager(),)diff --git a/saleor/warehouse/tests/test_stock_reservations_management.py b/saleor/warehouse/tests/test_stock_reservations_management.pyindex 7b4fe196f0..a4ec00f146 100644--- a/saleor/warehouse/tests/test_stock_reservations_management.py+++ b/saleor/warehouse/tests/test_stock_reservations_management.py@@ -3,9 +3,10 @@ from datetime import timedeltaimport pytestfrom django.utils import timezone+from ...channel import AllocationStrategyfrom ...checkout.models import Checkoutfrom ...core.exceptions import InsufficientStock-from ..models import Reservation, Stock, Warehouse+from ..models import ChannelWarehouse, Reservation, Stock, Warehousefrom ..reservations import reserve_stocksCOUNTRY_CODE = "US"@@ -24,7 +25,7 @@ def test_reserve_stocks(checkout_line, channel_USD):[checkout_line],[checkout_line.variant],COUNTRY_CODE,- channel_USD.slug,+ channel_USD,RESERVATION_LENGTH,)@@ -43,7 +44,7 @@ def test_stocks_reservation_skips_prev_reservation_delete_if_replace_is_disabled[checkout_line],[checkout_line.variant],COUNTRY_CODE,- channel_USD.slug,+ channel_USD,RESERVATION_LENGTH,replace=False,)@@ -53,12 +54,12 @@ def test_stocks_reservation_skips_prev_reservation_delete_if_replace_is_disabled[checkout_line],[checkout_line.variant],COUNTRY_CODE,- channel_USD.slug,+ channel_USD,RESERVATION_LENGTH,)-def test_multiple_stocks_are_reserved_if_single_stock_is_not_enough(+def test_multiple_stocks_reserved_if_single_stock_is_not_enough_highest_stock_strategy(checkout_line, warehouse, shipping_zone, channel_USD):checkout_line.quantity = 5@@ -79,14 +80,14 @@ def test_multiple_stocks_are_reserved_if_single_stock_is_not_enough(secondary_warehouse.save()secondary_stock = Stock.objects.create(- warehouse=secondary_warehouse, product_variant=stock.product_variant, quantity=3+ warehouse=secondary_warehouse, product_variant=stock.product_variant, quantity=2)reserve_stocks([checkout_line],[checkout_line.variant],COUNTRY_CODE,- channel_USD.slug,+ channel_USD,RESERVATION_LENGTH,)@@ -104,6 +105,74 @@ def test_multiple_stocks_are_reserved_if_single_stock_is_not_enough(assert second_reservation.reserved_until > timezone.now() + timedelta(minutes=1)+def test_multiple_stocks_reserved_if_single_stock_is_not_enough_sorting_order_strategy(+ checkout_line, warehouse, shipping_zone, channel_USD+):+ # given+ # set the prioritize sorting order stratefy+ channel_USD.allocation_strategy = AllocationStrategy.PRIORITIZE_SORTING_ORDER+ channel_USD.save(update_fields=["allocation_strategy"])++ quantity = 5+ checkout_line.quantity = quantity+ checkout_line.save()++ stock = Stock.objects.get(product_variant=checkout_line.variant)+ stock_quantity = 4+ stock.quantity = stock_quantity+ stock.save(update_fields=["quantity"])++ secondary_warehouse = Warehouse.objects.create(+ address=warehouse.address,+ name="Warehouse 2",+ slug="warehouse-2",+ email=warehouse.email,+ )+ secondary_warehouse.shipping_zones.add(shipping_zone)+ secondary_warehouse.channels.add(channel_USD)+ secondary_warehouse.save()++ secondary_stock_quantity = 3+ secondary_stock = Stock.objects.create(+ warehouse=secondary_warehouse,+ product_variant=stock.product_variant,+ quantity=secondary_stock_quantity,+ )++ channel_warehouse_1 = stock.warehouse.channelwarehouse.first()+ channel_warehouse_2 = secondary_stock.warehouse.channelwarehouse.first()++ # set the warehouse order+ channel_warehouse_2.sort_order = 0+ channel_warehouse_1.sort_order = 1+ ChannelWarehouse.objects.bulk_update(+ [channel_warehouse_1, channel_warehouse_2], ["sort_order"]+ )++ # when+ reserve_stocks(+ [checkout_line],+ [checkout_line.variant],+ COUNTRY_CODE,+ channel_USD,+ RESERVATION_LENGTH,+ )++ # then+ stock.refresh_from_db()+ assert stock.quantity == stock_quantity++ second_reservation = Reservation.objects.get(+ checkout_line=checkout_line, stock=secondary_stock+ )+ assert second_reservation.quantity_reserved == secondary_stock_quantity+ assert second_reservation.reserved_until > timezone.now() + timedelta(minutes=1)++ reservation = Reservation.objects.get(checkout_line=checkout_line, stock=stock)+ assert reservation.quantity_reserved == quantity - secondary_stock_quantity+ assert reservation.reserved_until > timezone.now() + timedelta(minutes=1)++def test_stocks_reservation_removes_previous_reservations_for_checkout(checkout_line, channel_USD):@@ -125,7 +194,7 @@ def test_stocks_reservation_removes_previous_reservations_for_checkout([checkout_line],[checkout_line.variant],COUNTRY_CODE,- channel_USD.slug,+ channel_USD,RESERVATION_LENGTH,)@@ -148,7 +217,7 @@ def test_stock_reservation_fails_if_there_is_not_enough_stock_available([checkout_line],[checkout_line.variant],COUNTRY_CODE,- channel_USD.slug,+ channel_USD,RESERVATION_LENGTH,)@@ -164,7 +233,7 @@ def test_stock_reservation_fails_if_there_is_no_stock(checkout_line, channel_USD[checkout_line],[checkout_line.variant],COUNTRY_CODE,- channel_USD.slug,+ channel_USD,RESERVATION_LENGTH,)@@ -185,7 +254,7 @@ def test_stock_reservation_accounts_for_order_allocations([checkout_line],[variant],COUNTRY_CODE,- channel_USD.slug,+ channel_USD,RESERVATION_LENGTH,)@@ -222,6 +291,6 @@ def test_stock_reservation_accounts_for_order_allocations_and_reservations([checkout_line],[variant],COUNTRY_CODE,- channel_USD.slug,+ channel_USD,RESERVATION_LENGTH,)