Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add `stocks` field to `Warehouse` type (#15771)
Teddy Ondieki9a1989d412d1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ba53f1b495..86ed388a1d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,6 +14,7 @@ All notable, unreleased changes to this project will be documented in this file.### GraphQL API- Add `translatableContent` to all translation types; add translated object id to all translatable content types - #15617 by @zedzior- Add a `taxConfiguration` to a `Channel` - #15610 by @Air-t+- Add `stocks` to a `Warehouse` - #15771 by @teddyondieki- Deprecate the `taxTypes` query - #15802 by @maarcingebala### Saleor Appsdiff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 4fc3a62004..bce106a3c7 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -227,7 +227,7 @@ type Query {Requires one of the following permissions: MANAGE_PRODUCTS."""stock(- """ID of an warehouse"""+ """ID of a stock"""id: ID!): Stock @doc(category: "Products")@@ -3811,6 +3811,31 @@ type Warehouse implements Node & ObjectWithMetadata @doc(category: "Products") {last: Int): ShippingZoneCountableConnection!+ """+ Stocks that belong to this warehouse.++ Added in Saleor 3.20.++ Requires one of the following permissions: MANAGE_PRODUCTS, MANAGE_ORDERS.+ """+ stocks(+ """Return the elements in the list that come before the specified cursor."""+ before: String++ """Return the elements in the list that come after the specified cursor."""+ after: String++ """+ Retrieve the first n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.+ """+ first: Int++ """+ Retrieve the last n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.+ """+ last: Int+ ): StockCountableConnection+"""External ID of this warehouse.@@ -8749,6 +8774,23 @@ type ProductTranslatableContent implements Node @doc(category: "Products") {attributeValues: [AttributeValueTranslatableContent!]!}+type StockCountableConnection @doc(category: "Products") {+ """Pagination data for this connection."""+ pageInfo: PageInfo!+ edges: [StockCountableEdge!]!++ """A total count of items in the collection."""+ totalCount: Int+}++type StockCountableEdge @doc(category: "Products") {+ """The item at the end of the edge."""+ node: Stock!++ """A cursor for use in pagination."""+ cursor: String!+}+type WarehouseCountableConnection @doc(category: "Products") {"""Pagination data for this connection."""pageInfo: PageInfo!@@ -10123,23 +10165,6 @@ type TaxCountryConfiguration @doc(category: "Taxes") {taxClassCountryRates: [TaxClassCountryRate!]!}-type StockCountableConnection @doc(category: "Products") {- """Pagination data for this connection."""- pageInfo: PageInfo!- edges: [StockCountableEdge!]!-- """A total count of items in the collection."""- totalCount: Int-}--type StockCountableEdge @doc(category: "Products") {- """The item at the end of the edge."""- node: Stock!-- """A cursor for use in pagination."""- cursor: String!-}-input StockFilterInput @doc(category: "Products") {quantity: Floatsearch: Stringdiff --git a/saleor/graphql/warehouse/dataloaders.py b/saleor/graphql/warehouse/dataloaders.pyindex eb517985c4..0261adac02 100644--- a/saleor/graphql/warehouse/dataloaders.py+++ b/saleor/graphql/warehouse/dataloaders.py@@ -672,6 +672,19 @@ class StockByIdLoader(DataLoader):return [stocks.get(key) for key in keys]+class StocksByWarehouseIdLoader(DataLoader):+ context_key = "stocks_by_warehouse"++ def batch_load(self, keys):+ stocks = Stock.objects.using(self.database_connection_name).filter(+ warehouse_id__in=keys+ )+ stocks_map = defaultdict(list)+ for stock in stocks:+ stocks_map[stock.warehouse_id].append(stock)+ return [stocks_map.get(warehouse_id, []) for warehouse_id in keys]++class WarehousesByChannelIdLoader(DataLoader):context_key = "warehouse_by_channel"diff --git a/saleor/graphql/warehouse/schema.py b/saleor/graphql/warehouse/schema.pyindex 36107bd20e..22dc14b820 100644--- a/saleor/graphql/warehouse/schema.py+++ b/saleor/graphql/warehouse/schema.py@@ -89,7 +89,7 @@ class StockQueries(graphene.ObjectType):stock = PermissionsField(Stock,description="Look up a stock by ID",- id=graphene.ID(required=True, description="ID of an warehouse"),+ id=graphene.ID(required=True, description="ID of a stock"),permissions=[ProductPermissions.MANAGE_PRODUCTS],doc_category=DOC_CATEGORY_PRODUCTS,)diff --git a/saleor/graphql/warehouse/tests/queries/test_warehouse.py b/saleor/graphql/warehouse/tests/queries/test_warehouse.pyindex 73c844295b..124a54fcd2 100644--- a/saleor/graphql/warehouse/tests/queries/test_warehouse.py+++ b/saleor/graphql/warehouse/tests/queries/test_warehouse.py@@ -1,5 +1,6 @@import graphene+from ....core.utils import from_global_id_or_errorfrom ....tests.utils import (assert_no_permission,get_graphql_content,@@ -23,6 +24,13 @@ query warehouse($id: ID!){}}}+ stocks(first: 50){+ edges{+ node{+ id+ }+ }+ }address {streetAddress1streetAddress2@@ -56,9 +64,15 @@ def test_warehouse_query(staff_api_client, warehouse, permission_manage_productsshipping_zones = queried_warehouse["shippingZones"]["edges"]assert len(shipping_zones) == warehouse.shipping_zones.count()queried_shipping_zone = shipping_zones[0]["node"]- shipipng_zone = warehouse.shipping_zones.first()- assert queried_shipping_zone["name"] == shipipng_zone.name- assert len(queried_shipping_zone["countries"]) == len(shipipng_zone.countries)+ shipping_zone = warehouse.shipping_zones.first()+ assert queried_shipping_zone["name"] == shipping_zone.name+ assert len(queried_shipping_zone["countries"]) == len(shipping_zone.countries)++ stocks = queried_warehouse["stocks"]["edges"]+ assert len(stocks) == warehouse.stock_set.count()+ stock_ids = set(warehouse.stock_set.values_list("id", flat=True))+ for stock in stocks:+ assert int(from_global_id_or_error(stock["node"]["id"])[1]) in stock_idsaddress = warehouse.addressqueried_address = queried_warehouse["address"]@@ -89,9 +103,15 @@ def test_warehouse_query_as_staff_with_manage_orders(shipping_zones = queried_warehouse["shippingZones"]["edges"]assert len(shipping_zones) == warehouse.shipping_zones.count()queried_shipping_zone = shipping_zones[0]["node"]- shipipng_zone = warehouse.shipping_zones.first()- assert queried_shipping_zone["name"] == shipipng_zone.name- assert len(queried_shipping_zone["countries"]) == len(shipipng_zone.countries)+ shipping_zone = warehouse.shipping_zones.first()+ assert queried_shipping_zone["name"] == shipping_zone.name+ assert len(queried_shipping_zone["countries"]) == len(shipping_zone.countries)++ stocks = queried_warehouse["stocks"]["edges"]+ assert len(stocks) == warehouse.stock_set.count()+ stock_ids = set(warehouse.stock_set.values_list("id", flat=True))+ for stock in stocks:+ assert int(from_global_id_or_error(stock["node"]["id"])[1]) in stock_idsaddress = warehouse.addressqueried_address = queried_warehouse["address"]@@ -99,6 +119,35 @@ def test_warehouse_query_as_staff_with_manage_orders(assert queried_address["postalCode"] == address.postal_code+QUERY_WAREHOUSE_WITHOUT_STOCKS = """+query warehouse($id: ID!){+ warehouse(id: $id) {+ id+ name+ companyName+ shippingZones(first: 100) {+ edges {+ node {+ name+ countries {+ country+ }+ }+ }+ }+ address {+ streetAddress1+ streetAddress2+ postalCode+ city+ phone+ }+ }+}+"""++def test_warehouse_query_as_staff_with_manage_shipping(staff_api_client, warehouse, permission_manage_shipping):@@ -107,7 +156,7 @@ def test_warehouse_query_as_staff_with_manage_shipping(# whenresponse = staff_api_client.post_graphql(- QUERY_WAREHOUSE,+ QUERY_WAREHOUSE_WITHOUT_STOCKS,variables={"id": warehouse_id},permissions=[permission_manage_shipping],)@@ -122,9 +171,9 @@ def test_warehouse_query_as_staff_with_manage_shipping(shipping_zones = queried_warehouse["shippingZones"]["edges"]assert len(shipping_zones) == warehouse.shipping_zones.count()queried_shipping_zone = shipping_zones[0]["node"]- shipipng_zone = warehouse.shipping_zones.first()- assert queried_shipping_zone["name"] == shipipng_zone.name- assert len(queried_shipping_zone["countries"]) == len(shipipng_zone.countries)+ shipping_zone = warehouse.shipping_zones.first()+ assert queried_shipping_zone["name"] == shipping_zone.name+ assert len(queried_shipping_zone["countries"]) == len(shipping_zone.countries)address = warehouse.addressqueried_address = queried_warehouse["address"]@@ -132,6 +181,23 @@ def test_warehouse_query_as_staff_with_manage_shipping(assert queried_address["postalCode"] == address.postal_code+def test_warehouse_query_as_staff_with_manage_shipping_no_access_to_stocks(+ staff_api_client, warehouse, permission_manage_shipping+):+ # given+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)++ # when+ response = staff_api_client.post_graphql(+ QUERY_WAREHOUSE,+ variables={"id": warehouse_id},+ permissions=[permission_manage_shipping],+ )++ # then+ assert_no_permission(response)++def test_warehouse_query_as_staff_with_manage_apps(staff_api_client, warehouse, permission_manage_apps):diff --git a/saleor/graphql/warehouse/types.py b/saleor/graphql/warehouse/types.pyindex 4cd2c16149..7a63b9c61d 100644--- a/saleor/graphql/warehouse/types.py+++ b/saleor/graphql/warehouse/types.py@@ -14,6 +14,7 @@ from ..core.context import get_database_connection_namefrom ..core.descriptions import (ADDED_IN_31,ADDED_IN_310,+ ADDED_IN_320,DEPRECATED_IN_3X_FIELD,DEPRECATED_IN_3X_INPUT,)@@ -28,7 +29,7 @@ from ..core.types import (from ..meta.types import ObjectWithMetadatafrom ..product.dataloaders import ProductVariantByIdLoaderfrom ..site.dataloaders import load_site_callback-from .dataloaders import WarehouseByIdLoader+from .dataloaders import StocksByWarehouseIdLoader, WarehouseByIdLoaderfrom .enums import WarehouseClickAndCollectOptionEnum@@ -114,6 +115,14 @@ class Warehouse(ModelObjectType[models.Warehouse]):required=True,description="Shipping zones supported by the warehouse.",)+ stocks = ConnectionField(+ "saleor.graphql.warehouse.types.StockCountableConnection",+ description="Stocks that belong to this warehouse." + ADDED_IN_320,+ permissions=[+ ProductPermissions.MANAGE_PRODUCTS,+ OrderPermissions.MANAGE_ORDERS,+ ],+ )external_reference = graphene.String(description=f"External ID of this warehouse. {ADDED_IN_310}", required=False)@@ -143,6 +152,17 @@ class Warehouse(ModelObjectType[models.Warehouse]):return slice+ @staticmethod+ def resolve_stocks(root, info: ResolveInfo, **kwargs):+ def _resolve_stocks(stocks):+ return create_connection_slice(+ stocks, info, kwargs, StockCountableConnection+ )++ return (+ StocksByWarehouseIdLoader(info.context).load(root.id).then(_resolve_stocks)+ )+@staticmethoddef resolve_address(root, info: ResolveInfo):if hasattr(root, "is_object_deleted") and root.is_object_deleted: