Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Merge stock and warehouse modules into one
Mira Szewczykf24f534bb660
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex 4e02a93065..b17f9e51db 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -40,8 +40,8 @@ from ..order.actions import order_createdfrom ..order.emails import send_order_confirmation, send_staff_order_confirmationfrom ..order.models import Order, OrderLinefrom ..shipping.models import ShippingMethod-from ..stock.availability import check_stock_quantity-from ..stock.management import allocate_stock+from ..warehouse.availability import check_stock_quantity+from ..warehouse.management import allocate_stockfrom . import AddressTypefrom .models import Checkout, CheckoutLinediff --git a/saleor/core/permissions.py b/saleor/core/permissions.pyindex f888930cb1..f3a1d98356 100644--- a/saleor/core/permissions.py+++ b/saleor/core/permissions.py@@ -57,7 +57,7 @@ class SitePermissions(BasePermissionEnum):class StockPermissions(BasePermissionEnum):- MANAGE_STOCKS = "stock.manage_stocks"+ MANAGE_STOCKS = "warehouse.manage_stocks"class WarehousePermissions(BasePermissionEnum):diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.pyindex 46adf1b4dc..00cb9f192b 100644--- a/saleor/core/utils/random_data.py+++ b/saleor/core/utils/random_data.py@@ -56,9 +56,8 @@ from ...product.thumbnails import (create_product_thumbnails,)from ...shipping.models import ShippingMethod, ShippingMethodType, ShippingZone-from ...stock.management import increase_stock-from ...stock.models import Stock-from ...warehouse.models import Warehouse+from ...warehouse.management import increase_stock+from ...warehouse.models import Stock, Warehousefake = Factory.create()PRODUCTS_LIST_DIR = "products-list/"diff --git a/saleor/data_feeds/google_merchant.py b/saleor/data_feeds/google_merchant.pyindex 58f63dc1a9..026d813da4 100644--- a/saleor/data_feeds/google_merchant.py+++ b/saleor/data_feeds/google_merchant.py@@ -13,7 +13,7 @@ from ..core.taxes import zero_moneyfrom ..discount import DiscountInfofrom ..discount.utils import fetch_discountsfrom ..product.models import Attribute, AttributeValue, Category, ProductVariant-from ..stock.availability import is_variant_in_stock+from ..warehouse.availability import is_variant_in_stockCATEGORY_SEPARATOR = " > "diff --git a/saleor/graphql/api.py b/saleor/graphql/api.pyindex 37eb914bcf..2107832e92 100644--- a/saleor/graphql/api.py+++ b/saleor/graphql/api.py@@ -13,9 +13,13 @@ from .payment.schema import PaymentMutations, PaymentQueriesfrom .product.schema import ProductMutations, ProductQueriesfrom .shipping.schema import ShippingMutations, ShippingQueriesfrom .shop.schema import ShopMutations, ShopQueries-from .stock.schema import StockMutations, StockQueriesfrom .translations.schema import TranslationQueries-from .warehouse.schema import WarehouseMutations, WarehouseQueries+from .warehouse.schema import (+ StockMutations,+ StockQueries,+ WarehouseMutations,+ WarehouseQueries,+)from .webhook.schema import WebhookMutations, WebhookQueriesfrom .wishlist.schema import WishlistMutationsdiff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.pyindex 3d60da330b..ec2874acaa 100644--- a/saleor/graphql/checkout/mutations.py+++ b/saleor/graphql/checkout/mutations.py@@ -33,7 +33,7 @@ from ...payment import PaymentError, gateway, models as payment_modelsfrom ...payment.interface import AddressDatafrom ...payment.utils import store_customer_idfrom ...product import models as product_models-from ...stock.availability import check_stock_quantity, get_available_quantity+from ...warehouse.availability import check_stock_quantity, get_available_quantityfrom ..account.i18n import I18nMixinfrom ..account.types import AddressInput, Userfrom ..core.mutations import (diff --git a/saleor/graphql/core/enums.py b/saleor/graphql/core/enums.pyindex 5366ce3ec7..7ad821529b 100644--- a/saleor/graphql/core/enums.py+++ b/saleor/graphql/core/enums.py@@ -13,7 +13,6 @@ from ...order import error_codes as order_error_codesfrom ...payment import error_codes as payment_error_codesfrom ...product import error_codes as product_error_codesfrom ...shipping import error_codes as shipping_error_codes-from ...stock import error_codes as stock_error_codesfrom ...warehouse import error_codes as warehouse_error_codesfrom ...webhook import error_codes as webhook_error_codesfrom ...wishlist import error_codes as wishlist_error_codes@@ -95,7 +94,7 @@ PaymentErrorCode = graphene.Enum.from_enum(payment_error_codes.PaymentErrorCode)ProductErrorCode = graphene.Enum.from_enum(product_error_codes.ProductErrorCode)ShopErrorCode = graphene.Enum.from_enum(shop_error_codes.ShopErrorCode)ShippingErrorCode = graphene.Enum.from_enum(shipping_error_codes.ShippingErrorCode)-StockErrorCode = graphene.Enum.from_enum(stock_error_codes.StockErorrCode)+StockErrorCode = graphene.Enum.from_enum(warehouse_error_codes.StockErorrCode)WarehouseErrorCode = graphene.Enum.from_enum(warehouse_error_codes.WarehouseErrorCode)WebhookErrorCode = graphene.Enum.from_enum(webhook_error_codes.WebhookErrorCode)WishlistErrorCode = graphene.Enum.from_enum(wishlist_error_codes.WishlistErrorCode)diff --git a/saleor/graphql/order/mutations/draft_orders.py b/saleor/graphql/order/mutations/draft_orders.pyindex 7f78926293..33a5765b80 100644--- a/saleor/graphql/order/mutations/draft_orders.py+++ b/saleor/graphql/order/mutations/draft_orders.py@@ -18,7 +18,7 @@ from ....order.utils import (recalculate_order,update_order_prices,)-from ....stock.availability import check_stock_quantity, get_available_quantity+from ....warehouse.availability import check_stock_quantity, get_available_quantityfrom ...account.i18n import I18nMixinfrom ...account.types import AddressInputfrom ...core.mutations import BaseMutation, ModelDeleteMutation, ModelMutationdiff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.pyindex e33649918a..5a3b4df56a 100644--- a/saleor/graphql/product/types/products.py+++ b/saleor/graphql/product/types/products.py@@ -20,8 +20,8 @@ from ....product.utils.availability import (get_variant_availability,)from ....product.utils.costs import get_margin_for_variant, get_product_costs_data-from ....stock import models as stock_models-from ....stock.availability import (+from ....warehouse import models as stock_models+from ....warehouse.availability import (get_available_quantity,get_available_quantity_for_customer,is_product_in_stock,@@ -41,7 +41,6 @@ from ...core.types import (TaxType,)from ...decorators import permission_required-from ...stock.types import Stockfrom ...translations.fields import TranslationFieldfrom ...translations.types import (CategoryTranslation,@@ -50,6 +49,7 @@ from ...translations.types import (ProductVariantTranslation,)from ...utils import get_database_id, reporting_period_to_date+from ...warehouse.types import Stockfrom ..filters import AttributeFilterInputfrom ..resolvers import resolve_attributesfrom .attributes import Attribute, SelectedAttributediff --git a/saleor/graphql/stock/__init__.py b/saleor/graphql/stock/__init__.pydeleted file mode 100644index e69de29bb2..0000000000diff --git a/saleor/graphql/stock/filters.py b/saleor/graphql/stock/filters.pydeleted file mode 100644index 0a2cd593f5..0000000000--- a/saleor/graphql/stock/filters.py+++ /dev/null@@ -1,33 +0,0 @@-import django_filters--from ...stock.models import Stock-from ..core.types import FilterInputObjectType-from ..utils import filter_by_query_param---def filter_search(qs, _, value):- search_fields = [- "product_variant__product__name",- "product_variant__name",- "warehouse__name",- "warehouse__company_name",- ]- if value:- qs = qs.select_related("product_variant", "warehouse").prefetch_related(- "product_variant__product"- )- qs = filter_by_query_param(qs, value, search_fields)- return qs---class StockFilter(django_filters.FilterSet):- search = django_filters.CharFilter(method=filter_search)-- class Meta:- model = Stock- fields = ["quantity", "quantity_allocated"]---class StockFilterInput(FilterInputObjectType):- class Meta:- filterset_class = StockFilterdiff --git a/saleor/graphql/stock/mutations.py b/saleor/graphql/stock/mutations.pydeleted file mode 100644index 06a4b147bd..0000000000--- a/saleor/graphql/stock/mutations.py+++ /dev/null@@ -1,60 +0,0 @@-import graphene--from ...core.permissions import StockPermissions-from ...stock import models-from ..core.mutations import ModelBulkDeleteMutation, ModelDeleteMutation, ModelMutation-from ..core.types.common import StockError-from .types import StockInput---class StockCreate(ModelMutation):- class Arguments:- input = StockInput(- required=True, description="Fields required to create stock."- )-- class Meta:- description = "Creates new stock."- model = models.Stock- permissions = (StockPermissions.MANAGE_STOCKS,)- error_type_class = StockError- error_type_field = "stock_errors"---class StockUpdate(ModelMutation):- class Arguments:- input = StockInput(- required=True, description="Fields required to update stock."- )- id = graphene.ID(required=True, description="ID of stock to update.")-- class Meta:- model = models.Stock- permissions = (StockPermissions.MANAGE_STOCKS,)- description = "Update given stock."- error_type_class = StockError- error_type_field = "stock_error"---class StockDelete(ModelDeleteMutation):- class Arguments:- id = graphene.ID(required=True, description="ID of stock to delete.")-- class Meta:- model = models.Stock- permissions = (StockPermissions.MANAGE_STOCKS,)- description = "Deletes selected stock."- erorr_type_class = StockError- error_type_field = "stock_error"---class StockBulkDelete(ModelBulkDeleteMutation):- class Arguments:- ids = graphene.List(graphene.ID, required=True)-- class Meta:- model = models.Stock- permissions = (StockPermissions.MANAGE_STOCKS,)- description = "Deletes stocks in bulk"- error_type_class = StockError- error_type_field = "stock_error"diff --git a/saleor/graphql/stock/schema.py b/saleor/graphql/stock/schema.pydeleted file mode 100644index 1090acfd38..0000000000--- a/saleor/graphql/stock/schema.py+++ /dev/null@@ -1,42 +0,0 @@-import graphene-import graphene_django_optimizer as gql_optimizer--from ...core.permissions import StockPermissions-from ...stock import models-from ..core.fields import FilterInputConnectionField-from ..decorators import permission_required-from .filters import StockFilterInput-from .mutations import StockBulkDelete, StockCreate, StockDelete, StockUpdate-from .types import Stock---class StockQueries(graphene.ObjectType):- stock = graphene.Field(- Stock,- description="Look up a stock by ID",- id=graphene.ID(required=True, description="ID of an warehouse"),- )- stocks = FilterInputConnectionField(- Stock,- description="List of stocks.",- filter=StockFilterInput(),- query=graphene.String(),- )-- @permission_required(StockPermissions.MANAGE_STOCKS)- def resolve_stock(self, info, **kwargs):- stock_id = kwargs.get("id")- stock = graphene.Node.get_node_from_global_id(info, stock_id, Stock)- return stock-- @permission_required(StockPermissions.MANAGE_STOCKS)- def resolve_stocks(self, info, **data):- qs = models.Stock.objects.all()- return gql_optimizer.query(qs, info)---class StockMutations(graphene.ObjectType):- create_stock = StockCreate.Field()- update_stock = StockUpdate.Field()- delete_stock = StockDelete.Field()- bulk_delete_stock = StockBulkDelete.Field()diff --git a/saleor/graphql/stock/types.py b/saleor/graphql/stock/types.pydeleted file mode 100644index deb05d97b3..0000000000--- a/saleor/graphql/stock/types.py+++ /dev/null@@ -1,32 +0,0 @@-import graphene--from ...core.permissions import StockPermissions-from ...stock import models-from ...stock.availability import get_available_quantity_for_customer-from ..core.connection import CountableDjangoObjectType-from ..decorators import permission_required---class StockInput(graphene.InputObjectType):- product_variant = graphene.ID(- required=True, description="Product variant assiociated with stock."- )- warehouse = graphene.ID(- required=True, description="Warehouse in which stock is lockated."- )- quantity = graphene.Int(description="Quantity of items available for sell.")- quantity_allocated = graphene.Int(description="Quantity allocated for orders.")---class Stock(CountableDjangoObjectType):- available = graphene.Int(description="Quantity of a product available for sale.")-- class Meta:- description = "Represents stock."- model = models.Stock- interfaces = [graphene.relay.Node]-- @staticmethod- @permission_required(StockPermissions.MANAGE_STOCKS)- def resolve_available(root, *_args):- return get_available_quantity_for_customer(root)diff --git a/saleor/graphql/warehouse/filters.py b/saleor/graphql/warehouse/filters.pyindex 23fee1f970..9d6f149d4b 100644--- a/saleor/graphql/warehouse/filters.py+++ b/saleor/graphql/warehouse/filters.py@@ -1,6 +1,6 @@import django_filters-from ...warehouse.models import Warehouse+from ...warehouse.models import Stock, Warehousefrom ..core.types import FilterInputObjectTypefrom ..utils import filter_by_query_param@@ -9,7 +9,7 @@ def prefech_qs_for_filter(qs):return qs.select_related("address")-def filter_search(qs, _, value):+def filter_search_warehouse(qs, _, value):search_fields = ["name","company_name",@@ -27,8 +27,23 @@ def filter_search(qs, _, value):return qs+def filter_search_stock(qs, _, value):+ search_fields = [+ "product_variant__product__name",+ "product_variant__name",+ "warehouse__name",+ "warehouse__company_name",+ ]+ if value:+ qs = qs.select_related("product_variant", "warehouse").prefetch_related(+ "product_variant__product"+ )+ qs = filter_by_query_param(qs, value, search_fields)+ return qs++class WarehouseFilter(django_filters.FilterSet):- search = django_filters.CharFilter(method=filter_search)+ search = django_filters.CharFilter(method=filter_search_warehouse)class Meta:model = Warehouse@@ -38,3 +53,16 @@ class WarehouseFilter(django_filters.FilterSet):class WarehouseFilterInput(FilterInputObjectType):class Meta:filterset_class = WarehouseFilter+++class StockFilter(django_filters.FilterSet):+ search = django_filters.CharFilter(method=filter_search_stock)++ class Meta:+ model = Stock+ fields = ["quantity", "quantity_allocated"]+++class StockFilterInput(FilterInputObjectType):+ class Meta:+ filterset_class = StockFilterdiff --git a/saleor/graphql/warehouse/mutations.py b/saleor/graphql/warehouse/mutations.pyindex 81e3c744b4..7c04b703eb 100644--- a/saleor/graphql/warehouse/mutations.py+++ b/saleor/graphql/warehouse/mutations.py@@ -1,14 +1,14 @@import graphenefrom django.core.exceptions import ValidationError-from ...core.permissions import WarehousePermissions+from ...core.permissions import StockPermissions, WarehousePermissionsfrom ...warehouse import modelsfrom ...warehouse.error_codes import WarehouseErrorCodefrom ...warehouse.validation import validate_warehouse_count # type: ignorefrom ..account.i18n import I18nMixin-from ..core.mutations import ModelDeleteMutation, ModelMutation-from ..core.types.common import WarehouseError-from .types import WarehouseCreateInput, WarehouseUpdateInput+from ..core.mutations import ModelBulkDeleteMutation, ModelDeleteMutation, ModelMutation+from ..core.types.common import StockError, WarehouseError+from .types import StockInput, WarehouseCreateInput, WarehouseUpdateInputADDRESS_FIELDS = ["street_address_1",@@ -93,3 +93,56 @@ class WarehouseDelete(ModelDeleteMutation):class Arguments:id = graphene.ID(description="ID of a warehouse to delete.", required=True)+++class StockCreate(ModelMutation):+ class Arguments:+ input = StockInput(+ required=True, description="Fields required to create stock."+ )++ class Meta:+ description = "Creates new stock."+ model = models.Stock+ permissions = (StockPermissions.MANAGE_STOCKS,)+ error_type_class = StockError+ error_type_field = "stock_errors"+++class StockUpdate(ModelMutation):+ class Arguments:+ input = StockInput(+ required=True, description="Fields required to update stock."+ )+ id = graphene.ID(required=True, description="ID of stock to update.")++ class Meta:+ model = models.Stock+ permissions = (StockPermissions.MANAGE_STOCKS,)+ description = "Update given stock."+ error_type_class = StockError+ error_type_field = "stock_error"+++class StockDelete(ModelDeleteMutation):+ class Arguments:+ id = graphene.ID(required=True, description="ID of stock to delete.")++ class Meta:+ model = models.Stock+ permissions = (StockPermissions.MANAGE_STOCKS,)+ description = "Deletes selected stock."+ erorr_type_class = StockError+ error_type_field = "stock_error"+++class StockBulkDelete(ModelBulkDeleteMutation):+ class Arguments:+ ids = graphene.List(graphene.ID, required=True)++ class Meta:+ model = models.Stock+ permissions = (StockPermissions.MANAGE_STOCKS,)+ description = "Deletes stocks in bulk"+ error_type_class = StockError+ error_type_field = "stock_error"diff --git a/saleor/graphql/warehouse/schema.py b/saleor/graphql/warehouse/schema.pyindex 59cfa65186..0a85d7469e 100644--- a/saleor/graphql/warehouse/schema.py+++ b/saleor/graphql/warehouse/schema.py@@ -1,13 +1,21 @@import grapheneimport graphene_django_optimizer as gql_optimizer-from ...core.permissions import WarehousePermissions+from ...core.permissions import StockPermissions, WarehousePermissionsfrom ...warehouse import modelsfrom ..core.fields import FilterInputConnectionFieldfrom ..decorators import permission_required-from .filters import WarehouseFilterInput-from .mutations import WarehouseCreate, WarehouseDelete, WarehouseUpdate-from .types import Warehouse+from .filters import StockFilterInput, WarehouseFilterInput+from .mutations import (+ StockBulkDelete,+ StockCreate,+ StockDelete,+ StockUpdate,+ WarehouseCreate,+ WarehouseDelete,+ WarehouseUpdate,+)+from .types import Stock, Warehouseclass WarehouseQueries(graphene.ObjectType):@@ -38,3 +46,35 @@ class WarehouseMutations(graphene.ObjectType):create_warehouse = WarehouseCreate.Field()update_warehouse = WarehouseUpdate.Field()delete_warehouse = WarehouseDelete.Field()+++class StockQueries(graphene.ObjectType):+ stock = graphene.Field(+ Stock,+ description="Look up a stock by ID",+ id=graphene.ID(required=True, description="ID of an warehouse"),+ )+ stocks = FilterInputConnectionField(+ Stock,+ description="List of stocks.",+ filter=StockFilterInput(),+ query=graphene.String(),+ )++ @permission_required(StockPermissions.MANAGE_STOCKS)+ def resolve_stock(self, info, **kwargs):+ stock_id = kwargs.get("id")+ stock = graphene.Node.get_node_from_global_id(info, stock_id, Stock)+ return stock++ @permission_required(StockPermissions.MANAGE_STOCKS)+ def resolve_stocks(self, info, **data):+ qs = models.Stock.objects.all()+ return gql_optimizer.query(qs, info)+++class StockMutations(graphene.ObjectType):+ create_stock = StockCreate.Field()+ update_stock = StockUpdate.Field()+ delete_stock = StockDelete.Field()+ bulk_delete_stock = StockBulkDelete.Field()diff --git a/saleor/graphql/warehouse/types.py b/saleor/graphql/warehouse/types.pyindex 7e8313e1f3..6fb154e0b9 100644--- a/saleor/graphql/warehouse/types.py+++ b/saleor/graphql/warehouse/types.py@@ -1,8 +1,11 @@import graphene+from ...core.permissions import StockPermissionsfrom ...warehouse import models+from ...warehouse.availability import get_available_quantity_for_customerfrom ..account.enums import CountryCodeEnumfrom ..core.connection import CountableDjangoObjectType+from ..decorators import permission_requiredclass WarehouseAddressInput(graphene.InputObjectType):@@ -50,3 +53,28 @@ class Warehouse(CountableDjangoObjectType):"address","email",]+++class StockInput(graphene.InputObjectType):+ product_variant = graphene.ID(+ required=True, description="Product variant assiociated with stock."+ )+ warehouse = graphene.ID(+ required=True, description="Warehouse in which stock is lockated."+ )+ quantity = graphene.Int(description="Quantity of items available for sell.")+ quantity_allocated = graphene.Int(description="Quantity allocated for orders.")+++class Stock(CountableDjangoObjectType):+ available = graphene.Int(description="Quantity of a product available for sale.")++ class Meta:+ description = "Represents stock."+ model = models.Stock+ interfaces = [graphene.relay.Node]++ @staticmethod+ @permission_required(StockPermissions.MANAGE_STOCKS)+ def resolve_available(root, *_args):+ return get_available_quantity_for_customer(root)diff --git a/saleor/order/actions.py b/saleor/order/actions.pyindex 12a93cd45c..7a21075973 100644--- a/saleor/order/actions.py+++ b/saleor/order/actions.py@@ -8,7 +8,7 @@ from django.utils.translation import pgettext_lazyfrom ..core import analyticsfrom ..extensions.manager import get_extensions_managerfrom ..payment import ChargeStatus, CustomPaymentChoices, PaymentError-from ..stock.management import decrease_stock+from ..warehouse.management import decrease_stockfrom . import FulfillmentStatus, OrderStatus, emails, events, utilsfrom .emails import send_fulfillment_confirmation_to_customer, send_payment_confirmationfrom .models import Fulfillment, FulfillmentLinediff --git a/saleor/order/utils.py b/saleor/order/utils.pyindex 0bfa45f987..67eb08c1a1 100644--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@ -15,8 +15,8 @@ from ..order import OrderStatusfrom ..order.models import Order, OrderLinefrom ..product.utils.digital_products import get_default_digital_content_settingsfrom ..shipping.models import ShippingMethod-from ..stock.availability import check_stock_quantity-from ..stock.management import allocate_stock, deallocate_stock, increase_stock+from ..warehouse.availability import check_stock_quantity+from ..warehouse.management import allocate_stock, deallocate_stock, increase_stockfrom . import eventsdiff --git a/saleor/product/migrations/0111_auto_20191209_0437.py b/saleor/product/migrations/0111_auto_20191209_0437.pyindex 572573f42a..162492751f 100644--- a/saleor/product/migrations/0111_auto_20191209_0437.py+++ b/saleor/product/migrations/0111_auto_20191209_0437.py@@ -5,7 +5,10 @@ from django.db import migrationsclass Migration(migrations.Migration):- dependencies = [("product", "0110_auto_20191108_0340"), ("stock", "0001_initial")]+ dependencies = [+ ("product", "0110_auto_20191108_0340"),+ ("warehouse", "0001_initial"),+ ]operations = [migrations.RemoveField(model_name="productvariant", name="quantity"),diff --git a/saleor/product/utils/availability.py b/saleor/product/utils/availability.pyindex 909c645929..910cb1d0a4 100644--- a/saleor/product/utils/availability.py+++ b/saleor/product/utils/availability.py@@ -10,7 +10,7 @@ from saleor.product.models import Product, ProductVariantfrom ...core.utils import to_local_currencyfrom ...discount import DiscountInfofrom ...extensions.manager import get_extensions_manager-from ...stock.availability import (+from ...warehouse.availability import (are_all_product_variants_in_stock,is_product_in_stock,is_variant_in_stock,diff --git a/saleor/settings.py b/saleor/settings.pyindex a02a7bdb82..cb2be51e5f 100644--- a/saleor/settings.py+++ b/saleor/settings.py@@ -217,7 +217,6 @@ INSTALLED_APPS = ["saleor.data_feeds","saleor.page","saleor.payment",- "saleor.stock","saleor.warehouse","saleor.webhook","saleor.wishlist",diff --git a/saleor/stock/__init__.py b/saleor/stock/__init__.pydeleted file mode 100644index e69de29bb2..0000000000diff --git a/saleor/stock/error_codes.py b/saleor/stock/error_codes.pydeleted file mode 100644index f893ff5cd0..0000000000--- a/saleor/stock/error_codes.py+++ /dev/null@@ -1,10 +0,0 @@-from enum import Enum---class StockErorrCode(str, Enum):- ALREADY_EXISTS = "already_exists"- GRAPHQL_ERROR = "graphql_error"- INVALID = "invalid"- NOT_FOUND = "not_found"- REQUIRED = "required"- UNIQUE = "unique"diff --git a/saleor/stock/migrations/0001_initial.py b/saleor/stock/migrations/0001_initial.pydeleted file mode 100644index adff9b97aa..0000000000--- a/saleor/stock/migrations/0001_initial.py+++ /dev/null@@ -1,103 +0,0 @@-# Generated by Django 2.2.7 on 2019-12-19 12:34--import django.db.models.deletion-from django.db import migrations, models---def get_warehouse(apps):- Warehouse = apps.get_model("warehouse", "Warehouse")- ShippingZone = apps.get_model("shipping", "ShippingZone")- warehouses = Warehouse.objects.annotate(- zones_count=models.Count("shipping_zones")- ).filter(zones_count=ShippingZone.objects.count())- if warehouses.first() is not None:- return warehouses.first()---def forward(apps, schema_editor):- ProductVariant = apps.get_model("product", "ProductVariant")- Stock = apps.get_model("stock", "Stock")-- if not ProductVariant.objects.exists():- return-- product_variants = ProductVariant.objects.all()- warehouse = get_warehouse(apps)- stocks = [- Stock(- product_variant=variant,- warehouse=warehouse,- quantity=variant.quantity,- quantity_allocated=variant.quantity_allocated,- )- for variant in product_variants.iterator()- ]- Stock.objects.bulk_create(stocks)---def backward(apps, schema_editor):- ProductVariant = apps.get_model("product", "ProductVariant")- Stock = apps.get_model("stock", "Stock")-- stocks = (- Stock.objects.values("product_variant_id")- .annotate(quantity_sum=models.Sum("quantity"))- .annotate(quantity_allocated_sum=models.Sum("quantity_allocated"))- )- product_variants = ProductVariant.objects.all()- for variant in product_variants.iterator():- variant_dict = stocks.get(product_variant=variant)- variant.quantity = variant_dict["quantity_sum"]- variant.quantity_allocated = variant_dict["quantity_allocated_sum"]- variant.save(update_fields=["quantity", "quantity_allocated"])-- Stock.objects.all().delete()---class Migration(migrations.Migration):-- initial = True-- dependencies = [- ("warehouse", "0001_initial"),- ("product", "0110_auto_20191108_0340"),- ("shipping", "0017_django_price_2"),- ]-- operations = [- migrations.CreateModel(- name="Stock",- fields=[- (- "id",- models.AutoField(- auto_created=True,- primary_key=True,- serialize=False,- verbose_name="ID",- ),- ),- ("quantity", models.PositiveIntegerField(default=0)),- ("quantity_allocated", models.PositiveIntegerField(default=0)),- (- "product_variant",- models.ForeignKey(- on_delete=django.db.models.deletion.CASCADE,- to="product.ProductVariant",- ),- ),- (- "warehouse",- models.ForeignKey(- on_delete=django.db.models.deletion.PROTECT,- to="warehouse.Warehouse",- ),- ),- ],- options={- "permissions": (("manage_stocks", "Manage stocks."),),- "unique_together": {("warehouse", "product_variant")},- },- ),- migrations.RunPython(forward, backward),- ]diff --git a/saleor/stock/migrations/__init__.py b/saleor/stock/migrations/__init__.pydeleted file mode 100644index e69de29bb2..0000000000diff --git a/saleor/stock/models.py b/saleor/stock/models.pydeleted file mode 100644index 717de9e3d4..0000000000--- a/saleor/stock/models.py+++ /dev/null@@ -1,90 +0,0 @@-from django.db import models-from django.db.models import F-from django.utils.translation import pgettext_lazy--from ..core.exceptions import InsufficientStock-from ..product.models import ProductVariant-from ..warehouse.models import Warehouse---class StockQuerySet(models.QuerySet):- def annotate_available_quantity(self):- return self.annotate(available_quantity=F("quantity") - F("quantity_allocated"))-- def for_country(self, country_code: str):- query_warehouse = models.Subquery(- Warehouse.objects.filter(- shipping_zones__countries__contains=country_code- ).values("pk")- )- return self.select_related("product_variant", "warehouse").filter(- warehouse__in=query_warehouse- )-- def get_variant_stock_for_country(- self, country_code: str, product_variant: ProductVariant- ):- return self.for_country(country_code).get(product_variant=product_variant)---class Stock(models.Model):- warehouse = models.ForeignKey(Warehouse, null=False, on_delete=models.PROTECT)- product_variant = models.ForeignKey(- ProductVariant, null=False, on_delete=models.CASCADE- )- quantity = models.PositiveIntegerField(default=0)- quantity_allocated = models.PositiveIntegerField(default=0)-- objects = StockQuerySet.as_manager()-- class Meta:- unique_together = [["warehouse", "product_variant"]]- permissions = (- (- "manage_stocks",- pgettext_lazy("Permission description", "Manage stocks."),- ),- )-- def __str__(self):- return f"{self.product_variant} - {self.warehouse.name}"-- @property- def quantity_available(self) -> int:- return max(self.quantity - self.quantity_allocated, 0)-- @property- def is_available(self):- return self.quantity_available > 0-- def check_quantity(self, quantity: int):- if quantity > self.quantity_available:- raise InsufficientStock(self)-- def allocate_stock(self, quantity: int, commit: bool = True):- self.quantity_allocated = F("quantity_allocated") + quantity- if commit:- self.save(update_fields=["quantity_allocated"])-- def deallocate_stock(self, quantity: int, commit: bool = True):- self.quantity_allocated = F("quantity_allocated") - quantity- if commit:- self.save(update_fields=["quantity_allocated"])-- def increase_stock(- self, quantity: int, allocate: bool = False, commit: bool = True- ):- """Return given quantity of product to a stock."""- self.quantity = F("quantity") + quantity- update_fields = ["quantity"]- if allocate:- self.quantity_allocated = F("quantity_allocated") + quantity- update_fields.append("quantity_allocated")- if commit:- self.save(update_fields=update_fields)-- def decrease_stock(self, quantity: int, commit: bool = True):- self.quantity = F("quantity") - quantity- self.quantity_allocated = F("quantity_allocated") - quantity- if commit:- self.save(update_fields=["quantity", "quantity_allocated"])diff --git a/saleor/stock/availability.py b/saleor/warehouse/availability.pysimilarity index 100%rename from saleor/stock/availability.pyrename to saleor/warehouse/availability.pydiff --git a/saleor/warehouse/error_codes.py b/saleor/warehouse/error_codes.pyindex 1828c4e54c..7c4221d981 100644--- a/saleor/warehouse/error_codes.py+++ b/saleor/warehouse/error_codes.py@@ -8,3 +8,12 @@ class WarehouseErrorCode(str, Enum):NOT_FOUND = "not_found"REQUIRED = "required"UNIQUE = "unique"+++class StockErorrCode(str, Enum):+ ALREADY_EXISTS = "already_exists"+ GRAPHQL_ERROR = "graphql_error"+ INVALID = "invalid"+ NOT_FOUND = "not_found"+ REQUIRED = "required"+ UNIQUE = "unique"diff --git a/saleor/stock/management.py b/saleor/warehouse/management.pysimilarity index 100%rename from saleor/stock/management.pyrename to saleor/warehouse/management.pydiff --git a/saleor/warehouse/migrations/0001_initial.py b/saleor/warehouse/migrations/0001_initial.pyindex 2b8b5838db..7088c68f02 100644--- a/saleor/warehouse/migrations/0001_initial.py+++ b/saleor/warehouse/migrations/0001_initial.py@@ -1,4 +1,4 @@-# Generated by Django 2.2.7 on 2019-12-19 12:34+# Generated by Django 2.2.9 on 2020-01-14 14:29import uuid@@ -6,13 +6,18 @@ import django.db.models.deletionfrom django.db import migrations, models-def create_warehouse(apps, schema_editor):+def get_or_create_warehouse(apps):Warehouse = apps.get_model("warehouse", "Warehouse")ShippingZone = apps.get_model("shipping", "ShippingZone")Site = apps.get_model("sites", "Site")- site_settings = Site.objects.get_current().settings+ warehouses = Warehouse.objects.annotate(+ zones_count=models.Count("shipping_zones")+ ).filter(zones_count=ShippingZone.objects.count())+ if warehouses.first() is not None:+ return warehouses.first()+ site_settings = Site.objects.get_current().settingsaddress = getattr(site_settings, "company_address", None)if address is None:Address = apps.get_model("account", "Address")@@ -23,13 +28,54 @@ def create_warehouse(apps, schema_editor):return warehouse+def forward(apps, schema_editor):+ ProductVariant = apps.get_model("product", "ProductVariant")+ Stock = apps.get_model("warehouse", "Stock")++ if not ProductVariant.objects.exists():+ return++ product_variants = ProductVariant.objects.all()+ warehouse = get_or_create_warehouse(apps)+ stocks = [+ Stock(+ product_variant=variant,+ warehouse=warehouse,+ quantity=variant.quantity,+ quantity_allocated=variant.quantity_allocated,+ )+ for variant in product_variants.iterator()+ ]+ Stock.objects.bulk_create(stocks)+++def backward(apps, schema_editor):+ ProductVariant = apps.get_model("product", "ProductVariant")+ Stock = apps.get_model("warehouse", "Stock")++ stocks = (+ Stock.objects.values("product_variant_id")+ .annotate(quantity_sum=models.Sum("quantity"))+ .annotate(quantity_allocated_sum=models.Sum("quantity_allocated"))+ )+ product_variants = ProductVariant.objects.all()+ for variant in product_variants.iterator():+ variant_dict = stocks.get(product_variant=variant)+ variant.quantity = variant_dict["quantity_sum"]+ variant.quantity_allocated = variant_dict["quantity_allocated_sum"]+ variant.save(update_fields=["quantity", "quantity_allocated"])++ Stock.objects.all().delete()++class Migration(migrations.Migration):initial = Truedependencies = [+ ("account", "0037_auto_20191219_0944"),("shipping", "0017_django_price_2"),- ("account", "0034_service_account_token"),+ ("product", "0110_auto_20191108_0340"),("site", "0025_auto_20191024_0552"),]@@ -79,5 +125,39 @@ class Migration(migrations.Migration):"permissions": (("manage_warehouses", "Manage warehouses."),),},),- migrations.RunPython(create_warehouse, migrations.RunPython.noop),+ migrations.CreateModel(+ name="Stock",+ fields=[+ (+ "id",+ models.AutoField(+ auto_created=True,+ primary_key=True,+ serialize=False,+ verbose_name="ID",+ ),+ ),+ ("quantity", models.PositiveIntegerField(default=0)),+ ("quantity_allocated", models.PositiveIntegerField(default=0)),+ (+ "product_variant",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ to="product.ProductVariant",+ ),+ ),+ (+ "warehouse",+ models.ForeignKey(+ on_delete=django.db.models.deletion.PROTECT,+ to="warehouse.Warehouse",+ ),+ ),+ ],+ options={+ "permissions": (("manage_stocks", "Manage stocks."),),+ "unique_together": {("warehouse", "product_variant")},+ },+ ),+ migrations.RunPython(forward, backward),]diff --git a/saleor/warehouse/models.py b/saleor/warehouse/models.pyindex 6b9b57caf9..212ab411fa 100644--- a/saleor/warehouse/models.py+++ b/saleor/warehouse/models.py@@ -3,9 +3,12 @@ import uuidfrom typing import Setfrom django.db import models+from django.db.models import Ffrom django.utils.translation import pgettext_lazyfrom ..account.models import Address+from ..core.exceptions import InsufficientStock+from ..product.models import ProductVariantfrom ..shipping.models import ShippingZone@@ -57,3 +60,86 @@ class Warehouse(models.Model):address = self.addresssuper().delete(*args, **kwargs)address.delete()+++class StockQuerySet(models.QuerySet):+ def annotate_available_quantity(self):+ return self.annotate(available_quantity=F("quantity") - F("quantity_allocated"))++ def for_country(self, country_code: str):+ query_warehouse = models.Subquery(+ Warehouse.objects.filter(+ shipping_zones__countries__contains=country_code+ ).values("pk")+ )+ return self.select_related("product_variant", "warehouse").filter(+ warehouse__in=query_warehouse+ )++ def get_variant_stock_for_country(+ self, country_code: str, product_variant: ProductVariant+ ):+ return self.for_country(country_code).get(product_variant=product_variant)+++class Stock(models.Model):+ warehouse = models.ForeignKey(Warehouse, null=False, on_delete=models.PROTECT)+ product_variant = models.ForeignKey(+ ProductVariant, null=False, on_delete=models.CASCADE+ )+ quantity = models.PositiveIntegerField(default=0)+ quantity_allocated = models.PositiveIntegerField(default=0)++ objects = StockQuerySet.as_manager()++ class Meta:+ unique_together = [["warehouse", "product_variant"]]+ permissions = (+ (+ "manage_stocks",+ pgettext_lazy("Permission description", "Manage stocks."),+ ),+ )++ def __str__(self):+ return f"{self.product_variant} - {self.warehouse.name}"++ @property+ def quantity_available(self) -> int:+ return max(self.quantity - self.quantity_allocated, 0)++ @property+ def is_available(self):+ return self.quantity_available > 0++ def check_quantity(self, quantity: int):+ if quantity > self.quantity_available:+ raise InsufficientStock(self)++ def allocate_stock(self, quantity: int, commit: bool = True):+ self.quantity_allocated = F("quantity_allocated") + quantity+ if commit:+ self.save(update_fields=["quantity_allocated"])++ def deallocate_stock(self, quantity: int, commit: bool = True):+ self.quantity_allocated = F("quantity_allocated") - quantity+ if commit:+ self.save(update_fields=["quantity_allocated"])++ def increase_stock(+ self, quantity: int, allocate: bool = False, commit: bool = True+ ):+ """Return given quantity of product to a stock."""+ self.quantity = F("quantity") + quantity+ update_fields = ["quantity"]+ if allocate:+ self.quantity_allocated = F("quantity_allocated") + quantity+ update_fields.append("quantity_allocated")+ if commit:+ self.save(update_fields=update_fields)++ def decrease_stock(self, quantity: int, commit: bool = True):+ self.quantity = F("quantity") - quantity+ self.quantity_allocated = F("quantity_allocated") - quantity+ if commit:+ self.save(update_fields=["quantity", "quantity_allocated"])diff --git a/tests/api/benchmark/test_variant.py b/tests/api/benchmark/test_variant.pyindex aa904e974d..acba6d2634 100644--- a/tests/api/benchmark/test_variant.py+++ b/tests/api/benchmark/test_variant.py@@ -4,7 +4,7 @@ import grapheneimport pytestfrom saleor.product.models import ProductVariant-from saleor.stock.models import Stock+from saleor.warehouse.models import Stockfrom tests.api.utils import get_graphql_contentdiff --git a/tests/api/test_checkout.py b/tests/api/test_checkout.pyindex 6f22029cd6..4828436b78 100644--- a/tests/api/test_checkout.py+++ b/tests/api/test_checkout.py@@ -1,4 +1,5 @@import uuid+from decimal import Decimalfrom unittest import mockfrom unittest.mock import ANY, patch@@ -23,7 +24,7 @@ from saleor.payment import TransactionKindfrom saleor.payment.interface import GatewayResponsefrom saleor.shipping import ShippingMethodTypefrom saleor.shipping.models import ShippingMethod-from saleor.stock.models import Stock+from saleor.warehouse.models import Stockfrom tests.api.utils import get_graphql_content@@ -1232,7 +1233,7 @@ ERROR_GATEWAY_RESPONSE = GatewayResponse(is_success=False,action_required=False,kind=TransactionKind.CAPTURE,- amount=0.0,+ amount=Decimal(0),currency="usd",transaction_id="1234",error="ERROR",diff --git a/tests/api/test_order.py b/tests/api/test_order.pyindex d4c1dbbd5e..2f954b31ab 100644--- a/tests/api/test_order.py+++ b/tests/api/test_order.py@@ -27,7 +27,7 @@ from saleor.order.models import Order, OrderEventfrom saleor.payment import ChargeStatus, CustomPaymentChoices, PaymentErrorfrom saleor.payment.models import Paymentfrom saleor.shipping.models import ShippingMethod-from saleor.stock.models import Stock+from saleor.warehouse.models import Stockfrom .utils import assert_no_permission, get_graphql_contentdiff --git a/tests/api/test_stock.py b/tests/api/test_stock.pyindex 38dc67f5c3..774ef582a6 100644--- a/tests/api/test_stock.py+++ b/tests/api/test_stock.py@@ -1,7 +1,7 @@import graphenefrom saleor.core.permissions import StockPermissions-from saleor.stock.models import Stock+from saleor.warehouse.models import Stockfrom tests.api.utils import assert_no_permission, get_graphql_contentMUTATION_CREATE_STOCK = """diff --git a/tests/api/test_warehouse.py b/tests/api/test_warehouse.pyindex bc592ae498..75df83fc61 100644--- a/tests/api/test_warehouse.py+++ b/tests/api/test_warehouse.py@@ -326,14 +326,14 @@ def test_create_warehouse_creates_address(],}}- assert Address.objects.count() == 1+ assert not Address.objects.exists()response = staff_api_client.post_graphql(MUTATION_CREATE_WAREHOUSE, variables=variables)content = get_graphql_content(response)errors = content["data"]["createWarehouse"]["errors"]assert len(errors) == 0- assert Address.objects.count() == 2+ assert Address.objects.count() == 1address = Address.objects.get(street_address_1="Teczowa 8", city="WROCLAW")address_id = graphene.Node.to_global_id("Address", address.id)warehouse_data = content["data"]["createWarehouse"]["warehouse"]@@ -473,14 +473,14 @@ def test_delete_warehouse_mutation():staff_api_client.user.user_permissions.add(permission_manage_warehouses)warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)- assert Warehouse.objects.count() == 2+ assert Warehouse.objects.count() == 1response = staff_api_client.post_graphql(MUTATION_DELETE_WAREHOUSE, variables={"id": warehouse_id})content = get_graphql_content(response)errors = content["data"]["deleteWarehouse"]["errors"]assert len(errors) == 0- assert Warehouse.objects.count() == 1+ assert not Warehouse.objects.exists()def test_delete_warehouse_deletes_associated_address(@@ -488,14 +488,14 @@ def test_delete_warehouse_deletes_associated_address():staff_api_client.user.user_permissions.add(permission_manage_warehouses)warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)- assert Address.objects.count() == 2+ assert Address.objects.count() == 1response = staff_api_client.post_graphql(MUTATION_DELETE_WAREHOUSE, variables={"id": warehouse_id})content = get_graphql_content(response)errors = content["data"]["deleteWarehouse"]["errors"]assert len(errors) == 0- assert Address.objects.count() == 1+ assert not Address.objects.exists()def test_shipping_zone_can_be_assigned_only_to_one_warehouse(diff --git a/tests/conftest.py b/tests/conftest.pyindex 34c8fab45f..7821176253 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -78,8 +78,7 @@ from saleor.shipping.models import ()from saleor.site import AuthenticationBackendsfrom saleor.site.models import AuthorizationKey, SiteSettings-from saleor.stock.models import Stock-from saleor.warehouse.models import Warehouse+from saleor.warehouse.models import Stock, Warehousefrom saleor.webhook.event_types import WebhookEventTypefrom saleor.webhook.models import Webhookfrom saleor.wishlist.models import Wishlistdiff --git a/tests/test_core.py b/tests/test_core.pyindex 4426c2e611..08278e1189 100644--- a/tests/test_core.py+++ b/tests/test_core.py@@ -125,9 +125,9 @@ def test_create_fake_users(db):def test_create_address(db):- assert Address.objects.all().count() == 1+ assert not Address.objects.exists()random_data.create_address()- assert Address.objects.all().count() == 2+ assert Address.objects.all().count() == 1def test_create_fake_order(db, monkeypatch, image, media_root, warehouse):diff --git a/tests/test_order.py b/tests/test_order.pyindex cb5ca3e4c7..084310f6e2 100644--- a/tests/test_order.py+++ b/tests/test_order.py@@ -32,7 +32,7 @@ from saleor.order.utils import (from saleor.payment import ChargeStatusfrom saleor.payment.models import Paymentfrom saleor.product.models import Collection-from saleor.stock.models import Stock+from saleor.warehouse.models import Stockdef test_total_setter():diff --git a/tests/test_order_actions.py b/tests/test_order_actions.pyindex 7b5bff9cd1..c82cce3cdc 100644--- a/tests/test_order_actions.py+++ b/tests/test_order_actions.py@@ -17,7 +17,7 @@ from saleor.order.actions import (from saleor.order.models import Fulfillmentfrom saleor.payment import ChargeStatus, PaymentErrorfrom saleor.product.models import DigitalContent-from saleor.stock.models import Stock+from saleor.warehouse.models import Stockfrom .utils import create_imagediff --git a/tests/test_product_availability.py b/tests/test_product_availability.pyindex f5fe03e172..53306757f1 100644--- a/tests/test_product_availability.py+++ b/tests/test_product_availability.py@@ -11,7 +11,7 @@ from saleor.product.utils.availability import (get_product_availability_status,get_variant_availability_status,)-from saleor.stock.models import Stock+from saleor.warehouse.models import Stockdef test_product_availability_status(unavailable_product, warehouse):diff --git a/tests/test_stock.py b/tests/test_stock.pyindex de43a989ff..39bdf48f01 100644--- a/tests/test_stock.py+++ b/tests/test_stock.py@@ -1,18 +1,18 @@import pytestfrom saleor.core.exceptions import InsufficientStock-from saleor.stock.availability import (+from saleor.warehouse.availability import (are_all_product_variants_in_stock,check_stock_quantity,products_with_low_stock,)-from saleor.stock.management import (+from saleor.warehouse.management import (allocate_stock,deallocate_stock,decrease_stock,increase_stock,)-from saleor.stock.models import Stock+from saleor.warehouse.models import StockCOUNTRY_CODE = "US"