Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Saleor 4421/3.1/extend orderfulfill mutation by new flag to allow stock exceeded (#8155)
L3str4ngeb51a9a832c6c
diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.pyindex a573364f76..8fe1d4fb37 100644--- a/saleor/graphql/checkout/mutations.py+++ b/saleor/graphql/checkout/mutations.py@@ -181,7 +181,7 @@ def check_lines_quantity(errors = [ValidationError(f"Could not add items {item.variant}. "- f"Only {item.available_quantity} remaining in stock.",+ f"Only {max(item.available_quantity, 0)} remaining in stock.",code=e.code,)for item in e.itemsdiff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.pyindex a06a1f164e..193750344e 100644--- a/saleor/graphql/checkout/tests/test_checkout.py+++ b/saleor/graphql/checkout/tests/test_checkout.py@@ -990,6 +990,62 @@ def test_checkout_create_check_lines_quantity_multiple_warehouse(assert data["errors"][0]["field"] == "quantity"+def test_checkout_create_when_all_stocks_exceeded(+ user_api_client, variant_with_many_stocks, graphql_address_data, channel_USD+):+ variant = variant_with_many_stocks+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)+ variables = {+ "checkoutInput": {+ "lines": [{"quantity": 16, "variantId": variant_id}],+ "email": "[email protected]",+ "shippingAddress": graphql_address_data,+ "channel": channel_USD.slug,+ }+ }++ # make stocks exceeded and assert+ variant.stocks.update(quantity=-99)+ for stock in variant.stocks.all():+ assert stock.quantity == -99++ 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 items SKU_A. Only 0 remaining in stock."+ )+ assert data["errors"][0]["field"] == "quantity"+++def test_checkout_create_when_one_stock_exceeded(+ user_api_client, variant_with_many_stocks, graphql_address_data, channel_USD+):+ variant = variant_with_many_stocks+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)+ variables = {+ "checkoutInput": {+ "lines": [{"quantity": 16, "variantId": variant_id}],+ "email": "[email protected]",+ "shippingAddress": graphql_address_data,+ "channel": channel_USD.slug,+ }+ }++ # make first stock exceeded+ stock = variant.stocks.first()+ stock.quantity = -1+ stock.save()++ 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 items SKU_A. Only 2 remaining in stock."+ )+ assert data["errors"][0]["field"] == "quantity"++@override_settings(DEFAULT_COUNTRY="DE")def test_checkout_create_sets_country_from_shipping_address_country(user_api_client,diff --git a/saleor/graphql/order/mutations/fulfillments.py b/saleor/graphql/order/mutations/fulfillments.pyindex efe767a327..d47b2c1e92 100644--- a/saleor/graphql/order/mutations/fulfillments.py+++ b/saleor/graphql/order/mutations/fulfillments.py@@ -68,6 +68,11 @@ class OrderFulfillInput(graphene.InputObjectType):description="If true, send an email notification to the customer.")+ allow_stock_to_be_exceeded = graphene.Boolean(+ description="If true, then allow proceed fulfillment when stock is exceeded.",+ default_value=False,+ )+class FulfillmentUpdateTrackingInput(graphene.InputObjectType):tracking_number = graphene.String(description="Fulfillment tracking number.")@@ -246,6 +251,9 @@ class OrderFulfill(BaseMutation):manager = context.pluginslines_for_warehouses = cleaned_input["lines_for_warehouses"]notify_customer = cleaned_input.get("notify_customer", True)+ allow_stock_to_be_exceeded = cleaned_input.get(+ "allow_stock_to_be_exceeded", False+ )gift_card_lines = cleaned_input["gift_card_lines"]quantities = cleaned_input["quantities"]@@ -267,6 +275,7 @@ class OrderFulfill(BaseMutation):dict(lines_for_warehouses),manager,notify_customer,+ allow_stock_to_be_exceeded=allow_stock_to_be_exceeded,approved=info.context.site.settings.fulfillment_auto_approve,)except InsufficientStock as exc:@@ -423,6 +432,9 @@ class FulfillmentApprove(BaseMutation):notify_customer = graphene.Boolean(required=True, description="True if confirmation email should be send.")+ allow_stock_to_be_exceeded = graphene.Boolean(+ default_value=False, description="True if stock could be exceeded."+ )class Meta:description = f"{ADDED_IN_31} Approve existing fulfillment."@@ -458,6 +470,7 @@ class FulfillmentApprove(BaseMutation):info.context.user,info.context.app,info.context.plugins,+ allow_stock_to_be_exceeded=data.get("allow_stock_to_be_exceeded"),notify_customer=data["notify_customer"],)order.refresh_from_db(fields=["status"])diff --git a/saleor/graphql/order/tests/test_fulfillment.py b/saleor/graphql/order/tests/test_fulfillment.pyindex 1baad4f297..f525fa135e 100644--- a/saleor/graphql/order/tests/test_fulfillment.py+++ b/saleor/graphql/order/tests/test_fulfillment.py@@ -125,10 +125,129 @@ def test_order_fulfill(fulfillment_lines_for_warehouses,ANY,True,+ allow_stock_to_be_exceeded=False,approved=fulfillment_auto_approve,)+def test_order_fulfill_with_stock_exceeded_with_flag_disabled(+ staff_api_client,+ staff_user,+ order_with_lines,+ permission_manage_orders,+ warehouse,+):+ order = order_with_lines+ query = ORDER_FULFILL_QUERY+ order_id = graphene.Node.to_global_id("Order", order.id)+ order_line, order_line2 = order.lines.all()+ order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id)+ order_line2_id = graphene.Node.to_global_id("OrderLine", order_line2.id)+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)++ # set stocks to out of quantity and assert+ Stock.objects.filter(warehouse=warehouse).update(quantity=0)++ # make first stock quantity < 0+ stock = Stock.objects.filter(warehouse=warehouse).first()+ stock.quantity = -99+ stock.save()++ for stock in Stock.objects.filter(warehouse=warehouse):+ assert stock.quantity <= 0++ variables = {+ "order": order_id,+ "input": {+ "notifyCustomer": False,+ "allowStockToBeExceeded": False,+ "lines": [+ {+ "orderLineId": order_line_id,+ "stocks": [{"quantity": 3, "warehouse": warehouse_id}],+ },+ {+ "orderLineId": order_line2_id,+ "stocks": [{"quantity": 2, "warehouse": warehouse_id}],+ },+ ],+ },+ }+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_orders]+ )+ content = get_graphql_content(response)+ data = content["data"]["orderFulfill"]+ assert data["errors"]++ errors = data["errors"]+ assert errors[0]["code"] == "INSUFFICIENT_STOCK"+ assert errors[0]["message"] == "Insufficient product stock: SKU_AA"++ assert errors[1]["code"] == "INSUFFICIENT_STOCK"+ assert errors[1]["message"] == "Insufficient product stock: SKU_B"+++def test_order_fulfill_with_stock_exceeded_with_flag_enabled(+ staff_api_client,+ staff_user,+ order_with_lines,+ permission_manage_orders,+ warehouse,+):+ order = order_with_lines+ query = ORDER_FULFILL_QUERY+ order_id = graphene.Node.to_global_id("Order", order.id)+ order_line, order_line2 = order.lines.all()+ order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id)+ order_line2_id = graphene.Node.to_global_id("OrderLine", order_line2.id)+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)++ # set stocks to out of quantity and assert+ Stock.objects.filter(warehouse=warehouse).update(quantity=0)+ for stock in Stock.objects.filter(warehouse=warehouse):+ assert stock.quantity == 0++ variables = {+ "order": order_id,+ "input": {+ "notifyCustomer": False,+ "allowStockToBeExceeded": True,+ "lines": [+ {+ "orderLineId": order_line_id,+ "stocks": [{"quantity": 3, "warehouse": warehouse_id}],+ },+ {+ "orderLineId": order_line2_id,+ "stocks": [{"quantity": 2, "warehouse": warehouse_id}],+ },+ ],+ },+ }+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_orders]+ )+ content = get_graphql_content(response)+ data = content["data"]["orderFulfill"]+ assert not data["errors"]++ order.refresh_from_db()++ assert order.status == OrderStatus.FULFILLED++ order_lines = order.lines.all()+ assert order_lines[0].quantity_fulfilled == 3+ assert order_lines[0].quantity_unfulfilled == 0++ assert order_lines[1].quantity_fulfilled == 2+ assert order_lines[1].quantity_unfulfilled == 0++ # check if stocks quantity are < 0 after fulfillments+ for stock in Stock.objects.filter(warehouse=warehouse):+ assert stock.quantity < 0++@patch("saleor.graphql.order.mutations.fulfillments.create_fulfillments")def test_order_fulfill_above_available_quantity(mock_create_fulfillments,@@ -233,6 +352,7 @@ def test_order_fulfill_as_app(fulfillment_lines_for_warehouses,ANY,True,+ allow_stock_to_be_exceeded=False,approved=True,)@@ -298,6 +418,7 @@ def test_order_fulfill_many_warehouses(fulfillment_lines_for_warehouses,ANY,True,+ allow_stock_to_be_exceeded=False,approved=True,)@@ -387,6 +508,7 @@ def test_order_fulfill_with_gift_cards(fulfillment_lines_for_warehouses,ANY,True,+ allow_stock_to_be_exceeded=False,approved=True,)@@ -461,7 +583,14 @@ def test_order_fulfill_with_gift_cards_by_app(]}mock_create_fulfillments.assert_called_once_with(- None, app, order, fulfillment_lines_for_warehouses, ANY, True, approved=True+ None,+ app,+ order,+ fulfillment_lines_for_warehouses,+ ANY,+ True,+ allow_stock_to_be_exceeded=False,+ approved=True,)mock_send_notification.assert_not_called@@ -535,7 +664,14 @@ def test_order_fulfill_with_gift_cards_multiple_warehouses(],}mock_create_fulfillments.assert_called_once_with(- None, app, order, fulfillment_lines_for_warehouses, ANY, True, approved=True+ None,+ app,+ order,+ fulfillment_lines_for_warehouses,+ ANY,+ True,+ allow_stock_to_be_exceeded=False,+ approved=True,)mock_send_notification.assert_not_called@@ -585,6 +721,7 @@ def test_order_fulfill_without_notification(fulfillment_lines_for_warehouses,ANY,False,+ allow_stock_to_be_exceeded=False,approved=True,)@@ -649,6 +786,7 @@ def test_order_fulfill_lines_with_empty_quantity(fulfillment_lines_for_warehouses,ANY,True,+ allow_stock_to_be_exceeded=False,approved=True,)@@ -1310,8 +1448,13 @@ def test_create_digital_fulfillment(APPROVE_FULFILLMENT_MUTATION = """- mutation approveFulfillment($id: ID!, $notifyCustomer: Boolean!) {- orderFulfillmentApprove(id: $id, notifyCustomer: $notifyCustomer) {+ mutation approveFulfillment(+ $id: ID!, $notifyCustomer: Boolean!, $allowStockToBeExceeded: Boolean = false+ ) {+ orderFulfillmentApprove(+ id: $id,+ notifyCustomer: $notifyCustomer,+ allowStockToBeExceeded: $allowStockToBeExceeded) {fulfillment {status}@@ -1358,6 +1501,79 @@ def test_fulfillment_approve(assert event.user == staff_api_client.user+@patch("saleor.order.actions.send_fulfillment_confirmation_to_customer", autospec=True)+def test_fulfillment_approve_when_stock_is_exceeded_and_flag_enabled(+ mock_email_fulfillment,+ staff_api_client,+ fulfillment,+ permission_manage_orders,+):+ # make stocks exceeded+ for stock in [line.stock for line in fulfillment.lines.all()]:+ stock.quantity = -99+ stock.save()++ fulfillment.status = FulfillmentStatus.WAITING_FOR_APPROVAL+ fulfillment.save(update_fields=["status"])+ query = APPROVE_FULFILLMENT_MUTATION+ fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id)++ # make response with flag disabled, raised error is expected+ variables = {+ "id": fulfillment_id,+ "notifyCustomer": True,+ "allowStockToBeExceeded": True,+ }+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_orders]+ )+ content = get_graphql_content(response)++ data = content["data"]["orderFulfillmentApprove"]+ assert not data["errors"]+ assert data["fulfillment"]["status"] == FulfillmentStatus.FULFILLED.upper()+ assert data["order"]["status"] == OrderStatus.FULFILLED.upper()+ fulfillment.refresh_from_db()+ assert fulfillment.status == FulfillmentStatus.FULFILLED++ assert mock_email_fulfillment.call_count == 1+ events = fulfillment.order.events.all()+ assert len(events) == 1+ event = events[0]+ assert event.type == OrderEvents.FULFILLMENT_FULFILLED_ITEMS+ assert event.user == staff_api_client.user+++@patch("saleor.order.actions.send_fulfillment_confirmation_to_customer", autospec=True)+def test_fulfillment_approve_when_stock_is_exceeded_and_flag_disabled(+ mock_email_fulfillment,+ staff_api_client,+ fulfillment,+ permission_manage_orders,+):+ # make stocks exceeded+ for stock in [line.stock for line in fulfillment.lines.all()]:+ stock.quantity = -99+ stock.save()++ fulfillment.status = FulfillmentStatus.WAITING_FOR_APPROVAL+ fulfillment.save(update_fields=["status"])+ query = APPROVE_FULFILLMENT_MUTATION+ fulfillment_id = graphene.Node.to_global_id("Fulfillment", fulfillment.id)++ variables = {+ "id": fulfillment_id,+ "notifyCustomer": True,+ "allowStockToBeExceeded": False,+ }+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_orders]+ )+ content = get_graphql_content(response, ignore_errors=True)+ assert content["errors"]+ assert content["errors"][0]["message"] == "Insufficient stock for SKU_AA, SKU_B"++@patch("saleor.order.actions.send_fulfillment_confirmation_to_customer", autospec=True)def test_fulfillment_approve_partial_order_fulfill(mock_email_fulfillment,diff --git a/saleor/graphql/product/tests/test_variant_availability.py b/saleor/graphql/product/tests/test_variant_availability.pyindex 38738e3f44..75c6036e2f 100644--- a/saleor/graphql/product/tests/test_variant_availability.py+++ b/saleor/graphql/product/tests/test_variant_availability.py@@ -7,43 +7,55 @@ from ...tests.utils import get_graphql_contentCOUNTRY_CODE = "US"--def test_variant_quantity_available_without_country_code(- api_client, variant_with_many_stocks, channel_USD-):- query = """+QUERY_QUANTITY_AVAILABLE = """query variantAvailability($id: ID!, $channel: String) {productVariant(id: $id, channel: $channel) {quantityAvailable}}"""+++def test_variant_quantity_available_without_country_code(+ api_client, variant_with_many_stocks, channel_USD+):variables = {"id": graphene.Node.to_global_id("ProductVariant", variant_with_many_stocks.pk),"channel": channel_USD.slug,}- response = api_client.post_graphql(query, variables)+ response = api_client.post_graphql(QUERY_QUANTITY_AVAILABLE, variables)content = get_graphql_content(response)variant_data = content["data"]["productVariant"]assert variant_data["quantityAvailable"] == 7-def test_variant_quantity_available_without_country_code_and_no_channel_shipping_zones(+def test_variant_quantity_available_when_one_stock_is_exceeded(api_client, variant_with_many_stocks, channel_USD):- query = """- query variantAvailability($id: ID!, $channel: String) {- productVariant(id: $id, channel: $channel) {- quantityAvailable- }+ # make first stock exceeded+ stock = variant_with_many_stocks.stocks.first()+ stock.quantity = -99+ stock.save()++ variables = {+ "id": graphene.Node.to_global_id("ProductVariant", variant_with_many_stocks.pk),+ "channel": channel_USD.slug,}- """+ response = api_client.post_graphql(QUERY_QUANTITY_AVAILABLE, variables)+ content = get_graphql_content(response)+ variant_data = content["data"]["productVariant"]+ assert variant_data["quantityAvailable"] == 3+++def test_variant_quantity_available_without_country_code_and_no_channel_shipping_zones(+ api_client, variant_with_many_stocks, channel_USD+):channel_USD.shipping_zones.clear()variables = {"id": graphene.Node.to_global_id("ProductVariant", variant_with_many_stocks.pk),"channel": channel_USD.slug,}- response = api_client.post_graphql(query, variables)+ response = api_client.post_graphql(QUERY_QUANTITY_AVAILABLE, variables)content = get_graphql_content(response)variant_data = content["data"]["productVariant"]assert variant_data["quantityAvailable"] == 0diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex a8b893f0a7..87158e02ea 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -3824,7 +3824,7 @@ type Mutation {orderConfirm(id: ID!): OrderConfirmorderFulfill(input: OrderFulfillInput!, order: ID): OrderFulfillorderFulfillmentCancel(id: ID!, input: FulfillmentCancelInput): FulfillmentCancel- orderFulfillmentApprove(id: ID!, notifyCustomer: Boolean!): FulfillmentApprove+ orderFulfillmentApprove(allowStockToBeExceeded: Boolean = false, id: ID!, notifyCustomer: Boolean!): FulfillmentApproveorderFulfillmentUpdateTracking(id: ID!, input: FulfillmentUpdateTrackingInput!): FulfillmentUpdateTrackingorderFulfillmentRefundProducts(input: OrderRefundProductsInput!, order: ID!): FulfillmentRefundProductsorderFulfillmentReturnProducts(input: OrderReturnProductsInput!, order: ID!): FulfillmentReturnProducts@@ -4336,6 +4336,7 @@ type OrderFulfill {input OrderFulfillInput {lines: [OrderFulfillLineInput!]!notifyCustomer: Boolean+ allowStockToBeExceeded: Boolean = false}input OrderFulfillLineInput {diff --git a/saleor/graphql/warehouse/dataloaders.py b/saleor/graphql/warehouse/dataloaders.pyindex 729f2e7d9e..b8f47d9688 100644--- a/saleor/graphql/warehouse/dataloaders.py+++ b/saleor/graphql/warehouse/dataloaders.py@@ -49,7 +49,7 @@ class AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader(for variant_id, quantity in quantities:quantity_by_variant_and_country[(variant_id, country_code, channel_slug)- ] = quantity+ ] = max(0, quantity)return [quantity_by_variant_and_country[key] for key in keys]@@ -103,7 +103,7 @@ class AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader(int, DefaultDict[int, int]] = defaultdict(lambda: defaultdict(int))for stock in stocks:- quantity = stock.available_quantity+ quantity = max(0, stock.available_quantity)variant_id = stock.product_variant_idwarehouse_id = stock.warehouse_idshipping_zone_ids = warehouse_shipping_zones_map[warehouse_id]diff --git a/saleor/order/actions.py b/saleor/order/actions.pyindex 8272a1377d..5b6a794c3b 100644--- a/saleor/order/actions.py+++ b/saleor/order/actions.py@@ -371,6 +371,7 @@ def approve_fulfillment(app: Optional["App"],manager: "PluginsManager",notify_customer=True,+ allow_stock_to_be_exceeded: bool = False,):fulfillment.status = FulfillmentStatus.FULFILLEDfulfillment.save()@@ -391,7 +392,7 @@ def approve_fulfillment()for f_line in fulfillment.lines.all()]- _decrease_stocks(lines_to_fulfill, manager)+ _decrease_stocks(lines_to_fulfill, manager, allow_stock_to_be_exceeded)order.refresh_from_db()update_order_status(order)@@ -458,10 +459,14 @@ def clean_mark_order_as_paid(order: "Order"):)-def _decrease_stocks(order_lines_info, manager):+def _decrease_stocks(order_lines_info, manager, allow_stock_to_be_exceeded=False):lines_to_decrease_stock = get_order_lines_with_track_inventory(order_lines_info)if lines_to_decrease_stock:- decrease_stock(lines_to_decrease_stock, manager)+ decrease_stock(+ lines_to_decrease_stock,+ manager,+ allow_stock_to_be_exceeded=allow_stock_to_be_exceeded,+ )def _increase_order_line_quantity(order_lines_info):@@ -478,9 +483,10 @@ def _increase_order_line_quantity(order_lines_info):def fulfill_order_lines(order_lines_info: Iterable["OrderLineData"],manager: "PluginsManager",+ allow_stock_to_be_exceeded: bool = False,):"""Fulfill order line with given quantity."""- _decrease_stocks(order_lines_info, manager)+ _decrease_stocks(order_lines_info, manager, allow_stock_to_be_exceeded)_increase_order_line_quantity(order_lines_info)@@ -538,6 +544,7 @@ def _create_fulfillment_lines(channel_slug: str,manager: "PluginsManager",decrease_stock: bool = True,+ allow_stock_to_be_exceeded: bool = False,) -> List[FulfillmentLine]:"""Modify stocks and allocations. Return list of unsaved FulfillmentLines.@@ -556,6 +563,8 @@ def _create_fulfillment_lines(channel_slug (str): Channel for which fulfillment lines should be created.manager (PluginsManager): Plugin manager from given contextdecrease_stock (Bool): Stocks will get decreased if this is True.+ allow_stock_to_be_exceeded (bool): If `True` then stock quantity could exceed.+ Default value is set to `False`.Return:List[FulfillmentLine]: Unsaved fulfillmet lines created for this fulfillment@@ -618,7 +627,7 @@ def _create_fulfillment_lines(if lines_info:if decrease_stock:- _decrease_stocks(lines_info, manager)+ _decrease_stocks(lines_info, manager, allow_stock_to_be_exceeded)_increase_order_line_quantity(lines_info)return fulfillment_lines@@ -633,6 +642,7 @@ def create_fulfillments(manager: "PluginsManager",notify_customer: bool = True,approved: bool = True,+ allow_stock_to_be_exceeded: bool = False,) -> List[Fulfillment]:"""Fulfill order.@@ -659,6 +669,8 @@ def create_fulfillments(fulfillments to customer.approved (Boolean): fulfillments will have status fulfilled if it's True,otherwise waiting_for_approval.+ allow_stock_to_be_exceeded (bool): If `True` then stock quantity could exceed.+ Default value is set to `False`.Return:List[Fulfillment]: Fulfillmet with lines created for this order@@ -687,6 +699,7 @@ def create_fulfillments(order.channel.slug,manager,decrease_stock=approved,+ allow_stock_to_be_exceeded=allow_stock_to_be_exceeded,))diff --git a/saleor/order/tests/test_fulfullments_actions.py b/saleor/order/tests/test_fulfillments_actions.pysimilarity index 100%rename from saleor/order/tests/test_fulfullments_actions.pyrename to saleor/order/tests/test_fulfillments_actions.pydiff --git a/saleor/warehouse/management.py b/saleor/warehouse/management.pyindex dcb4d9d9db..c60895cf67 100644--- a/saleor/warehouse/management.py+++ b/saleor/warehouse/management.py@@ -307,7 +307,10 @@ def decrease_allocations(lines_info: Iterable["OrderLineData"], manager):@traced_atomic_transaction()def decrease_stock(- order_lines_info: Iterable["OrderLineData"], manager, update_stocks=True+ order_lines_info: Iterable["OrderLineData"],+ manager,+ update_stocks=True,+ allow_stock_to_be_exceeded: bool = False,):"""Decrease stocks quantities for given `order_lines` in given warehouses.@@ -318,6 +321,7 @@ def decrease_stock(function decrease it by given value.If update_stocks is False, allocations will decrease but stocks quantitieswill stay unmodified (case of unconfirmed order editing).+ If allow_stock_to_be_exceeded flag is True then quantity could be < 0."""variants = [line_info.variant for line_info in order_lines_info]warehouse_pks = [line_info.warehouse_pk for line_info in order_lines_info]@@ -361,6 +365,7 @@ def decrease_stock(order_lines_info,variant_and_warehouse_to_stock,quantity_allocation_for_stocks,+ allow_stock_to_be_exceeded,)stock_ids = (s.id for s in stocks)@@ -377,6 +382,7 @@ def _decrease_stocks_quantity(order_lines_info: Iterable["OrderLineData"],variant_and_warehouse_to_stock: Dict[int, Dict[str, Stock]],quantity_allocation_for_stocks: Dict[int, int],+ allow_stock_to_be_exceeded: bool = False,):insufficient_stocks: List[InsufficientStockData] = []stocks_to_update = []@@ -396,7 +402,8 @@ def _decrease_stocks_quantity(quantity_allocated = quantity_allocation_for_stocks.get(stock.pk, 0)- if stock.quantity - quantity_allocated < line_info.quantity:+ is_stock_exceeded = stock.quantity - quantity_allocated < line_info.quantity+ if is_stock_exceeded and not allow_stock_to_be_exceeded:insufficient_stocks.append(InsufficientStockData(variant=variant, # type: ignorediff --git a/saleor/warehouse/migrations/0015_alter_stock_quantity.py b/saleor/warehouse/migrations/0015_alter_stock_quantity.pynew file mode 100644index 0000000000..1943d386d9--- /dev/null+++ b/saleor/warehouse/migrations/0015_alter_stock_quantity.py@@ -0,0 +1,18 @@+# Generated by Django 3.2.7 on 2021-09-16 10:47++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("warehouse", "0014_remove_warehouse_company_name"),+ ]++ operations = [+ migrations.AlterField(+ model_name="stock",+ name="quantity",+ field=models.IntegerField(default=0),+ ),+ ]diff --git a/saleor/warehouse/migrations/0016_merge_20210921_1036.py b/saleor/warehouse/migrations/0016_merge_20210921_1036.pynew file mode 100644index 0000000000..a4543cabb4--- /dev/null+++ b/saleor/warehouse/migrations/0016_merge_20210921_1036.py@@ -0,0 +1,13 @@+# Generated by Django 3.2.7 on 2021-09-21 10:36++from django.db import migrations+++class Migration(migrations.Migration):++ dependencies = [+ ("warehouse", "0015_alter_stock_quantity"),+ ("warehouse", "0015_auto_20210713_0904"),+ ]++ operations = []diff --git a/saleor/warehouse/models.py b/saleor/warehouse/models.pyindex c07fbbcd09..40fa7d9d6e 100644--- a/saleor/warehouse/models.py+++ b/saleor/warehouse/models.py@@ -199,7 +199,7 @@ class Stock(models.Model):product_variant = models.ForeignKey(ProductVariant, null=False, on_delete=models.CASCADE, related_name="stocks")- quantity = models.PositiveIntegerField(default=0)+ quantity = models.IntegerField(default=0)objects = models.Manager.from_queryset(StockQuerySet)()