Skip to content

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

Add option to create allocation in many stocks for one line

fowczrekf10d4e2e48dd
diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.py
index db1052c140..e49053eeb5 100644
--- a/saleor/core/utils/random_data.py
+++ b/saleor/core/utils/random_data.py
@@ -482,7 +482,12 @@ def create_order_lines(order, discounts, how_many=10):
unit_price = manager.calculate_order_line_unit(line)
line.unit_price = unit_price
line.tax_rate = unit_price.tax / unit_price.net
- increase_stock(line, country, line.quantity, allocate=True)
+ warehouse = (
+ Warehouse.objects.filter(shipping_zones__countries__contains=country)
+ .order_by("?")
+ .first()
+ )
+ increase_stock(line, warehouse, line.quantity, allocate=True)
OrderLine.objects.bulk_update(
lines,
["unit_price_net_amount", "unit_price_gross_amount", "currency", "tax_rate"],
@@ -491,7 +496,6 @@ def create_order_lines(order, discounts, how_many=10):
def create_fulfillments(order):
- country = order.shipping_method.shipping_zone.countries[0]
for line in order:
if random.choice([False, True]):
fulfillment, _ = Fulfillment.objects.get_or_create(order=order)
@@ -500,7 +504,7 @@ def create_fulfillments(order):
line.quantity_fulfilled = quantity
line.save(update_fields=["quantity_fulfilled"])
- deallocate_stock(line, country, quantity)
+ deallocate_stock(line, quantity)
update_order_status(order)
diff --git a/saleor/graphql/order/mutations/draft_orders.py b/saleor/graphql/order/mutations/draft_orders.py
index d2edfa803e..f58763945a 100644
--- a/saleor/graphql/order/mutations/draft_orders.py
+++ b/saleor/graphql/order/mutations/draft_orders.py
@@ -10,15 +10,14 @@ from ....order import OrderStatus, events, models
from ....order.actions import order_created
from ....order.error_codes import OrderErrorCode
from ....order.utils import (
- add_variant_to_order,
- allocate_stock,
+ add_variant_to_draft_order,
change_order_line_quantity,
delete_order_line,
get_order_country,
recalculate_order,
update_order_prices,
)
-from ....warehouse.availability import check_stock_quantity, get_available_quantity
+from ....warehouse.management import allocate_stock
from ...account.i18n import I18nMixin
from ...account.types import AddressInput
from ...core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation
@@ -143,13 +142,7 @@ class DraftOrderCreate(ModelMutation, I18nMixin):
lines = []
for variant, quantity in zip(variants, quantities):
lines.append((quantity, variant))
- add_variant_to_order(
- instance,
- variant,
- quantity,
- allow_overselling=True,
- track_inventory=False,
- )
+ add_variant_to_draft_order(instance, variant, quantity)
# New event
events.draft_order_added_products_event(
@@ -257,7 +250,8 @@ class DraftOrderComplete(BaseMutation):
@classmethod
def perform_mutation(cls, _root, info, id):
order = cls.get_node_or_error(info, id, only_type=Order)
- validate_draft_order(order)
+ country = get_order_country(order)
+ validate_draft_order(order, country)
cls.update_user_fields(order)
order.status = OrderStatus.UNFULFILLED
@@ -268,24 +262,21 @@ class DraftOrderComplete(BaseMutation):
order.shipping_address.delete()
order.save()
- country = get_order_country(order)
- oversold_items = []
for line in order:
try:
- check_stock_quantity(line.variant, country, line.quantity)
allocate_stock(line, country, line.quantity)
- except InsufficientStock:
- available_stock = get_available_quantity(line.variant, country)
- allocate_stock(line, country, available_stock)
- oversold_items.append(str(line))
+ except InsufficientStock as exc:
+ raise ValidationError(
+ {
+ "lines": ValidationError(
+ f"Insufficient product stock: {exc.item}",
+ code=OrderErrorCode.INSUFFICIENT_STOCK,
+ )
+ }
+ )
order_created(order, user=info.context.user, from_draft=True)
- if oversold_items:
- events.draft_order_oversold_items_event(
- order=order, user=info.context.user, oversold_items=oversold_items
- )
-
return DraftOrderComplete(order=order)
@@ -346,7 +337,7 @@ class DraftOrderLinesCreate(BaseMutation):
# Add the lines
lines = [
- add_variant_to_order(order, variant, quantity, allow_overselling=True)
+ add_variant_to_draft_order(order, variant, quantity)
for quantity, variant in lines_to_add
]
diff --git a/saleor/graphql/order/mutations/fulfillments.py b/saleor/graphql/order/mutations/fulfillments.py
index b3ace67083..b66e4bd537 100644
--- a/saleor/graphql/order/mutations/fulfillments.py
+++ b/saleor/graphql/order/mutations/fulfillments.py
@@ -151,14 +151,17 @@ class FulfillmentCreate(BaseMutation):
quantities = cleaned_input.get("quantities")
fulfillment_lines = []
for order_line, quantity in zip(order_lines, quantities):
- fulfill_order_line(order_line, quantity)
- if order_line.is_digital:
- order_line.variant.digital_content.urls.create(line=order_line)
- fulfillment_lines.append(
- models.FulfillmentLine(
- order_line=order_line, fulfillment=fulfillment, quantity=quantity
+ if quantity > 0:
+ fulfill_order_line(order_line, quantity)
+ if order_line.is_digital:
+ order_line.variant.digital_content.urls.create(line=order_line)
+ fulfillment_lines.append(
+ models.FulfillmentLine(
+ order_line=order_line,
+ fulfillment=fulfillment,
+ quantity=quantity,
+ )
)
- )
fulfillment.lines.bulk_create(fulfillment_lines)
order_fulfilled(
diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.py
index beef2a3a18..bab47b5a1a 100644
--- a/saleor/graphql/order/types.py
+++ b/saleor/graphql/order/types.py
@@ -7,9 +7,9 @@ from graphql_jwt.exceptions import PermissionDenied
from ...core.permissions import AccountPermissions, OrderPermissions
from ...core.taxes import display_gross_prices
from ...plugins.manager import get_plugins_manager
-from ...order import models
+from ...order import OrderStatus, models
from ...order.models import FulfillmentStatus
-from ...order.utils import get_valid_shipping_methods_for_order
+from ...order.utils import get_order_country, get_valid_shipping_methods_for_order
from ...product.templatetags.product_images import get_product_image_thumbnail
from ..account.types import User
from ..core.connection import CountableDjangoObjectType
@@ -465,10 +465,12 @@ class Order(CountableDjangoObjectType):
@staticmethod
def resolve_can_finalize(root: models.Order, _info):
- try:
- validate_draft_order(root)
- except ValidationError:
- return False
+ if root.status == OrderStatus.DRAFT:
+ country = get_order_country(root)
+ try:
+ validate_draft_order(root, country)
+ except ValidationError:
+ return False
return True
@staticmethod
diff --git a/saleor/graphql/order/utils.py b/saleor/graphql/order/utils.py
index b342152d64..bff7e0f5b4 100644
--- a/saleor/graphql/order/utils.py
+++ b/saleor/graphql/order/utils.py
@@ -1,6 +1,8 @@
from django.core.exceptions import ValidationError
+from ...core.exceptions import InsufficientStock
from ...order.error_codes import OrderErrorCode
+from ...warehouse.availability import check_stock_quantity
def validate_total_quantity(order):
@@ -34,7 +36,7 @@ def validate_shipping_method(order):
)
-def validate_order_lines(order):
+def validate_order_lines(order, country):
for line in order:
if line.variant is None:
raise ValidationError(
@@ -45,18 +47,31 @@ def validate_order_lines(order):
)
}
)
+ if line.variant.track_inventory:
+ try:
+ check_stock_quantity(line.variant, country, line.quantity)
+ except InsufficientStock as exc:
+ raise ValidationError(
+ {
+ "lines": ValidationError(
+ f"Insufficient product stock: {exc.item}",
+ code=OrderErrorCode.INSUFFICIENT_STOCK,
+ )
+ }
+ )
-def validate_draft_order(order):
+def validate_draft_order(order, country):
"""Check if the given order contains the proper data.
- Has proper customer data,
- Shipping address and method are set up,
- Product variants for order lines still exists in database.
+ - Product variants are availale in requested quantity.
Returns a list of errors if any were found.
"""
if order.is_shipping_required():
validate_shipping_method(order)
validate_total_quantity(order)
- validate_order_lines(order)
+ validate_order_lines(order, country)
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 0def7269d1..0c3db39c3f 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -2580,6 +2580,7 @@ enum OrderErrorCode {
UNIQUE
VOID_INACTIVE_PAYMENT
ZERO_QUANTITY
+ INSUFFICIENT_STOCK
}
type OrderEvent implements Node {
diff --git a/saleor/order/actions.py b/saleor/order/actions.py
index 708dd81c42..552a0ffd74 100644
--- a/saleor/order/actions.py
+++ b/saleor/order/actions.py
@@ -12,7 +12,6 @@ from . import FulfillmentStatus, OrderStatus, emails, events, utils
from .emails import send_fulfillment_confirmation_to_customer, send_payment_confirmation
from .models import Fulfillment, FulfillmentLine
from .utils import (
- get_order_country,
order_line_needs_automatic_fulfillment,
recalculate_order,
restock_fulfillment_lines,
@@ -208,9 +207,8 @@ def clean_mark_order_as_paid(order: "Order"):
def fulfill_order_line(order_line, quantity):
"""Fulfill order line with given quantity."""
- country = get_order_country(order_line.order)
if order_line.variant and order_line.variant.track_inventory:
- decrease_stock(order_line, country, quantity)
+ decrease_stock(order_line, quantity)
order_line.quantity_fulfilled += quantity
order_line.save(update_fields=["quantity_fulfilled"])
diff --git a/saleor/order/error_codes.py b/saleor/order/error_codes.py
index 0383d59bcc..6d94c009da 100644
--- a/saleor/order/error_codes.py
+++ b/saleor/order/error_codes.py
@@ -22,3 +22,4 @@ class OrderErrorCode(Enum):
UNIQUE = "unique"
VOID_INACTIVE_PAYMENT = "void_inactive_payment"
ZERO_QUANTITY = "zero_quantity"
+ INSUFFICIENT_STOCK = "insufficient_stock"
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index 1c97100759..d26f8bc37e 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -15,8 +15,8 @@ from ..order import OrderStatus
from ..order.models import Order, OrderLine
from ..product.utils.digital_products import get_default_digital_content_settings
from ..shipping.models import ShippingMethod
-from ..warehouse.availability import check_stock_quantity
-from ..warehouse.management import allocate_stock, deallocate_stock, increase_stock
+from ..warehouse.management import deallocate_stock, increase_stock
+from ..warehouse.models import Warehouse
from . import events
@@ -163,24 +163,11 @@ def update_order_status(order):
@transaction.atomic
-def add_variant_to_order(
- order,
- variant,
- quantity,
- discounts=None,
- allow_overselling=False,
- track_inventory=True,
-):
+def add_variant_to_draft_order(order, variant, quantity, discounts=None):
"""Add total_quantity of variant to order.
Returns an order line the variant was added to.
-
- By default, raises InsufficientStock exception if quantity could not be
- fulfilled. This can be disabled by setting `allow_overselling` to True.
"""
- country = get_order_country(order)
- if not allow_overselling:
- check_stock_quantity(variant, country, quantity)
try:
line = order.lines.get(variant=variant)
@@ -222,8 +209,6 @@ def add_variant_to_order(
]
)
- if variant.track_inventory and track_inventory:
- allocate_stock(line, country, quantity)
return line
@@ -278,9 +263,16 @@ def restock_order_lines(order):
for line in order:
if line.variant and line.variant.track_inventory:
if line.quantity_unfulfilled > 0:
- deallocate_stock(line, country, line.quantity_unfulfilled)
+ deallocate_stock(line, line.quantity_unfulfilled)
if line.quantity_fulfilled > 0:
- increase_stock(line, country, line.quantity_fulfilled)
+ allocation = line.allocations.first()
+ if allocation:
+ warehouse = allocation.stock.warehouse
+ else:
+ warehouse = Warehouse.objects.filter(
+ shipping_zones__countries__contains=country
+ ).first()
+ increase_stock(line, warehouse, line.quantity_fulfilled)
if line.quantity_fulfilled > 0:
line.quantity_fulfilled = 0
@@ -292,7 +284,14 @@ def restock_fulfillment_lines(fulfillment):
country = get_order_country(fulfillment.order)
for line in fulfillment:
if line.order_line.variant and line.order_line.variant.track_inventory:
- increase_stock(line.order_line, country, line.quantity, allocate=True)
+ allocation = line.order_line.allocations.first()
+ if allocation:
+ warehouse = allocation.stock.warehouse
+ else:
+ warehouse = Warehouse.objects.filter(
+ shipping_zones__countries__contains=country
+ ).first()
+ increase_stock(line.order_line, warehouse, line.quantity, allocate=True)
def sum_order_totals(qs):
diff --git a/saleor/settings.py b/saleor/settings.py
index 29cc81080e..da633021a8 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -385,7 +385,6 @@ PAYMENT_MODEL = "order.Payment"
SESSION_SERIALIZER = "django.contrib.sessions.serializers.JSONSerializer"
-LOW_STOCK_THRESHOLD = 10
MAX_CHECKOUT_LINE_QUANTITY = int(os.environ.get("MAX_CHECKOUT_LINE_QUANTITY", 50))
TEST_RUNNER = "tests.runner.PytestTestRunner"
diff --git a/saleor/warehouse/availability.py b/saleor/warehouse/availability.py
index 9d817056a3..c87b5bc995 100644
--- a/saleor/warehouse/availability.py
+++ b/saleor/warehouse/availability.py
@@ -1,25 +1,28 @@
-from typing import TYPE_CHECKING, Optional
+from typing import TYPE_CHECKING
from django.conf import settings
from django.db.models import Sum
from django.db.models.functions import Coalesce
from ..core.exceptions import InsufficientStock
-from .models import Stock
+from .models import Stock, StockQuerySet
if TYPE_CHECKING:
from ..product.models import Product, ProductVariant
-def _get_quantity_allocated(stock: Stock) -> int:
- return stock.allocations.aggregate(
- quantity_allocated=Coalesce(Sum("quantity_allocated"), 0)
+def _get_quantity_allocated(stocks: StockQuerySet) -> int:
+ return stocks.aggregate(
+ quantity_allocated=Coalesce(Sum("allocations__quantity_allocated"), 0)
)["quantity_allocated"]
-def _get_available_quantity(stock: Stock) -> int:
- quantity_allocated = _get_quantity_allocated(stock)
- return max(stock.quantity - quantity_allocated, 0)
+def _get_available_quantity(stocks: StockQuerySet) -> int:
+ quantity_allocated = _get_quantity_allocated(stocks)
+ total_quantity = stocks.aggregate(total_quantity=Coalesce(Sum("quantity"), 0))[
+ "total_quantity"
+ ]
+ return max(total_quantity - quantity_allocated, 0)
def check_stock_quantity(variant: "ProductVariant", country_code: str, quantity: int):
@@ -28,41 +31,37 @@ def check_stock_quantity(variant: "ProductVariant", country_code: str, quantity:
If so - returns None. If there is less stock then required rise InsufficientStock
exception.
"""
- try:
- stock = Stock.objects.get_variant_stock_for_country(country_code, variant)
- except Stock.DoesNotExist:
+ stocks = Stock.objects.get_variant_stocks_for_country(country_code, variant)
+ if not stocks:
raise InsufficientStock(variant)
- if variant.track_inventory and quantity > _get_available_quantity(stock):
+ if variant.track_inventory and quantity > _get_available_quantity(stocks):
raise InsufficientStock(variant)
def get_available_quantity(variant: "ProductVariant", country_code: str) -> int:
"""Return available quantity for given product in given country."""
- try:
- stock = Stock.objects.get_variant_stock_for_country(country_code, variant)
- except Stock.DoesNotExist:
+ stocks = Stock.objects.get_variant_stocks_for_country(country_code, variant)
+ if not stocks:
return 0
- return _get_available_quantity(stock)
+ return _get_available_quantity(stocks)
def get_available_quantity_for_customer(
variant: "ProductVariant", country_code: str
) -> int:
"""Return maximum checkout line quantity."""
- try:
- stock = Stock.objects.get_variant_stock_for_country(country_code, variant)
- except Stock.DoesNotExist:
+ stocks = Stock.objects.get_variant_stocks_for_country(country_code, variant)
+ if not stocks:
return 0
- return min(_get_available_quantity(stock), settings.MAX_CHECKOUT_LINE_QUANTITY)
+ return min(_get_available_quantity(stocks), settings.MAX_CHECKOUT_LINE_QUANTITY)
def get_quantity_allocated(variant: "ProductVariant", country_code: str) -> int:
- try:
- stock = Stock.objects.get_variant_stock_for_country(country_code, variant)
- except Stock.DoesNotExist:
+ stocks = Stock.objects.get_variant_stocks_for_country(country_code, variant)
+ if not stocks:
return 0
- return _get_quantity_allocated(stock)
+ return _get_quantity_allocated(stocks)
def is_variant_in_stock(variant: "ProductVariant", country_code: str) -> bool:
@@ -100,15 +99,3 @@ def are_all_product_variants_in_stock(product: "Product", country_code: str) ->
product_variants = product.variants.exclude(id__in=variants_with_stocks).exists()
return are_all_available and not product_variants
-
-
-def products_with_low_stock(threshold: Optional[int] = None):
- """Return queryset with stock lower than given threshold."""
- if threshold is None:
- threshold = settings.LOW_STOCK_THRESHOLD
- stocks = (
- Stock.objects.select_related("product_variant")
- .values("product_variant__product_id", "warehouse_id")
- .annotate(total_stock=Sum("quantity"))
- )
- return stocks.filter(total_stock__lte=threshold).distinct()
diff --git a/saleor/warehouse/management.py b/saleor/warehouse/management.py
index 40bc404399..e160b4e814 100644
--- a/saleor/warehouse/management.py
+++ b/saleor/warehouse/management.py
@@ -1,90 +1,204 @@
from typing import TYPE_CHECKING
from django.db import transaction
+from django.db.models import F, Sum
-from .models import Allocation, Stock
+from ..core.exceptions import InsufficientStock
+from .models import Allocation, Stock, Warehouse
if TYPE_CHECKING:
from ..order.models import OrderLine
from ..product.models import ProductVariant
-def _allocate_stock(stock: Stock, order_line: "OrderLine", quantity: int) -> Allocation:
- allocation = (
- stock.allocations.select_for_update(of=("self",))
- .filter(order_line=order_line)
- .first()
+def allocate_stock(
+ order_line: "OrderLine", country_code: str, quantity: int,
+):
+ """Allocate stocks for given `order_line` in given country.
+
+ Function lock for update all stocks and allocations for variant in
+ given country and order by pk. Next, generate the dictionary
+ ({"stock_pk": "quantity_allocated"}) with actual allocated quantity for stocks.
+ Iterate by stocks and allocate as many items as needed or available in stock
+ for order line, until allocated all required quantity for the order line.
+ If there is less quantity in stocks then rise InsufficientStock exception.
+ """
+ stocks = (
+ Stock.objects.select_for_update(of=("self",))
+ .get_variant_stocks_for_country(country_code, order_line.variant)
+ .order_by("pk")
)
- if allocation:
- allocation.allocate_stock(quantity, commit=True)
- else:
- allocation = Allocation.objects.create(
- order_line=order_line, stock=stock, quantity_allocated=quantity
- )
- return allocation
-
-def _deallocate_stock(
- stock: Stock, order_line: "OrderLine", quantity: int
-) -> Allocation:
- allocation = stock.allocations.select_for_update(of=("self",)).get(
- order_line=order_line
+ quantity_allocation_list = list(
+ Allocation.objects.filter(stock__in=stocks, quantity_allocated__gt=0,)
+ .values("stock")
+ .annotate(Sum("quantity_allocated"))
)
- allocation.deallocate_stock(quantity, commit=True)
- return allocation
+ quantity_allocation_for_stocks = {
+ allocation["stock"]: allocation["quantity_allocated__sum"]
+ for allocation in quantity_allocation_list
+ }
+ quantity_allocated = 0
+ allocations = []
-def allocate_stock(
- order_line: "OrderLine", country_code: str, quantity: int
-) -> Allocation:
- stock = Stock.objects.select_for_update(of=("self",)).get_variant_stock_for_country(
- country_code, order_line.variant
- )
- return _allocate_stock(stock, order_line, quantity)
+ for stock in stocks:
+ quantity_allocated_in_stock = quantity_allocation_for_stocks.get(stock.pk, 0)
+
+ quantity_available_in_stock = stock.quantity - quantity_allocated_in_stock
+
+ quantity_to_allocate = min(
+ (quantity - quantity_allocated), quantity_available_in_stock
+ )
+ if quantity_to_allocate > 0:
+ allocations.append(
+ Allocation(
+ order_line=order_line,
+ stock=stock,
+ quantity_allocated=quantity_to_allocate,
+ )
+ )
+
+ quantity_allocated += quantity_to_allocate
+ if quantity_allocated == quantity:
+ Allocation.objects.bulk_create(allocations)
+ return None
+ raise InsufficientStock(order_line.variant)
@transaction.atomic
-def deallocate_stock(
- order_line: "OrderLine", country_code: str, quantity: int
-) -> Allocation:
- stock = Stock.objects.get_variant_stock_for_country(
- country_code, order_line.variant
+def deallocate_stock(order_line: "OrderLine", quantity: int):
+ """Deallocate stocks for given `order_line`.
+
+ Function lock for update stocks and allocations related to given `order_line`.
+ Iterate over allocations sorted by `stock.pk` and deallocate as many items
+ as needed of available in stock for order line, until deallocated all required
+ quantity for the order line. If there is less quantity in stocks then
+ raise an exception.
+ """
+ allocations = (
+ order_line.allocations.select_related("stock")
+ .select_for_update(of=("self", "stock",))
+ .order_by("stock__pk")
+ )
+ quantity_dealocated = 0
+ for allocation in allocations:
+ quantity_to_deallocate = min(
+ (quantity - quantity_dealocated), allocation.quantity_allocated
+ )
+ if quantity_to_deallocate > 0:
+ allocation.quantity_allocated = (
+ F("quantity_allocated") - quantity_to_deallocate
+ )
+ quantity_dealocated += quantity_to_deallocate
+ if quantity_dealocated == quantity:
+ Allocation.objects.bulk_update(allocations, ["quantity_allocated"])
+ return None
+ raise Exception(
+ f"Can't deallocate {quantity} for variant: {order_line.variant}"
+ f" in order: {order_line.order}"
)
- return _deallocate_stock(stock, order_line, quantity)
@transaction.atomic
def increase_stock(
- order_line: "OrderLine", country_code: str, quantity: int, allocate: bool = False,
-) -> Stock:
- stock = Stock.objects.select_for_update(of=("self",)).get_or_create_for_country(
- country_code, order_line.variant
+ order_line: "OrderLine",
+ warehouse: Warehouse,
+ quantity: int,
+ allocate: bool = False,
+):
+ """Increse stock quantity for given `order_line` in a given warehouse.
+
+ Function lock for update stock and allocations related to given `order_line`
+ in a given warehouse. If the stock exists, increase the stock quantity
+ by given value. If not exist create a stock with the given quantity. This function
+ can create the allocation for increased quantity in stock by passing True
+ to `allocate` argument. If the order line has the allocation in this stock
+ function increase `quantity_allocated`. If allocation does not exist function
+ create a new allocation for this order line in this stock.
+ """
+ stock = (
+ Stock.objects.select_for_update(of=("self",))
+ .filter(warehouse=warehouse, product_variant=order_line.variant)
+ .first()
)
- stock.increase_stock(quantity, commit=True)
+ if stock:
+ stock.increase_stock(quantity, commit=True)
+ else:
+ stock = Stock.objects.create(
+ warehouse=warehouse, product_variant=order_line.variant, quantity=quantity
+ )
if allocate:
- _allocate_stock(stock, order_line, quantity)
- return stock
+ allocation = order_line.allocations.filter(stock=stock).first()
+ if allocation:
+ allocation.quantity_allocated = F("quantity_allocated") + quantity
+ allocation.save(update_fields=["quantity_allocated"])
+ else:
+ Allocation.objects.create(
+ order_line=order_line, stock=stock, quantity_allocated=quantity
+ )
@transaction.atomic
-def decrease_stock(order_line: "OrderLine", country_code: str, quantity: int) -> Stock:
- stock = Stock.objects.select_for_update(of=("self",)).get_variant_stock_for_country(
- country_code, order_line.variant
+def decrease_stock(order_line: "OrderLine", quantity: int):
+ """Decrease stock quantity for given `order_line`.
+
+ Function lock for update stocks and allocations related to given `order_line`.
+ Iterate over allocations sorted by `stock.pk` and deallocate and decrease stock
+ quantity for as many items as needed of available in stock for order line, until
+ deallocated all required quantity for the order line. If there is less quantity in
+ stocks then raise an exception.
+ """
+ allocations = (
+ order_line.allocations.select_related("stock")
+ .select_for_update(of=("self", "stock",))
+ .order_by("stock__pk")
+ )
+ quantity_decreased = 0
+ updated_stocks = []
+
+ for allocation in allocations:
+ quantity_to_decreased = min(
+ (quantity - quantity_decreased), allocation.quantity_allocated
+ )
+ if quantity_to_decreased > 0:
+
+ allocation.quantity_allocated = (
+ F("quantity_allocated") - quantity_to_decreased
+ )
+
+ stock = allocation.stock
+ stock.quantity = F("quantity") - quantity_to_decreased
+ updated_stocks.append(stock)
+
+ quantity_decreased += quantity_to_decreased
+ if quantity_decreased == quantity:
+ Allocation.objects.bulk_update(allocations, ["quantity_allocated"])
+ Stock.objects.bulk_update(updated_stocks, ["quantity"])
+ return None
+ raise Exception(
+ f"Can't decrease {quantity} for variant: {order_line.variant}"
+ f" in order: {order_line.order}"
)
- stock.decrease_stock(quantity, commit=True)
- _deallocate_stock(stock, order_line, quantity)
- return stock
@transaction.atomic
def set_stock_quantity(
- variant: "ProductVariant", country_code: str, quantity: int, commit: bool = True
+ variant: "ProductVariant", country_code: str, quantity: int
) -> Stock:
- stock = Stock.objects.select_for_update(of=("self",)).get_or_create_for_country(
- country_code, variant
+ stock = (
+ Stock.objects.select_for_update(of=("self",))
+ .get_variant_stocks_for_country(country_code, variant)
+ .order_by("pk")
+ .first()
)
- stock.quantity = quantity
- if commit:
+ if stock:
+ stock.quantity = quantity
stock.save(update_fields=["quantity"])
+ else:
+ warehouse = Warehouse.objects.for_country(country_code).first()
+ stock = Stock.objects.create(
+ warehouse=warehouse, product_variant=variant, quantity=quantity
+ )
return stock
diff --git a/saleor/warehouse/migrations/0007_auto_20200406_0341.py b/saleor/warehouse/migrations/0007_auto_20200406_0341.py
index 193e4bb47e..631b75cb36 100644
--- a/saleor/warehouse/migrations/0007_auto_20200406_0341.py
+++ b/saleor/warehouse/migrations/0007_auto_20200406_0341.py
@@ -36,11 +36,12 @@ def create_allocations(apps, schema_editor):
class Migration(migrations.Migration):
dependencies = [
- ("order", "0080_invoice"),
+ ("order", "0081_auto_20200406_0456"),
("warehouse", "0006_auto_20200228_0519"),
]
operations = [
+ migrations.AlterModelOptions(name="stock", options={"ordering": ("pk",)},),
migrations.CreateModel(
name="Allocation",
fields=[
@@ -71,7 +72,10 @@ class Migration(migrations.Migration):
),
),
],
- options={"unique_together": {("order_line", "stock")}},
+ options={
+ "ordering": ("pk",),
+ "unique_together": {("order_line", "stock")},
+ },
),
migrations.RunPython(create_allocations),
migrations.RemoveField(model_name="stock", name="quantity_allocated",),
diff --git a/saleor/warehouse/models.py b/saleor/warehouse/models.py
index 5f2aba7b73..5d7f0e8a2d 100644
--- a/saleor/warehouse/models.py
+++ b/saleor/warehouse/models.py
@@ -17,7 +17,11 @@ class WarehouseQueryset(models.QuerySet):
return self.select_related("address").prefetch_related("shipping_zones")
def for_country(self, country: str):
- return self.prefetch_data().get(shipping_zones__countries__contains=country)
+ return (
+ self.prefetch_data()
+ .filter(shipping_zones__countries__contains=country)
+ .order_by("pk")
+ )
class Warehouse(models.Model):
@@ -69,23 +73,14 @@ class StockQuerySet(models.QuerySet):
warehouse__in=query_warehouse
)
- def get_variant_stock_for_country(
+ def get_variant_stocks_for_country(
self, country_code: str, product_variant: ProductVariant
):
"""Return the stock information about the a stock for a given country.
Note it will raise a 'Stock.DoesNotExist' exception if no such stock is found.
"""
- return self.for_country(country_code).get(product_variant=product_variant)
-
- def get_or_create_for_country(
- self, country_code: str, product_variant: ProductVariant
- ):
- try:
- return self.get_variant_stock_for_country(country_code, product_variant)
- except Stock.DoesNotExist:
- warehouse = Warehouse.objects.for_country(country_code)
- return self.create(product_variant=product_variant, warehouse=warehouse)
+ return self.for_country(country_code).filter(product_variant=product_variant)
class Stock(models.Model):
@@ -99,6 +94,7 @@ class Stock(models.Model):
class Meta:
unique_together = [["warehouse", "product_variant"]]
+ ordering = ("pk",)
def __str__(self):
return f"{self.product_variant} - {self.warehouse.name}"
@@ -134,13 +130,4 @@ class Allocation(models.Model):
class Meta:
unique_together = [["order_line", "stock"]]
-
- 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"])
+ ordering = ("pk",)
diff --git a/saleor/webhook/payloads.py b/saleor/webhook/payloads.py
index 3a62e623a0..c7acb3fd1d 100644
--- a/saleor/webhook/payloads.py
+++ b/saleor/webhook/payloads.py
@@ -234,10 +234,10 @@ def generate_fulfillment_lines_payload(fulfillment: Fulfillment):
def generate_fulfillment_payload(fulfillment: Fulfillment):
serializer = PayloadSerializer()
- # fulfilment fields to serialize
+ # fulfillment fields to serialize
fulfillment_fields = ("status", "tracking_code", "order__user_email")
order_country = get_order_country(fulfillment.order)
- warehouse = Warehouse.objects.for_country(order_country)
+ warehouse = Warehouse.objects.for_country(order_country).first()
fulfillment_data = serializer.serialize(
[fulfillment],
fields=fulfillment_fields,
diff --git a/tests/api/test_checkout.py b/tests/api/test_checkout.py
index f5d79f1df6..1a6909c55a 100644
--- a/tests/api/test_checkout.py
+++ b/tests/api/test_checkout.py
@@ -170,6 +170,37 @@ def test_checkout_create(api_client, stock, graphql_address_data):
assert new_checkout.shipping_address.city == shipping_address["city"].upper()
+def test_checkout_create_multiple_warehouse(
+ api_client, variant_with_many_stocks, graphql_address_data
+):
+ variant = variant_with_many_stocks
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ test_email = "[email protected]"
+ shipping_address = graphql_address_data
+ variables = {
+ "checkoutInput": {
+ "lines": [{"quantity": 4, "variantId": variant_id}],
+ "email": test_email,
+ "shippingAddress": shipping_address,
+ }
+ }
+ assert not Checkout.objects.exists()
+ response = api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)
+ content = get_graphql_content(response)["data"]["checkoutCreate"]
+
+ # Look at the flag to see whether a new checkout was created or not
+ assert content["created"] is True
+
+ new_checkout = Checkout.objects.first()
+ assert new_checkout is not None
+ checkout_data = content["checkout"]
+ assert checkout_data["token"] == str(new_checkout.token)
+ assert new_checkout.lines.count() == 1
+ checkout_line = new_checkout.lines.first()
+ assert checkout_line.variant == variant
+ assert checkout_line.quantity == 4
+
+
@pytest.mark.parametrize(
"quantity, expected_error_message, error_code",
(
@@ -370,6 +401,31 @@ def test_checkout_create_logged_in_customer_custom_addresses(
assert new_checkout.billing_address.first_name == billing_address["firstName"]
+def test_checkout_create_check_lines_quantity_multiple_warehouse(
+ user_api_client, variant_with_many_stocks, graphql_address_data
+):
+ variant = variant_with_many_stocks
+
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ test_email = "[email protected]"
+ shipping_address = graphql_address_data
+ variables = {
+ "checkoutInput": {
+ "lines": [{"quantity": 16, "variantId": variant_id}],
+ "email": test_email,
+ "shippingAddress": shipping_address,
+ }
+ }
+ assert not Checkout.objects.exists()
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutCreate"]
+ assert data["errors"][0]["message"] == (
+ "Could not add item Test product (SKU_A). Only 7 remaining in stock."
+ )
+ assert data["errors"][0]["field"] == "quantity"
+
+
def test_checkout_create_check_lines_quantity(
user_api_client, stock, graphql_address_data
):
diff --git a/tests/api/test_order.py b/tests/api/test_order.py
index 4fe2c5259b..2330aed7e1 100644
--- a/tests/api/test_order.py
+++ b/tests/api/test_order.py
@@ -27,7 +27,7 @@ from saleor.order.models import Order, OrderEvent
from saleor.payment import ChargeStatus, CustomPaymentChoices, PaymentError
from saleor.payment.models import Payment
from saleor.shipping.models import ShippingMethod
-from saleor.warehouse.models import Stock
+from saleor.warehouse.models import Allocation, Stock
from ..utils import get_available_quantity_for_stock
from .utils import assert_no_permission, get_graphql_content
@@ -717,10 +717,8 @@ ORDER_CAN_FINALIZE_QUERY = """
"""
-def test_can_finalize_order(
- staff_api_client, permission_manage_orders, order_with_lines
-):
- order_id = graphene.Node.to_global_id("Order", order_with_lines.id)
+def test_can_finalize_order(staff_api_client, permission_manage_orders, draft_order):
+ order_id = graphene.Node.to_global_id("Order", draft_order.id)
variables = {"id": order_id}
staff_api_client.user.user_permissions.add(permission_manage_orders)
response = staff_api_client.post_graphql(ORDER_CAN_FINALIZE_QUERY, variables)
@@ -731,6 +729,8 @@ def test_can_finalize_order(
def test_can_finalize_order_no_order_lines(
staff_api_client, permission_manage_orders, order
):
+ order.status = OrderStatus.DRAFT
+ order.save(update_fields=["status"])
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id}
staff_api_client.user.user_permissions.add(permission_manage_orders)
@@ -739,32 +739,32 @@ def test_can_finalize_order_no_order_lines(
assert content["data"]["order"]["canFinalize"] is False
-def test_validate_draft_order(order_with_lines):
+def test_validate_draft_order(draft_order):
# should not raise any errors
- validate_draft_order(order_with_lines)
+ assert validate_draft_order(draft_order, "US") is None
-def test_validate_draft_order_wrong_shipping(order_with_lines):
- order = order_with_lines
+def test_validate_draft_order_wrong_shipping(draft_order):
+ order = draft_order
shipping_zone = order.shipping_method.shipping_zone
shipping_zone.countries = ["DE"]
shipping_zone.save()
assert order.shipping_address.country.code not in shipping_zone.countries
with pytest.raises(ValidationError) as e:
- validate_draft_order(order)
+ validate_draft_order(order, "US")
msg = "Shipping method is not valid for chosen shipping address"
assert e.value.error_dict["shipping"][0].message == msg
def test_validate_draft_order_no_order_lines(order):
with pytest.raises(ValidationError) as e:
- validate_draft_order(order)
+ validate_draft_order(order, "US")
msg = "Could not create order without any products."
assert e.value.error_dict["lines"][0].message == msg
-def test_validate_draft_order_non_existing_variant(order_with_lines):
- order = order_with_lines
+def test_validate_draft_order_non_existing_variant(draft_order):
+ order = draft_order
line = order.lines.first()
variant = line.variant
variant.delete()
@@ -772,13 +772,28 @@ def test_validate_draft_order_non_existing_variant(order_with_lines):
assert line.variant is None
with pytest.raises(ValidationError) as e:
- validate_draft_order(order)
+ validate_draft_order(order, "US")
msg = "Could not create orders with non-existing products."
assert e.value.error_dict["lines"][0].message == msg
+def test_validate_draft_order_out_of_stock_variant(draft_order):
+ order = draft_order
+ line = order.lines.first()
+ variant = line.variant
+
+ stock = variant.stocks.get()
+ stock.quantity = 0
+ stock.save(update_fields=["quantity"])
+
+ with pytest.raises(ValidationError) as e:
+ validate_draft_order(order, "US")
+ msg = "Insufficient product stock: SKU_A"
+ assert e.value.error_dict["lines"][0].message == msg
+
+
def test_draft_order_complete(
- staff_api_client, permission_manage_orders, staff_user, draft_order
+ staff_api_client, permission_manage_orders, staff_user, draft_order,
):
order = draft_order
query = """
@@ -794,13 +809,8 @@ def test_draft_order_complete(
# Ensure no events were created
assert not OrderEvent.objects.exists()
- line_1, line_2 = order.lines.order_by("-quantity").all()
- line_1.quantity = 1
- line_1.save(update_fields=["quantity"])
- stock_1 = Stock.objects.get(product_variant=line_1.variant)
- stock_2 = Stock.objects.get(product_variant=line_2.variant)
- assert get_available_quantity_for_stock(stock_1) >= line_1.quantity
- assert get_available_quantity_for_stock(stock_2) < line_2.quantity
+ # Ensure no allocation were created
+ assert not Allocation.objects.filter(order_line__order=order).exists()
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id}
@@ -811,17 +821,57 @@ def test_draft_order_complete(
data = content["data"]["draftOrderComplete"]["order"]
order.refresh_from_db()
assert data["status"] == order.status.upper()
- draft_placed_event, missing_stock_event = OrderEvent.objects.all()
+ draft_placed_event = OrderEvent.objects.get()
- assert missing_stock_event.user == staff_user
- assert missing_stock_event.type == order_events.OrderEvents.OVERSOLD_ITEMS
- assert missing_stock_event.parameters == {"oversold_items": [str(line_2)]}
+ for line in order:
+ allocation = line.allocations.get()
+ assert allocation.quantity_allocated == line.quantity_unfulfilled
assert draft_placed_event.user == staff_user
assert draft_placed_event.type == order_events.OrderEvents.PLACED_FROM_DRAFT
assert draft_placed_event.parameters == {}
+def test_draft_order_complete_out_of_stock_variant(
+ staff_api_client, permission_manage_orders, staff_user, draft_order
+):
+ order = draft_order
+ query = """
+ mutation draftComplete($id: ID!) {
+ draftOrderComplete(id: $id) {
+ orderErrors {
+ field
+ code
+ }
+ order {
+ status
+ }
+ }
+ }
+ """
+
+ # Ensure no events were created
+ assert not OrderEvent.objects.exists()
+
+ line_1, _ = order.lines.order_by("-quantity").all()
+ stock_1 = Stock.objects.get(product_variant=line_1.variant)
+ line_1.quantity = get_available_quantity_for_stock(stock_1) + 1
+ line_1.save(update_fields=["quantity"])
+
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variables = {"id": order_id}
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ error = content["data"]["draftOrderComplete"]["orderErrors"][0]
+ order.refresh_from_db()
+ assert order.status == OrderStatus.DRAFT
+
+ assert error["field"] == "lines"
+ assert error["code"] == OrderErrorCode.INSUFFICIENT_STOCK.name
+
+
def test_draft_order_complete_existing_user_email_updates_user_field(
staff_api_client, draft_order, customer_user, permission_manage_orders
):
diff --git a/tests/conftest.py b/tests/conftest.py
index c3feec9a78..5e4f21719c 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -765,6 +765,14 @@ def variant(product) -> ProductVariant:
return product_variant
+def variant_with_many_stocks(variant, warehouses_with_shipping_zone):
+ warehouses = warehouses_with_shipping_zone
+ Stock.objects.create(warehouse=warehouses[0], product_variant=variant, quantity=4)
+ Stock.objects.create(warehouse=warehouses[1], product_variant=variant, quantity=3)
+ return variant
+
+
@pytest.fixture
def product_variant_list(product):
return list(
@@ -1032,6 +1040,39 @@ def order_line(order, variant):
)
+def order_line_with_allocation_in_many_stocks(customer_user, variant_with_many_stocks):
+ address = customer_user.default_billing_address.get_copy()
+ variant = variant_with_many_stocks
+ stocks = variant.stocks.all().order_by("pk")
+
+ order = Order.objects.create(
+ billing_address=address, user_email=customer_user.email, user=customer_user
+ )
+
+ net = variant.get_price()
+ gross = Money(amount=net.amount * Decimal(1.23), currency=net.currency)
+ order_line = order.lines.create(
+ product_name=str(variant.product),
+ variant_name=str(variant),
+ product_sku=variant.sku,
+ is_shipping_required=variant.is_shipping_required(),
+ quantity=2,
+ variant=variant,
+ unit_price=TaxedMoney(net=net, gross=gross),
+ tax_rate=23,
+ )
+
+ Allocation.objects.bulk_create(
+ [
+ Allocation(order_line=order_line, stock=stocks[0], quantity_allocated=2),
+ Allocation(order_line=order_line, stock=stocks[1], quantity_allocated=1),
+ ]
+ )
+
+ return order_line
+
+
@pytest.fixture
def gift_card(customer_user, staff_user):
return GiftCard.objects.create(
@@ -1179,6 +1220,7 @@ def fulfillment(fulfilled_order):
@pytest.fixture
def draft_order(order_with_lines):
+ Allocation.objects.filter(order_line__order=order_with_lines).delete()
order_with_lines.status = OrderStatus.DRAFT
order_with_lines.save(update_fields=["status"])
return order_with_lines
@@ -1880,6 +1922,13 @@ def warehouses(address):
)
+def warehouses_with_shipping_zone(warehouses, shipping_zone):
+ warehouses[0].shipping_zones.add(shipping_zone)
+ warehouses[1].shipping_zones.add(shipping_zone)
+ return warehouses
+
+
@pytest.fixture
def warehouse_no_shipping_zone(address):
warehouse = Warehouse.objects.create(
diff --git a/tests/test_emails.py b/tests/test_emails.py
index 0ed80b1683..3dc57c8ec7 100644
--- a/tests/test_emails.py
+++ b/tests/test_emails.py
@@ -11,7 +11,7 @@ import saleor.account.emails as account_emails
import saleor.order.emails as emails
from saleor.core.emails import get_email_context, prepare_url
from saleor.core.utils import build_absolute_uri
-from saleor.order.utils import add_variant_to_order
+from saleor.order.utils import add_variant_to_draft_order
def test_get_email_context(site_settings):
@@ -151,7 +151,7 @@ def test_send_confirmation_emails_without_addresses_for_payment(
assert not order.lines.count()
template = emails.CONFIRM_PAYMENT_TEMPLATE
- add_variant_to_order(order, digital_content.product_variant, quantity=1)
+ add_variant_to_draft_order(order, digital_content.product_variant, quantity=1)
order.shipping_address = None
order.shipping_method = None
order.billing_address = None
@@ -185,7 +185,7 @@ def test_send_confirmation_emails_without_addresses_for_order(
assert not order.lines.count()
template = emails.CONFIRM_ORDER_TEMPLATE
- add_variant_to_order(order, digital_content.product_variant, quantity=1)
+ add_variant_to_draft_order(order, digital_content.product_variant, quantity=1)
order.shipping_address = None
order.shipping_method = None
order.billing_address = None
diff --git a/tests/test_order.py b/tests/test_order.py
index b6d1385e10..67cbfa2062 100644
--- a/tests/test_order.py
+++ b/tests/test_order.py
@@ -4,7 +4,6 @@ from unittest.mock import MagicMock, Mock, patch
import pytest
from prices import Money, TaxedMoney
-from saleor.core.exceptions import InsufficientStock
from saleor.core.weight import zero_weight
from saleor.discount.models import (
DiscountValueType,
@@ -19,7 +18,7 @@ from saleor.order.events import OrderEvent, OrderEventsEmails, email_sent_event
from saleor.order.models import Order
from saleor.order.templatetags.order_lines import display_translated_order_line_name
from saleor.order.utils import (
- add_variant_to_order,
+ add_variant_to_draft_order,
change_order_line_quantity,
delete_order_line,
get_voucher_discount_for_order,
@@ -58,14 +57,14 @@ def test_order_get_subtotal(order_with_lines):
assert order_with_lines.get_subtotal() == target_subtotal
-def test_add_variant_to_order_adds_line_for_new_variant(
+def test_add_variant_to_draft_order_adds_line_for_new_variant(
order_with_lines, product, product_translation_fr, settings
):
order = order_with_lines
variant = product.variants.get()
lines_before = order.lines.count()
settings.LANGUAGE_CODE = "fr"
- add_variant_to_order(order, variant, 1)
+ add_variant_to_draft_order(order, variant, 1)
line = order.lines.last()
assert order.lines.count() == lines_before + 1
@@ -77,33 +76,27 @@ def test_add_variant_to_order_adds_line_for_new_variant(
assert line.product_name == str(variant.product)
[email protected]("track_inventory", (True, False))
-def test_add_variant_to_order_allocates_stock_for_new_variant(
- order_with_lines, product, track_inventory
+def test_add_variant_to_draft_order_not_allocates_stock_for_new_variant(
+ order_with_lines, product
):
variant = product.variants.get()
- variant.track_inventory = track_inventory
- variant.save()
stock = Stock.objects.get(product_variant=variant)
stock_before = get_quantity_allocated_for_stock(stock)
- add_variant_to_order(order_with_lines, variant, 1)
+ add_variant_to_draft_order(order_with_lines, variant, 1)
stock.refresh_from_db()
- if track_inventory:
- assert get_quantity_allocated_for_stock(stock) == stock_before + 1
- else:
- assert get_quantity_allocated_for_stock(stock) == stock_before
+ assert get_quantity_allocated_for_stock(stock) == stock_before
-def test_add_variant_to_order_edits_line_for_existing_variant(order_with_lines):
+def test_add_variant_to_draft_order_edits_line_for_existing_variant(order_with_lines):
existing_line = order_with_lines.lines.first()
variant = existing_line.variant
lines_before = order_with_lines.lines.count()
line_quantity_before = existing_line.quantity
- add_variant_to_order(order_with_lines, variant, 1)
+ add_variant_to_draft_order(order_with_lines, variant, 1)
existing_line.refresh_from_db()
assert order_with_lines.lines.count() == lines_before
@@ -111,33 +104,23 @@ def test_add_variant_to_order_edits_line_for_existing_variant(order_with_lines):
assert existing_line.quantity == line_quantity_before + 1
-def test_add_variant_to_order_allocates_stock_for_existing_variant(order_with_lines):
- existing_line = order_with_lines.lines.first()
- variant = existing_line.variant
- stock = Stock.objects.get(product_variant=variant)
- stock_before = get_quantity_allocated_for_stock(stock)
-
- add_variant_to_order(order_with_lines, variant, 1)
-
- stock.refresh_from_db()
- assert get_quantity_allocated_for_stock(stock) == stock_before + 1
-
-
-def test_add_variant_to_order_allow_overselling(order_with_lines):
+def test_add_variant_to_draft_order_not_allocates_stock_for_existing_variant(
+ order_with_lines,
+):
existing_line = order_with_lines.lines.first()
variant = existing_line.variant
stock = Stock.objects.get(product_variant=variant)
stock_before = get_quantity_allocated_for_stock(stock)
+ quantity_before = existing_line.quantity
+ quantity_unfulfilled_before = existing_line.quantity_unfulfilled
- quantity = stock.quantity + 1
- with pytest.raises(InsufficientStock):
- add_variant_to_order(
- order_with_lines, variant, quantity, allow_overselling=False
- )
+ add_variant_to_draft_order(order_with_lines, variant, 1)
- add_variant_to_order(order_with_lines, variant, quantity, allow_overselling=True)
stock.refresh_from_db()
- assert get_quantity_allocated_for_stock(stock) == stock_before + quantity
+ existing_line.refresh_from_db()
+ assert get_quantity_allocated_for_stock(stock) == stock_before
+ assert existing_line.quantity == quantity_before + 1
+ assert existing_line.quantity_unfulfilled == quantity_unfulfilled_before + 1
@pytest.mark.parametrize("track_inventory", (True, False))
@@ -375,7 +358,7 @@ def test_calculate_order_weight(order_with_lines):
def test_order_weight_add_more_variant(order_with_lines):
variant = order_with_lines.lines.first().variant
- add_variant_to_order(order_with_lines, variant, 2)
+ add_variant_to_draft_order(order_with_lines, variant, 2)
order_with_lines.refresh_from_db()
assert order_with_lines.weight == _calculate_order_weight_from_lines(
order_with_lines
@@ -384,7 +367,7 @@ def test_order_weight_add_more_variant(order_with_lines):
def test_order_weight_add_new_variant(order_with_lines, product):
variant = product.variants.first()
- add_variant_to_order(order_with_lines, variant, 2)
+ add_variant_to_draft_order(order_with_lines, variant, 2)
order_with_lines.refresh_from_db()
assert order_with_lines.weight == _calculate_order_weight_from_lines(
order_with_lines
@@ -413,7 +396,7 @@ def test_get_order_weight_non_existing_product(order_with_lines, product):
# Removing product should not affect order's weight
order = order_with_lines
variant = product.variants.first()
- add_variant_to_order(order, variant, 1)
+ add_variant_to_draft_order(order, variant, 1)
old_weight = order.get_total_weight()
product.delete()
diff --git a/tests/test_stock.py b/tests/test_stock.py
index cd1582d012..024cb8e427 100644
--- a/tests/test_stock.py
+++ b/tests/test_stock.py
@@ -1,33 +1,21 @@
-import pytest
-
-from saleor.core.exceptions import InsufficientStock
-from saleor.warehouse.availability import (
- are_all_product_variants_in_stock,
- check_stock_quantity,
- get_available_quantity,
- get_quantity_allocated,
- products_with_low_stock,
-)
-from saleor.warehouse.management import (
- allocate_stock,
- deallocate_stock,
- decrease_stock,
- increase_stock,
-)
-from saleor.warehouse.models import Allocation, Stock
+from saleor.warehouse.models import Stock
COUNTRY_CODE = "US"
-def test_stock_for_country(product):
- stock = Stock.objects.get()
- warehouse = stock.warehouse
- assert COUNTRY_CODE in warehouse.countries
- assert stock.warehouse == warehouse
-
- stock_qs = Stock.objects.for_country(COUNTRY_CODE)
- assert stock_qs.count() == 1
- assert stock_qs.first() == stock
+def test_stocks_for_country(variant_with_many_stocks):
+ [stock1, stock2] = (
+ Stock.objects.filter(product_variant=variant_with_many_stocks)
+ .for_country(COUNTRY_CODE)
+ .order_by("pk")
+ .all()
+ )
+ warehouse1 = stock1.warehouse
+ warehouse2 = stock2.warehouse
+ assert stock1.quantity == 4
+ assert COUNTRY_CODE in warehouse1.countries
+ assert stock2.quantity == 3
+ assert COUNTRY_CODE in warehouse2.countries
def test_stock_for_country_does_not_exists(product, warehouse):
@@ -39,229 +27,3 @@ def test_stock_for_country_does_not_exists(product, warehouse):
assert fake_country_code not in warehouse.countries
stock_qs = Stock.objects.for_country(fake_country_code)
assert not stock_qs.exists()
-
-
-def test_check_stock_quantity_without_allocation(order_line, stock):
- assert not Allocation.objects.filter(order_line=order_line, stock=stock).exists()
- assert (
- check_stock_quantity(order_line.variant, COUNTRY_CODE, order_line.quantity)
- is None
- )
-
-
-def test_check_stock_quantity_without_stock(order_line):
- with pytest.raises(InsufficientStock):
- check_stock_quantity(order_line.variant, COUNTRY_CODE, 5)
-
-
-def test_check_stock_quantity_many_allocations(allocations, variant):
- assert check_stock_quantity(variant, COUNTRY_CODE, 1) is None
-
-
-def test_check_stock_quantity_many_allocations_out_of_stock(allocations, variant):
- quantity = allocations[0].stock.quantity
- with pytest.raises(InsufficientStock):
- check_stock_quantity(variant, COUNTRY_CODE, quantity)
-
-
-def test_check_stock_quantity_out_of_stock(allocation, variant):
- quantity = allocation.stock.quantity
- with pytest.raises(InsufficientStock):
- check_stock_quantity(variant, COUNTRY_CODE, quantity)
-
-
-def test_check_stock_quantity(allocation, variant):
- assert check_stock_quantity(variant, COUNTRY_CODE, 1) is None
-
-
-def test_are_all_product_variants_in_stock_all_in_stock(stock):
- assert are_all_product_variants_in_stock(
- stock.product_variant.product, COUNTRY_CODE
- )
-
-
-def test_are_all_product_variants_in_stock_stock_empty(allocation, variant):
- allocation.quantity_allocated = allocation.stock.quantity
- allocation.save(update_fields=["quantity_allocated"])
-
- assert not are_all_product_variants_in_stock(variant.product, COUNTRY_CODE)
-
-
-def test_are_all_product_variants_in_stock_lack_of_stocks(variant):
- assert not are_all_product_variants_in_stock(variant.product, COUNTRY_CODE)
-
-
-def test_products_with_low_stock_one_stock(product, settings):
- settings.LOW_STOCK_THRESHOLD = 70
- stock = Stock.objects.first()
- result = products_with_low_stock()
- assert len(result) == 1
- stock_result = result[0]
- assert (
- stock_result["product_variant__product_id"] == stock.product_variant.product_id
- )
- assert stock_result["warehouse_id"] == stock.warehouse_id
- assert stock_result["total_stock"] == stock.quantity
-
-
-def test_products_with_low_stock_many_stocks(stock, settings):
- settings.LOW_STOCK_THRESHOLD = 70
- quantity = Stock.objects.all().values_list("quantity", flat=True)
- result = products_with_low_stock()
- assert result[0]["total_stock"] == sum(quantity)
-
-
-def test_products_with_low_stock_filter_properly(stock, settings):
- quantities = Stock.objects.order_by("quantity").values_list("quantity", flat=True)
- settings.LOW_STOCK_THRESHOLD = quantities[0] + 1
- result = products_with_low_stock()
- assert len(result) == 0
-
-
-def test_decrease_stock(allocation):
- stock = allocation.stock
- stock.quantity = 100
- stock.save(update_fields=["quantity"])
- allocation.quantity_allocated = 80
- allocation.save(update_fields=["quantity_allocated"])
-
- decrease_stock(allocation.order_line, COUNTRY_CODE, 50)
-
- stock.refresh_from_db()
- assert stock.quantity == 50
- allocation.refresh_from_db()
- assert allocation.quantity_allocated == 30
-
-
-def test_increase_stock_without_allocate(allocation):
- stock = allocation.stock
- stock.quantity = 100
- stock.save(update_fields=["quantity"])
- allocation.quantity_allocated = 80
- allocation.save(update_fields=["quantity_allocated"])
-
- increase_stock(allocation.order_line, COUNTRY_CODE, 50, allocate=False)
-
- stock.refresh_from_db()
- assert stock.quantity == 150
- allocation.refresh_from_db()
- assert allocation.quantity_allocated == 80
-
-
-def test_increase_stock_with_allocate(allocation):
- stock = allocation.stock
- stock.quantity = 100
- stock.save(update_fields=["quantity"])
- allocation.quantity_allocated = 80
- allocation.save(update_fields=["quantity_allocated"])
-
- increase_stock(allocation.order_line, COUNTRY_CODE, 50, allocate=True)
-
- stock.refresh_from_db()
- assert stock.quantity == 150
- allocation.refresh_from_db()
- assert allocation.quantity_allocated == 130
-
-
-def test_increase_stock_new_allocation(order_line, stock):
- assert not Allocation.objects.filter(order_line=order_line, stock=stock).exists()
- stock.quantity = 100
- stock.save(update_fields=["quantity"])
-
- increase_stock(order_line, COUNTRY_CODE, 50, allocate=True)
-
- stock.refresh_from_db()
- assert stock.quantity == 150
- allocation = Allocation.objects.get(order_line=order_line, stock=stock)
- assert allocation.quantity_allocated == 50
-
-
-def test_deallocate_stock(allocation):
- stock = allocation.stock
- stock.quantity = 100
- stock.save(update_fields=["quantity"])
- allocation.quantity_allocated = 80
- allocation.save(update_fields=["quantity_allocated"])
-
- deallocate_stock(allocation.order_line, COUNTRY_CODE, 50)
-
- stock.refresh_from_db()
- assert stock.quantity == 100
- allocation.refresh_from_db()
- assert allocation.quantity_allocated == 30
-
-
-def test_allocate_stock(allocation):
- stock = allocation.stock
- stock.quantity = 100
- stock.save(update_fields=["quantity"])
- allocation.quantity_allocated = 80
- allocation.save(update_fields=["quantity_allocated"])
-
- allocate_stock(allocation.order_line, COUNTRY_CODE, 20)
-
- stock.refresh_from_db()
- assert stock.quantity == 100
- allocation.refresh_from_db()
- assert allocation.quantity_allocated == 100
-
-
-def test_allocate_stock_new_allocation(order_line, stock):
- assert not Allocation.objects.filter(order_line=order_line, stock=stock).exists()
- stock.quantity = 100
- stock.save(update_fields=["quantity"])
-
- allocate_stock(order_line, COUNTRY_CODE, 50)
-
- stock.refresh_from_db()
- assert stock.quantity == 100
- allocation = Allocation.objects.get(order_line=order_line, stock=stock)
- assert allocation.quantity_allocated == 50
-
-
-def test_get_quantity_allocated_without_allocation(order_line, stock):
- assert not Allocation.objects.filter(order_line=order_line, stock=stock).exists()
- quantity_allocated = get_quantity_allocated(order_line.variant, COUNTRY_CODE)
- assert quantity_allocated == 0
-
-
-def test_get_quantity_allocated_without_stock(order_line):
- quantity_allocated = get_quantity_allocated(order_line.variant, COUNTRY_CODE)
- assert quantity_allocated == 0
-
-
-def test_get_quantity_allocated_many_allocations(allocations, variant):
- quantity_allocated = get_quantity_allocated(variant, COUNTRY_CODE)
- assert quantity_allocated == 7
-
-
-def test_get_quantity_allocated(allocation):
- quantity_allocated = get_quantity_allocated(
- allocation.order_line.variant, COUNTRY_CODE
- )
- assert quantity_allocated == allocation.order_line.quantity
-
-
-def test_get_available_quantity_without_allocation(order_line, stock):
- assert not Allocation.objects.filter(order_line=order_line, stock=stock).exists()
- available_quantity = get_available_quantity(order_line.variant, COUNTRY_CODE)
- assert available_quantity == stock.quantity
-
-
-def test_get_available_quantity_without_stock(order_line):
- available_quantity = get_available_quantity(order_line.variant, COUNTRY_CODE)
- assert available_quantity == 0
-
-
-def test_get_available_quantity_many_allocations(allocations, variant):
- available_quantity = get_available_quantity(variant, COUNTRY_CODE)
- assert available_quantity == 8
-
-
-def test_get_available_quantity(allocation):
- available_quantity = get_available_quantity(
- allocation.order_line.variant, COUNTRY_CODE
- )
- assert available_quantity == (
- allocation.stock.quantity - allocation.quantity_allocated
- )
diff --git a/tests/test_stock_availability.py b/tests/test_stock_availability.py
new file mode 100644
index 0000000000..b64d6edd6f
--- /dev/null
+++ b/tests/test_stock_availability.py
@@ -0,0 +1,134 @@
+import pytest
+from django.test import override_settings
+
+from saleor.core.exceptions import InsufficientStock
+from saleor.warehouse.availability import (
+ are_all_product_variants_in_stock,
+ check_stock_quantity,
+ get_available_quantity,
+ get_available_quantity_for_customer,
+ get_quantity_allocated,
+)
+from saleor.warehouse.models import Allocation
+
+COUNTRY_CODE = "US"
+
+
+def test_check_stock_quantity(variant_with_many_stocks):
+ assert check_stock_quantity(variant_with_many_stocks, COUNTRY_CODE, 7) is None
+
+
+def test_check_stock_quantity_out_of_stock(variant_with_many_stocks):
+ with pytest.raises(InsufficientStock):
+ check_stock_quantity(variant_with_many_stocks, COUNTRY_CODE, 8)
+
+
+def test_check_stock_quantity_with_allocations(
+ variant_with_many_stocks, order_line_with_allocation_in_many_stocks
+):
+ assert check_stock_quantity(variant_with_many_stocks, COUNTRY_CODE, 4) is None
+
+
+def test_check_stock_quantity_with_allocations_out_of_stock(
+ variant_with_many_stocks, order_line_with_allocation_in_many_stocks
+):
+ with pytest.raises(InsufficientStock):
+ check_stock_quantity(variant_with_many_stocks, COUNTRY_CODE, 5)
+
+
+def test_check_stock_quantity_without_stocks(variant_with_many_stocks):
+ variant_with_many_stocks.stocks.all().delete()
+ with pytest.raises(InsufficientStock):
+ check_stock_quantity(variant_with_many_stocks, COUNTRY_CODE, 1)
+
+
+def test_check_stock_quantity_without_one_stock(variant_with_many_stocks):
+ variant_with_many_stocks.stocks.get(quantity=3).delete()
+ assert check_stock_quantity(variant_with_many_stocks, COUNTRY_CODE, 4) is None
+
+
+def test_get_available_quantity_without_allocation(order_line, stock):
+ assert not Allocation.objects.filter(order_line=order_line, stock=stock).exists()
+ available_quantity = get_available_quantity(order_line.variant, COUNTRY_CODE)
+ assert available_quantity == stock.quantity
+
+
+def test_get_available_quantity(variant_with_many_stocks):
+ available_quantity = get_available_quantity(variant_with_many_stocks, COUNTRY_CODE)
+ assert available_quantity == 7
+
+
+def test_get_available_quantity_with_allocations(
+ variant_with_many_stocks, order_line_with_allocation_in_many_stocks
+):
+ available_quantity = get_available_quantity(variant_with_many_stocks, COUNTRY_CODE)
+ assert available_quantity == 4
+
+
+def test_get_available_quantity_without_stocks(variant_with_many_stocks):
+ variant_with_many_stocks.stocks.all().delete()
+ available_quantity = get_available_quantity(variant_with_many_stocks, COUNTRY_CODE)
+ assert available_quantity == 0
+
+
+@override_settings(MAX_CHECKOUT_LINE_QUANTITY=15)
+def test_get_available_quantity_for_customer(variant_with_many_stocks, settings):
+ stock = variant_with_many_stocks.stocks.first()
+ stock.quantity = 16
+ stock.save(update_fields=["quantity"])
+ available_quantity = get_available_quantity_for_customer(
+ variant_with_many_stocks, COUNTRY_CODE
+ )
+ assert available_quantity == settings.MAX_CHECKOUT_LINE_QUANTITY
+
+
+def test_get_available_quantity_for_customer_without_stocks(variant_with_many_stocks):
+ variant_with_many_stocks.stocks.all().delete()
+ available_quantity = get_available_quantity_for_customer(
+ variant_with_many_stocks, COUNTRY_CODE
+ )
+ assert available_quantity == 0
+
+
+def test_get_quantity_allocated(
+ variant_with_many_stocks, order_line_with_allocation_in_many_stocks
+):
+ quantity_allocated = get_quantity_allocated(variant_with_many_stocks, COUNTRY_CODE)
+ assert quantity_allocated == 3
+
+
+def test_get_quantity_allocated_without_allocation(variant_with_many_stocks):
+ quantity_allocated = get_quantity_allocated(variant_with_many_stocks, COUNTRY_CODE)
+ assert quantity_allocated == 0
+
+
+def test_get_quantity_allocated_without_stock(variant_with_many_stocks):
+ variant_with_many_stocks.stocks.all().delete()
+ quantity_allocated = get_quantity_allocated(variant_with_many_stocks, COUNTRY_CODE)
+ assert quantity_allocated == 0
+
+
+def test_are_all_product_variants_in_stock_all_in_stock(stock):
+ assert are_all_product_variants_in_stock(
+ stock.product_variant.product, COUNTRY_CODE
+ )
+
+
+def test_are_all_product_variants_in_stock_stock_empty(allocation, variant):
+ allocation.quantity_allocated = allocation.stock.quantity
+ allocation.save(update_fields=["quantity_allocated"])
+
+ assert not are_all_product_variants_in_stock(variant.product, COUNTRY_CODE)
+
+
+def test_are_all_product_variants_in_stock_lack_of_stocks(variant):
+ assert not are_all_product_variants_in_stock(variant.product, COUNTRY_CODE)
+
+
+def test_are_all_product_variants_in_stock_warehouse_without_stock(
+ variant_with_many_stocks,
+):
+ variant_with_many_stocks.stocks.first().delete()
+ assert are_all_product_variants_in_stock(
+ variant_with_many_stocks.product, COUNTRY_CODE
+ )
diff --git a/tests/test_stock_management.py b/tests/test_stock_management.py
new file mode 100644
index 0000000000..ba76c4cff2
--- /dev/null
+++ b/tests/test_stock_management.py
@@ -0,0 +1,259 @@
+import pytest
+
+from saleor.core.exceptions import InsufficientStock
+from saleor.warehouse.management import (
+ allocate_stock,
+ deallocate_stock,
+ decrease_stock,
+ increase_stock,
+)
+from saleor.warehouse.models import Allocation
+
+COUNTRY_CODE = "US"
+
+
+def test_allocate_stock(order_line, stock):
+ stock.quantity = 100
+ stock.save(update_fields=["quantity"])
+
+ allocate_stock(order_line, COUNTRY_CODE, 50)
+
+ stock.refresh_from_db()
+ assert stock.quantity == 100
+ allocation = Allocation.objects.get(order_line=order_line, stock=stock)
+ assert allocation.quantity_allocated == 50
+
+
+def test_allocate_stock_many_stocks(order_line, variant_with_many_stocks):
+ variant = variant_with_many_stocks
+ stocks = variant.stocks.all()
+
+ allocate_stock(order_line, COUNTRY_CODE, 5)
+
+ allocations = Allocation.objects.filter(order_line=order_line, stock__in=stocks)
+ assert allocations[0].quantity_allocated == 4
+ assert allocations[1].quantity_allocated == 1
+
+
+def test_allocate_stock_many_stocks_partially_allocated(
+ order_line, order_line_with_allocation_in_many_stocks
+):
+ allocated_line = order_line_with_allocation_in_many_stocks
+ variant = allocated_line.variant
+ stocks = variant.stocks.all()
+
+ allocate_stock(order_line, COUNTRY_CODE, 4)
+
+ allocations = Allocation.objects.filter(order_line=order_line, stock__in=stocks)
+ assert allocations[0].quantity_allocated == 2
+ assert allocations[1].quantity_allocated == 2
+
+
+def test_allocate_stock_partially_allocated_insufficient_stocks(
+ order_line, order_line_with_allocation_in_many_stocks
+):
+ allocated_line = order_line_with_allocation_in_many_stocks
+ variant = allocated_line.variant
+ stocks = variant.stocks.all()
+
+ with pytest.raises(InsufficientStock):
+ allocate_stock(order_line, COUNTRY_CODE, 6)
+
+ assert not Allocation.objects.filter(
+ order_line=order_line, stock__in=stocks
+ ).exists()
+
+
+def test_allocate_stock_insufficient_stocks(order_line, variant_with_many_stocks):
+ variant = variant_with_many_stocks
+ stocks = variant.stocks.all()
+
+ with pytest.raises(InsufficientStock):
+ allocate_stock(order_line, COUNTRY_CODE, 10)
+
+ assert not Allocation.objects.filter(
+ order_line=order_line, stock__in=stocks
+ ).exists()
+
+
+def test_deallocate_stock(allocation):
+ stock = allocation.stock
+ stock.quantity = 100
+ stock.save(update_fields=["quantity"])
+ allocation.quantity_allocated = 80
+ allocation.save(update_fields=["quantity_allocated"])
+
+ deallocate_stock(allocation.order_line, 80)
+
+ stock.refresh_from_db()
+ assert stock.quantity == 100
+ allocation.refresh_from_db()
+ assert allocation.quantity_allocated == 0
+
+
+def test_deallocate_stock_partially(allocation):
+ stock = allocation.stock
+ stock.quantity = 100
+ stock.save(update_fields=["quantity"])
+ allocation.quantity_allocated = 80
+ allocation.save(update_fields=["quantity_allocated"])
+
+ deallocate_stock(allocation.order_line, 50)
+
+ stock.refresh_from_db()
+ assert stock.quantity == 100
+ allocation.refresh_from_db()
+ assert allocation.quantity_allocated == 30
+
+
+def test_deallocate_stock_many_allocations(order_line_with_allocation_in_many_stocks,):
+ order_line = order_line_with_allocation_in_many_stocks
+
+ deallocate_stock(order_line, 3)
+
+ allocations = order_line.allocations.all()
+ assert allocations[0].quantity_allocated == 0
+ assert allocations[1].quantity_allocated == 0
+
+
+def test_deallocate_stock_many_allocations_partially(
+ order_line_with_allocation_in_many_stocks,
+):
+ order_line = order_line_with_allocation_in_many_stocks
+
+ deallocate_stock(order_line, 1)
+
+ allocations = order_line.allocations.all()
+ assert allocations[0].quantity_allocated == 1
+ assert allocations[1].quantity_allocated == 1
+
+
+def test_increase_stock_without_allocate(allocation):
+ stock = allocation.stock
+ stock.quantity = 100
+ stock.save(update_fields=["quantity"])
+ allocation.quantity_allocated = 80
+ allocation.save(update_fields=["quantity_allocated"])
+
+ increase_stock(allocation.order_line, stock.warehouse, 50, allocate=False)
+
+ stock.refresh_from_db()
+ assert stock.quantity == 150
+ allocation.refresh_from_db()
+ assert allocation.quantity_allocated == 80
+
+
+def test_increase_stock_with_allocate(allocation):
+ stock = allocation.stock
+ stock.quantity = 100
+ stock.save(update_fields=["quantity"])
+ allocation.quantity_allocated = 80
+ allocation.save(update_fields=["quantity_allocated"])
+
+ increase_stock(allocation.order_line, stock.warehouse, 50, allocate=True)
+
+ stock.refresh_from_db()
+ assert stock.quantity == 150
+ allocation.refresh_from_db()
+ assert allocation.quantity_allocated == 130
+
+
+def test_increase_stock_with_new_allocation(order_line, stock):
+ assert not Allocation.objects.filter(order_line=order_line, stock=stock).exists()
+ stock.quantity = 100
+ stock.save(update_fields=["quantity"])
+
+ increase_stock(order_line, stock.warehouse, 50, allocate=True)
+
+ stock.refresh_from_db()
+ assert stock.quantity == 150
+ allocation = Allocation.objects.get(order_line=order_line, stock=stock)
+ assert allocation.quantity_allocated == 50
+
+
+def test_decrease_stock(allocation):
+ stock = allocation.stock
+ stock.quantity = 100
+ stock.save(update_fields=["quantity"])
+ allocation.quantity_allocated = 80
+ allocation.save(update_fields=["quantity_allocated"])
+
+ decrease_stock(allocation.order_line, 50)
+
+ stock.refresh_from_db()
+ assert stock.quantity == 50
+ allocation.refresh_from_db()
+ assert allocation.quantity_allocated == 30
+
+
+def test_decrease_stock_partially(allocation):
+ stock = allocation.stock
+ stock.quantity = 100
+ stock.save(update_fields=["quantity"])
+ allocation.quantity_allocated = 80
+ allocation.save(update_fields=["quantity_allocated"])
+
+ decrease_stock(allocation.order_line, 80)
+
+ stock.refresh_from_db()
+ assert stock.quantity == 20
+ allocation.refresh_from_db()
+ assert allocation.quantity_allocated == 0
+
+
+def test_decrease_stock_many_allocations(order_line_with_allocation_in_many_stocks,):
+ order_line = order_line_with_allocation_in_many_stocks
+
+ decrease_stock(order_line, 3)
+
+ allocations = order_line.allocations.all()
+ if not allocations[0].quantity_allocated == 0:
+ import ipdb
+
+ ipdb.set_trace()
+ if not allocations[0].stock.quantity == 2:
+ import ipdb
+
+ ipdb.set_trace()
+ if not allocations[1].quantity_allocated == 0:
+ import ipdb
+
+ ipdb.set_trace()
+ if not allocations[1].stock.quantity == 2:
+ import ipdb
+
+ ipdb.set_trace()
+ assert allocations[0].quantity_allocated == 0
+ assert allocations[0].stock.quantity == 2
+ assert allocations[1].quantity_allocated == 0
+ assert allocations[1].stock.quantity == 2
+
+
+def test_decrease_stock_many_allocations_partially(
+ order_line_with_allocation_in_many_stocks,
+):
+ order_line = order_line_with_allocation_in_many_stocks
+
+ decrease_stock(order_line, 2)
+
+ allocations = order_line.allocations.all()
+ if not allocations[0].quantity_allocated == 0:
+ import ipdb
+
+ ipdb.set_trace()
+ if not allocations[0].stock.quantity == 2:
+ import ipdb
+
+ ipdb.set_trace()
+ if not allocations[1].quantity_allocated == 1:
+ import ipdb
+
+ ipdb.set_trace()
+ if not allocations[1].stock.quantity == 3:
+ import ipdb
+
+ ipdb.set_trace()
+ assert allocations[0].quantity_allocated == 0
+ assert allocations[0].stock.quantity == 2
+ assert allocations[1].quantity_allocated == 1
+ assert allocations[1].stock.quantity == 3