Skip to content

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

Multiple copies of a single variant in the same Checkout/Order (#10095)

SzymJ6c0a67da7b5c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 72b437457e..69c1b515dd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -38,6 +38,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Add synchronous tax calculation via webhooks - #9526 by @fowczarek, @mateuszgrzyb, @stnatic
- Add option to calculate taxes via webhooks more info in docs
<!-- We should put docs link here before release -->
+- Add `forceNewLine` flag to lines input in `CheckoutLinesAdd`, `CheckoutCreate`, `DraftOrderCreate`, `OrderCreate`, `OrderLinesCreate` mutations to support same variant in multiple lines - #10095 by @SzymJ
### GraphQL API
- Add synchronous tax calculation via webhooks - #9526 by @fowczarek, @mateuszgrzyb, @stnatic
diff --git a/saleor/checkout/fetch.py b/saleor/checkout/fetch.py
index 249003d6ff..224d940df8 100644
--- a/saleor/checkout/fetch.py
+++ b/saleor/checkout/fetch.py
@@ -211,7 +211,9 @@ def get_delivery_method_info(
def fetch_checkout_lines(
- checkout: "Checkout", prefetch_variant_attributes=False
+ checkout: "Checkout",
+ prefetch_variant_attributes=False,
+ skip_lines_with_unavailable_variants=True,
) -> Tuple[Iterable[CheckoutLineInfo], Iterable[int]]:
"""Fetch checkout lines as CheckoutLineInfo objects."""
from .utils import get_voucher_for_checkout
@@ -250,6 +252,17 @@ def fetch_checkout_lines(
checkout, product, variant_channel_listing, product_channel_listing_mapping
):
unavailable_variant_pks.append(variant.pk)
+ if not skip_lines_with_unavailable_variants:
+ lines_info.append(
+ CheckoutLineInfo(
+ line=line,
+ variant=variant,
+ channel_listing=variant_channel_listing,
+ product=product,
+ product_type=product_type,
+ collections=collections,
+ )
+ )
continue
lines_info.append(
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index 701e68cbc0..f88ac12b6f 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -127,6 +127,7 @@ def add_variant_to_checkout(
price_override: Optional["Decimal"] = None,
replace: bool = False,
check_quantity: bool = True,
+ force_new_line: bool = False,
):
"""Add a product variant to checkout.
@@ -153,16 +154,22 @@ def add_variant_to_checkout(
check_quantity=check_quantity,
)
+ if force_new_line:
+ checkout.lines.create(
+ variant=variant,
+ quantity=quantity,
+ price_override=price_override,
+ )
+ return checkout
+
if line is None:
line = checkout.lines.filter(variant=variant).first()
if new_quantity == 0:
if line is not None:
line.delete()
- line = None
elif line is None:
- line = checkout.lines.create( # type: ignore
- checkout=checkout,
+ checkout.lines.create( # type: ignore
variant=variant,
quantity=new_quantity,
currency=checkout.currency,
@@ -199,18 +206,23 @@ def add_variants_to_checkout(
country_code = checkout.get_country()
checkout_lines = checkout.lines.select_related("variant")
- variant_ids_in_lines = {line.variant_id: line for line in checkout_lines}
+
+ lines_by_id = {str(line.pk): line for line in checkout_lines}
+ variants_map = {str(variant.pk): variant for variant in variants}
+
to_create: List[CheckoutLine] = []
to_update: List[CheckoutLine] = []
to_delete: List[CheckoutLine] = []
- for variant, line_data in zip(variants, checkout_lines_data):
- _append_line_to_update(
- to_update, to_delete, variant, line_data, replace, variant_ids_in_lines
- )
- _append_line_to_delete(to_delete, variant, line_data, variant_ids_in_lines)
- _append_line_to_create(
- to_create, checkout, variant, line_data, variant_ids_in_lines
- )
+
+ for line_data in checkout_lines_data:
+ line = lines_by_id.get(line_data.line_id) if line_data.line_id else None
+ if line:
+ _append_line_to_update(to_update, to_delete, line_data, replace, line)
+ _append_line_to_delete(to_delete, line_data, line)
+ else:
+ variant = variants_map[line_data.variant_id]
+ _append_line_to_create(to_create, checkout, variant, line_data, line)
+
if to_delete:
CheckoutLine.objects.filter(pk__in=[line.pk for line in to_delete]).delete()
if to_update:
@@ -219,6 +231,7 @@ def add_variants_to_checkout(
CheckoutLine.objects.bulk_create(to_create)
to_reserve = to_create + to_update
+
if reservation_length and to_reserve:
updated_lines_ids = [line.pk for line in to_reserve + to_delete]
for line in checkout_lines:
@@ -238,12 +251,12 @@ def add_variants_to_checkout(
return checkout
-def _append_line_to_update(
- to_update, to_delete, variant, line_data, replace, variant_ids_in_lines
-):
- if variant.pk not in variant_ids_in_lines:
- return
- line = variant_ids_in_lines[variant.pk]
+def _get_line_if_exist(line_data, lines_by_ids):
+ if line_data.line_id and line_data.line_id in lines_by_ids:
+ return lines_by_ids[line_data.line_id]
+
+
+def _append_line_to_update(to_update, to_delete, line_data, replace, line):
if line_data.quantity_to_update:
quantity = line_data.quantity
if quantity > 0:
@@ -258,20 +271,15 @@ def _append_line_to_update(
to_update.append(line)
-def _append_line_to_delete(to_delete, variant, line_data, variant_ids_in_lines):
- if variant.pk not in variant_ids_in_lines:
- return
- line = variant_ids_in_lines[variant.pk]
+def _append_line_to_delete(to_delete, line_data, line):
quantity = line_data.quantity
if line_data.quantity_to_update:
if quantity <= 0:
to_delete.append(line)
-def _append_line_to_create(
- to_create, checkout, variant, line_data, variant_ids_in_lines
-):
- if variant.pk not in variant_ids_in_lines:
+def _append_line_to_create(to_create, checkout, variant, line_data, line):
+ if line is None:
if line_data.quantity > 0:
to_create.append(
CheckoutLine(
diff --git a/saleor/core/management/commands/populatedb.py b/saleor/core/management/commands/populatedb.py
index 887694aa1e..9ba9d42987 100644
--- a/saleor/core/management/commands/populatedb.py
+++ b/saleor/core/management/commands/populatedb.py
@@ -12,6 +12,7 @@ from ...utils.random_data import (
create_channels,
create_checkout_with_custom_prices,
create_checkout_with_preorders,
+ create_checkout_with_same_variant_in_multiple_lines,
create_gift_cards,
create_menus,
create_orders,
@@ -114,6 +115,8 @@ class Command(BaseCommand):
self.stdout.write(msg)
for msg in create_checkout_with_custom_prices():
self.stdout.write(msg)
+ for msg in create_checkout_with_same_variant_in_multiple_lines():
+ self.stdout.write(msg)
if options["createsuperuser"]:
credentials = {
diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.py
index e16d5eda95..ee4f93de69 100644
--- a/saleor/core/utils/random_data.py
+++ b/saleor/core/utils/random_data.py
@@ -1561,11 +1561,16 @@ def get_image(image_dir, image_name):
return File(open(img_path, "rb"), name=image_name)
-def create_checkout_with_preorders():
+def prepare_checkout_info():
channel = Channel.objects.get(slug=settings.DEFAULT_CHANNEL_SLUG)
checkout = Checkout.objects.create(currency=channel.currency_code, channel=channel)
checkout.set_country(channel.default_country, commit=True)
checkout_info = fetch_checkout_info(checkout, [], [], get_plugins_manager())
+ return checkout_info
+
+
+def create_checkout_with_preorders():
+ checkout_info = prepare_checkout_info()
for product_variant in ProductVariant.objects.all()[:2]:
product_variant.is_preorder = True
product_variant.preorder_global_threshold = 10
@@ -1579,19 +1584,31 @@ def create_checkout_with_preorders():
]
)
add_variant_to_checkout(checkout_info, product_variant, 2)
- yield f"Created checkout with two preorders. Checkout token: {checkout.token}"
+ yield (
+ "Created checkout with two preorders. Checkout token: "
+ f"{checkout_info.checkout.token}"
+ )
def create_checkout_with_custom_prices():
- channel = Channel.objects.get(slug=settings.DEFAULT_CHANNEL_SLUG)
- checkout = Checkout.objects.create(currency=channel.currency_code, channel=channel)
- checkout.set_country(channel.default_country, commit=True)
- checkout_info = fetch_checkout_info(checkout, [], [], get_plugins_manager())
+ checkout_info = prepare_checkout_info()
for product_variant in ProductVariant.objects.all()[:2]:
add_variant_to_checkout(
checkout_info, product_variant, 2, price_override=Decimal("20.0")
)
yield (
"Created checkout with two lines and custom prices. "
- f"Checkout token: {checkout.token}."
+ f"Checkout token: {checkout_info.checkout.token}."
+ )
+
+
+def create_checkout_with_same_variant_in_multiple_lines():
+ checkout_info = prepare_checkout_info()
+ for product_variant in ProductVariant.objects.all()[:2]:
+ add_variant_to_checkout(checkout_info, product_variant, 2)
+ add_variant_to_checkout(checkout_info, product_variant, 2, force_new_line=True)
+
+ yield (
+ "Created checkout with four lines and same variant in multiple lines "
+ f"Checkout token: {checkout_info.checkout.token}."
)
diff --git a/saleor/graphql/checkout/mutations/checkout_create.py b/saleor/graphql/checkout/mutations/checkout_create.py
index 1872595dda..1db8ba9bb8 100644
--- a/saleor/graphql/checkout/mutations/checkout_create.py
+++ b/saleor/graphql/checkout/mutations/checkout_create.py
@@ -15,6 +15,7 @@ from ...channel.utils import clean_channel
from ...core.descriptions import (
ADDED_IN_31,
ADDED_IN_35,
+ ADDED_IN_36,
DEPRECATED_IN_3X_FIELD,
PREVIEW_FEATURE,
)
@@ -28,7 +29,8 @@ from ..types import Checkout
from .utils import (
check_lines_quantity,
check_permissions_for_custom_prices,
- group_quantity_and_custom_prices_by_variants,
+ get_variants_and_total_quantities,
+ group_lines_input_on_add,
validate_variants_are_published,
validate_variants_available_for_purchase,
)
@@ -94,6 +96,14 @@ class CheckoutLineInput(graphene.InputObjectType):
+ PREVIEW_FEATURE
),
)
+ force_new_line = graphene.Boolean(
+ required=False,
+ default_value=False,
+ description=(
+ "Flag that allow force splitting the same variant into multiple lines "
+ "by skipping the matching logic. " + ADDED_IN_36 + PREVIEW_FEATURE
+ ),
+ )
class CheckoutCreateInput(graphene.InputObjectType):
@@ -169,7 +179,7 @@ class CheckoutCreate(ModelMutation, I18nMixin):
),
)
- checkout_lines_data = group_quantity_and_custom_prices_by_variants(lines)
+ checkout_lines_data = group_lines_input_on_add(lines)
variant_db_ids = {variant.id for variant in variants}
validate_variants_available_for_purchase(variant_db_ids, channel.id)
@@ -177,7 +187,11 @@ class CheckoutCreate(ModelMutation, I18nMixin):
variant_db_ids, channel.id, CheckoutErrorCode.UNAVAILABLE_VARIANT_IN_CHANNEL
)
validate_variants_are_published(variant_db_ids, channel.id)
- quantities = [line_data.quantity for line_data in checkout_lines_data]
+
+ variants, quantities = get_variants_and_total_quantities(
+ variants, checkout_lines_data
+ )
+
check_lines_quantity(
variants,
quantities,
diff --git a/saleor/graphql/checkout/mutations/checkout_lines_add.py b/saleor/graphql/checkout/mutations/checkout_lines_add.py
index 46c6273e43..f34a17f6e8 100644
--- a/saleor/graphql/checkout/mutations/checkout_lines_add.py
+++ b/saleor/graphql/checkout/mutations/checkout_lines_add.py
@@ -1,3 +1,5 @@
+from typing import Dict, List
+
import graphene
from ....checkout.error_codes import CheckoutErrorCode
@@ -20,7 +22,8 @@ from .utils import (
check_lines_quantity,
check_permissions_for_custom_prices,
get_checkout,
- group_quantity_and_custom_prices_by_variants,
+ get_variants_and_total_quantities,
+ group_lines_input_on_add,
update_checkout_shipping_method_if_invalid,
validate_variants_are_published,
validate_variants_available_for_purchase,
@@ -72,7 +75,9 @@ class CheckoutLinesAdd(BaseMutation):
channel_slug,
lines=None,
):
- quantities = [line_data.quantity for line_data in checkout_lines_data]
+ variants, quantities = get_variants_and_total_quantities(
+ variants, checkout_lines_data
+ )
check_lines_quantity(
variants,
quantities,
@@ -170,23 +175,25 @@ class CheckoutLinesAdd(BaseMutation):
discounts = info.context.discounts
manager = info.context.plugins
- variant_ids = [line.get("variant_id") for line in lines]
- variants = cls.get_nodes_or_error(variant_ids, "variant_id", ProductVariant)
- checkout_lines_data = group_quantity_and_custom_prices_by_variants(lines)
+ variants = cls._get_variants_from_lines_input(lines)
shipping_channel_listings = checkout.channel.shipping_method_listings.all()
checkout_info = fetch_checkout_info(
checkout, [], discounts, manager, shipping_channel_listings
)
- lines, _ = fetch_checkout_lines(checkout)
+ existing_lines_info, _ = fetch_checkout_lines(
+ checkout, skip_lines_with_unavailable_variants=False
+ )
+ input_lines_data = cls._get_grouped_lines_data(lines, existing_lines_info)
+
lines = cls.clean_input(
info,
checkout,
variants,
- checkout_lines_data,
+ input_lines_data,
checkout_info,
- lines,
+ existing_lines_info,
manager,
discounts,
replace,
@@ -196,3 +203,16 @@ class CheckoutLinesAdd(BaseMutation):
manager.checkout_updated(checkout)
return CheckoutLinesAdd(checkout=checkout)
+
+ @classmethod
+ def _get_variants_from_lines_input(cls, lines: List[Dict]) -> List[ProductVariant]:
+ """Return list of ProductVariant objects.
+
+ Uses variants ids provided in CheckoutLineInput to fetch ProductVariant objects.
+ """
+ variant_ids = [line.get("variant_id") for line in lines]
+ return cls.get_nodes_or_error(variant_ids, "variant_id", ProductVariant)
+
+ @classmethod
+ def _get_grouped_lines_data(cls, lines, existing_lines_info):
+ return group_lines_input_on_add(lines, existing_lines_info)
diff --git a/saleor/graphql/checkout/mutations/checkout_lines_update.py b/saleor/graphql/checkout/mutations/checkout_lines_update.py
index f9d65da2d8..5de36c3c69 100644
--- a/saleor/graphql/checkout/mutations/checkout_lines_update.py
+++ b/saleor/graphql/checkout/mutations/checkout_lines_update.py
@@ -1,18 +1,38 @@
+from typing import Dict, List
+
import graphene
from django.forms import ValidationError
from ....checkout.error_codes import CheckoutErrorCode
from ....warehouse.reservations import is_reservation_enabled
-from ...core.descriptions import ADDED_IN_34, DEPRECATED_IN_3X_INPUT
-from ...core.scalars import UUID
+from ...checkout.types import CheckoutLine
+from ...core.descriptions import (
+ ADDED_IN_31,
+ ADDED_IN_34,
+ ADDED_IN_36,
+ DEPRECATED_IN_3X_INPUT,
+ PREVIEW_FEATURE,
+)
+from ...core.scalars import UUID, PositiveDecimal
from ...core.types import CheckoutError, NonNullList
+from ...core.validators import validate_one_of_args_is_in_mutation
+from ...product.types import ProductVariant
from ..types import Checkout
-from .checkout_create import CheckoutLineInput
from .checkout_lines_add import CheckoutLinesAdd
-from .utils import check_lines_quantity
+from .utils import (
+ check_lines_quantity,
+ get_variants_and_total_quantities,
+ group_lines_input_data_on_update,
+)
-class CheckoutLineUpdateInput(CheckoutLineInput):
+class CheckoutLineUpdateInput(graphene.InputObjectType):
+ variant_id = graphene.ID(
+ required=False,
+ description=(
+ f"ID of the product variant. {DEPRECATED_IN_3X_INPUT} Use `lineId` instead."
+ ),
+ )
quantity = graphene.Int(
required=False,
description=(
@@ -20,6 +40,20 @@ class CheckoutLineUpdateInput(CheckoutLineInput):
"Optional for apps, required for any other users."
),
)
+ price = PositiveDecimal(
+ required=False,
+ description=(
+ "Custom price of the item. Can be set only by apps "
+ "with `HANDLE_CHECKOUTS` permission. When the line with the same variant "
+ "will be provided multiple times, the last price will be used."
+ + ADDED_IN_31
+ + PREVIEW_FEATURE
+ ),
+ )
+ line_id = graphene.ID(
+ description="ID of the line." + ADDED_IN_36,
+ required=False,
+ )
class CheckoutLinesUpdate(CheckoutLinesAdd):
@@ -64,15 +98,12 @@ class CheckoutLinesUpdate(CheckoutLinesAdd):
channel_slug,
lines=None,
):
- variants_to_validate = []
- quantities = []
- for variant, line_data in zip(variants, checkout_lines_data):
- if line_data.quantity_to_update:
- variants_to_validate.append(variant)
- quantities.append(line_data.quantity)
+ variants, quantities = get_variants_and_total_quantities(
+ variants, checkout_lines_data, quantity_to_update_check=True
+ )
check_lines_quantity(
- variants_to_validate,
+ variants,
quantities,
country,
channel_slug,
@@ -126,7 +157,49 @@ class CheckoutLinesUpdate(CheckoutLinesAdd):
)
@classmethod
- def perform_mutation(cls, root, info, lines, checkout_id=None, token=None, id=None):
+ def perform_mutation(
+ cls, root, info, lines, checkout_id=None, token=None, id=None, replace=True
+ ):
+ for line in lines:
+ validate_one_of_args_is_in_mutation(
+ CheckoutErrorCode,
+ "line_id",
+ line.get("line_id"),
+ "variant_id",
+ line.get("variant_id"),
+ )
+
return super().perform_mutation(
root, info, lines, checkout_id, token, id, replace=True
)
+
+ @classmethod
+ def _get_variants_from_lines_input(cls, lines: List[Dict]) -> List[ProductVariant]:
+ """Return list of ProductVariant objects.
+
+ Uses variants ids or lines ids provided in CheckoutLineUpdateInput to
+ fetch ProductVariant objects.
+ """
+
+ variant_ids = set()
+
+ variant_ids.update(
+ {line.get("variant_id") for line in lines if line.get("variant_id")}
+ )
+
+ line_ids = [line.get("line_id") for line in lines if line.get("line_id")]
+
+ if line_ids:
+ lines_instances = cls.get_nodes_or_error(line_ids, "line_id", CheckoutLine)
+ variant_ids.update(
+ {
+ graphene.Node.to_global_id("ProductVariant", line.variant_id)
+ for line in lines_instances
+ }
+ )
+
+ return cls.get_nodes_or_error(variant_ids, "variant_id", ProductVariant)
+
+ @classmethod
+ def _get_grouped_lines_data(cls, lines, existing_lines_info):
+ return group_lines_input_data_on_update(lines, existing_lines_info)
diff --git a/saleor/graphql/checkout/mutations/utils.py b/saleor/graphql/checkout/mutations/utils.py
index 0009655572..9630bdf9e1 100644
--- a/saleor/graphql/checkout/mutations/utils.py
+++ b/saleor/graphql/checkout/mutations/utils.py
@@ -38,6 +38,8 @@ ERROR_DOES_NOT_SHIP = "This checkout doesn't need shipping"
@dataclass
class CheckoutLineData:
+ variant_id: Optional[str] = None
+ line_id: Optional[str] = None
quantity: int = 0
quantity_to_update: bool = False
custom_price: Optional[Decimal] = None
@@ -96,6 +98,26 @@ def update_checkout_shipping_method_if_invalid(
clear_delivery_method(checkout_info)
+def get_variants_and_total_quantities(
+ variants, lines_data, quantity_to_update_check=False
+):
+ variants_total_quantity_map = defaultdict(int)
+ mapped_data = defaultdict(int)
+
+ if quantity_to_update_check:
+ lines_data = filter(lambda d: d.quantity_to_update, lines_data)
+
+ for data in lines_data:
+ mapped_data[data.variant_id] += data.quantity
+
+ for variant in variants:
+ quantity = mapped_data.get(str(variant.id), None)
+ if quantity is not None:
+ variants_total_quantity_map[variant] += quantity
+
+ return variants_total_quantity_map.keys(), variants_total_quantity_map.values()
+
+
def check_lines_quantity(
variants,
quantities,
@@ -273,24 +295,105 @@ def get_checkout(
return checkout
-def group_quantity_and_custom_prices_by_variants(
- lines: List[Dict[str, Any]]
+def group_lines_input_on_add(
+ lines: List[Dict[str, Any]], existing_lines_info=None
) -> List[CheckoutLineData]:
- variant_checkout_line_data_map: Dict[str, CheckoutLineData] = defaultdict(
- CheckoutLineData
- )
+ """Return list od CheckoutLineData objects.
+
+ Lines data provided in CheckoutLineInput will be grouped depending on
+ provided parameters.
+ """
+ grouped_checkout_lines_data: List[CheckoutLineData] = []
+ checkout_lines_data_map: Dict[str, CheckoutLineData] = defaultdict(CheckoutLineData)
+
+ for line in lines:
+ variant_id = cast(str, line.get("variant_id"))
+ force_new_line = line.get("force_new_line")
+ _, variant_db_id = graphene.Node.from_global_id(variant_id)
+
+ if force_new_line:
+ line_data = CheckoutLineData(variant_id=variant_db_id)
+ grouped_checkout_lines_data.append(line_data)
+ else:
+ _, variant_db_id = graphene.Node.from_global_id(variant_id)
+
+ try:
+ line_db_id = find_line_id_when_variant_parameter_used(
+ variant_db_id, existing_lines_info
+ )
+
+ if not line_db_id:
+ line_data = checkout_lines_data_map[variant_db_id]
+ line_data.variant_id = variant_db_id
+ else:
+ line_data = checkout_lines_data_map[line_db_id]
+ line_data.line_id = line_db_id
+ line_data.variant_id = find_variant_id_when_line_parameter_used(
+ line_db_id, existing_lines_info
+ )
+
+ # when variant already exist in multiple lines then create a new line
+ except ValidationError:
+ line_data = CheckoutLineData(variant_id=variant_db_id)
+ grouped_checkout_lines_data.append(line_data)
+
+ if (quantity := line.get("quantity")) is not None:
+ line_data.quantity += quantity
+ line_data.quantity_to_update = True
+
+ if "price" in line:
+ line_data.custom_price = line["price"]
+ line_data.custom_price_to_update = True
+
+ grouped_checkout_lines_data += list(checkout_lines_data_map.values())
+ return grouped_checkout_lines_data
+
+
+def group_lines_input_data_on_update(
+ lines: List[Dict[str, Any]], existing_lines_info=None
+) -> List[CheckoutLineData]:
+ """Return list od CheckoutLineData objects.
+
+ This function is used in CheckoutLinesUpdate mutation.
+ Lines data provided in CheckoutLineUpdateInput will be grouped depending on
+ provided parameters.
+ """
+ grouped_checkout_lines_data: List[CheckoutLineData] = []
+ checkout_lines_data_map: Dict[str, CheckoutLineData] = defaultdict(CheckoutLineData)
for line in lines:
variant_id = cast(str, line.get("variant_id"))
- line_data = variant_checkout_line_data_map[variant_id]
+ line_id = cast(str, line.get("line_id"))
+
+ if line_id:
+ _, line_db_id = graphene.Node.from_global_id(line_id)
+
+ if variant_id:
+ _, variant_db_id = graphene.Node.from_global_id(variant_id)
+ line_db_id = find_line_id_when_variant_parameter_used(
+ variant_db_id, existing_lines_info
+ )
+
+ if not line_db_id:
+ line_data = checkout_lines_data_map[variant_db_id]
+ line_data.variant_id = variant_db_id
+ else:
+ line_data = checkout_lines_data_map[line_db_id]
+ line_data.line_id = line_db_id
+ line_data.variant_id = find_variant_id_when_line_parameter_used(
+ line_db_id, existing_lines_info
+ )
+
if (quantity := line.get("quantity")) is not None:
line_data.quantity += quantity
line_data.quantity_to_update = True
+
if "price" in line:
line_data.custom_price = line["price"]
line_data.custom_price_to_update = True
- return list(variant_checkout_line_data_map.values())
+ grouped_checkout_lines_data += list(checkout_lines_data_map.values())
+ return grouped_checkout_lines_data
def check_permissions_for_custom_prices(app, lines):
@@ -303,3 +406,49 @@ def check_permissions_for_custom_prices(app, lines):
not app or not app.has_perm(CheckoutPermissions.HANDLE_CHECKOUTS)
):
raise PermissionDenied(permissions=[CheckoutPermissions.HANDLE_CHECKOUTS])
+
+
+def find_line_id_when_variant_parameter_used(
+ variant_db_id: str, lines_info: List[CheckoutLineInfo]
+):
+ """Return line id when variantId parameter was used.
+
+ If variant exists in multiple lines error will be returned.
+ """
+ if not lines_info:
+ return
+
+ line_info = list(filter(lambda x: (x.variant.pk == int(variant_db_id)), lines_info))
+
+ if not line_info:
+ return
+
+ # if same variant occur in multiple lines `lineId` parameter have to be used
+ if len(line_info) > 1:
+ message = (
+ "Variant occurs in multiple lines. Use `lineId` instead " "of `variantId`."
+ )
+ variant_global_id = graphene.Node.to_global_id("ProductVariant", variant_db_id)
+
+ raise ValidationError(
+ {
+ "variantId": ValidationError(
+ message=message,
+ code=CheckoutErrorCode.INVALID.value,
+ params={"variants": [variant_global_id]},
+ )
+ }
+ )
+
+ return str(line_info[0].line.id)
+
+
+def find_variant_id_when_line_parameter_used(
+ line_db_id: str, lines_info: List[CheckoutLineInfo]
+):
+ """Return variant id when lineId parameter was used."""
+ if not lines_info:
+ return
+
+ line_info = list(filter(lambda x: (str(x.line.pk) == line_db_id), lines_info))
+ return str(line_info[0].line.variant_id)
diff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
index a41c39d117..696b1231f8 100644
--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
@@ -596,6 +596,7 @@ def test_update_checkout_lines(
},
],
}
+
response = get_graphql_content(
api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)
)
@@ -644,13 +645,14 @@ def test_update_checkout_lines_with_reservations(
variants,
[
CheckoutLineData(
+ variant_id=str(variant.pk),
quantity=2,
quantity_to_update=True,
custom_price=None,
custom_price_to_update=False,
)
- ]
- * 10,
+ for variant in variants
+ ],
channel_USD.slug,
replace_reservations=True,
reservation_length=5,
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_create.py b/saleor/graphql/checkout/tests/mutations/test_checkout_create.py
index 6beca54709..072ef3bd4d 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_create.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_create.py
@@ -616,6 +616,50 @@ def test_checkout_create_with_custom_price_duplicated_items(
assert checkout_line.price_override == price_2
+def test_checkout_create_with_force_new_line(
+ app_api_client,
+ stock,
+ graphql_address_data,
+ channel_USD,
+ permission_handle_checkouts,
+):
+ variant = stock.product_variant
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ test_email = "[email protected]"
+ shipping_address = graphql_address_data
+
+ variables = {
+ "checkoutInput": {
+ "channel": channel_USD.slug,
+ "lines": [
+ {"quantity": 1, "variantId": variant_id},
+ {"quantity": 1, "variantId": variant_id, "forceNewLine": True},
+ ],
+ "email": test_email,
+ "shippingAddress": shipping_address,
+ }
+ }
+ assert not Checkout.objects.exists()
+ response = app_api_client.post_graphql(
+ MUTATION_CHECKOUT_CREATE,
+ variables,
+ permissions=[permission_handle_checkouts],
+ check_no_permissions=False,
+ )
+ content = get_graphql_content(response)["data"]["checkoutCreate"]
+
+ new_checkout = Checkout.objects.first()
+ new_checkout_lines = new_checkout.lines.all()
+ assert new_checkout is not None
+ checkout_data = content["checkout"]
+ assert checkout_data["token"] == str(new_checkout.token)
+ assert len(new_checkout_lines) == 2
+
+ for line in new_checkout_lines:
+ assert line.variant == variant
+ assert line.quantity == 1
+
+
def test_checkout_create_with_custom_price_by_app_no_perm(
app_api_client, stock, graphql_address_data, channel_USD
):
@@ -1350,6 +1394,48 @@ def test_checkout_create_check_lines_quantity_when_limit_per_variant_is_set_rais
assert data["errors"][0]["field"] == "quantity"
[email protected]("is_preorder", [True, False])
+def test_checkout_create_check_lines_quantity_limit_when_variant_in_multiple_lines(
+ user_api_client, stock, graphql_address_data, channel_USD, is_preorder
+):
+ limit_per_customer = 5
+ variant = stock.product_variant
+ variant.quantity_limit_per_customer = limit_per_customer
+ variant.is_preorder = is_preorder
+ variant.preorder_end_date = timezone.now() + datetime.timedelta(days=1)
+ variant.save(
+ update_fields=[
+ "quantity_limit_per_customer",
+ "is_preorder",
+ "preorder_end_date",
+ ]
+ )
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ shipping_address = graphql_address_data
+ test_email = "[email protected]"
+ variables = {
+ "checkoutInput": {
+ "lines": [
+ {"quantity": 4, "variantId": variant_id},
+ {"quantity": 3, "variantId": variant_id, "forceNewLine": True},
+ ],
+ "email": test_email,
+ "shippingAddress": shipping_address,
+ "channel": channel_USD.slug,
+ }
+ }
+ 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"] == (
+ f"Cannot add more than {limit_per_customer} times this item: {variant}."
+ )
+ assert data["errors"][0]["field"] == "quantity"
+
+
@pytest.mark.parametrize("is_preorder", [True, False])
def test_checkout_create_check_lines_quantity_respects_site_settings(
user_api_client,
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py
index 34a984aaaf..59f0aad08f 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py
@@ -243,6 +243,83 @@ def test_checkout_lines_add_existing_variant(user_api_client, checkout_with_item
assert checkout.last_change != previous_last_change
+def test_checkout_lines_add_with_force_new_line(
+ app_api_client, checkout, stock, permission_handle_checkouts
+):
+ # given
+ variant = stock.product_variant
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "lines": [
+ {"variantId": variant_id, "quantity": 1},
+ {"variantId": variant_id, "quantity": 1, "forceNewLine": True},
+ ],
+ "channelSlug": checkout.channel.slug,
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_CHECKOUT_LINES_ADD,
+ variables,
+ permissions=[permission_handle_checkouts],
+ check_no_permissions=False,
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutLinesAdd"]
+ checkout.refresh_from_db()
+ lines = checkout.lines.all()
+
+ # then
+ assert not data["errors"]
+ assert len(lines) == 2
+ for line in lines:
+ assert line.variant == variant
+ assert line.quantity == 1
+
+
+def test_checkout_lines_add_create_new_line_when_variant_already_in_multiple_lines(
+ app_api_client,
+ checkout_with_same_items_in_multiple_lines,
+ permission_handle_checkouts,
+):
+ # given
+ checkout = checkout_with_same_items_in_multiple_lines
+ assert checkout.lines.count() == 2
+
+ variant_id = checkout.lines.first().variant_id
+ variant_global_id = graphene.Node.to_global_id("ProductVariant", variant_id)
+
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "lines": [
+ {"variantId": variant_global_id, "quantity": 1},
+ ],
+ "channelSlug": checkout.channel.slug,
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_CHECKOUT_LINES_ADD,
+ variables,
+ permissions=[permission_handle_checkouts],
+ check_no_permissions=False,
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutLinesAdd"]
+ checkout.refresh_from_db()
+ lines = checkout.lines.all()
+
+ # then
+ assert not data["errors"]
+ assert len(lines) == 3
+
+ for line in lines:
+ assert line.variant_id == variant_id
+ assert line.quantity == 1
+
+
def test_checkout_lines_add_custom_price(
app_api_client, checkout, stock, permission_handle_checkouts
):
@@ -640,6 +717,34 @@ def test_checkout_lines_add_too_many(user_api_client, checkout_with_item, stock)
]
+def test_checkout_lines_add_too_many_when_variant_in_multiple_lines(
+ user_api_client, checkout_with_item, stock
+):
+ variant = stock.product_variant
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+
+ variables = {
+ "id": to_global_id_or_none(checkout_with_item),
+ "lines": [
+ {"variantId": variant_id, "quantity": 30},
+ {"variantId": variant_id, "quantity": 21, "forceNewLine": True},
+ ],
+ "channelSlug": checkout_with_item.channel.slug,
+ }
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
+ content = get_graphql_content(response)["data"]["checkoutLinesAdd"]
+
+ assert content["errors"]
+ assert content["errors"] == [
+ {
+ "field": "quantity",
+ "message": "Cannot add more than 50 times this item: SKU_A.",
+ "code": "QUANTITY_GREATER_THAN_LIMIT",
+ "variants": None,
+ }
+ ]
+
+
@pytest.mark.parametrize("is_preorder", [True, False])
def test_checkout_lines_add_too_many_after_two_trials(
user_api_client, checkout_with_item, stock, is_preorder
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py
index 044ff56356..f1c02e42bb 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py
@@ -110,6 +110,155 @@ def test_checkout_lines_update(
assert mocked_invalidate_checkout_prices.call_count == 1
+ "saleor.graphql.checkout.mutations.checkout_lines_add."
+ "update_checkout_shipping_method_if_invalid",
+ wraps=update_checkout_shipping_method_if_invalid,
+)
+def test_checkout_lines_update_using_line_id(
+ mocked_update_shipping_method, user_api_client, checkout_with_item
+):
+ checkout = checkout_with_item
+ lines, _ = fetch_checkout_lines(checkout)
+ assert checkout.lines.count() == 1
+ assert calculate_checkout_quantity(lines) == 3
+ line = checkout.lines.first()
+ variant = line.variant
+ assert line.quantity == 3
+ previous_last_change = checkout.last_change
+
+ line_id = graphene.Node.to_global_id("CheckoutLine", line.pk)
+
+ variables = {
+ "id": to_global_id_or_none(checkout_with_item),
+ "lines": [{"lineId": line_id, "quantity": 1}],
+ }
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)
+ content = get_graphql_content(response)
+
+ data = content["data"]["checkoutLinesUpdate"]
+ assert not data["errors"]
+ checkout.refresh_from_db()
+ lines, _ = fetch_checkout_lines(checkout)
+ assert checkout.lines.count() == 1
+ line = checkout.lines.first()
+ assert line.variant == variant
+ assert line.quantity == 1
+ assert calculate_checkout_quantity(lines) == 1
+
+ manager = get_plugins_manager()
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+ mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)
+ assert checkout.last_change != previous_last_change
+
+
+ "saleor.graphql.checkout.mutations.checkout_lines_add."
+ "update_checkout_shipping_method_if_invalid",
+ wraps=update_checkout_shipping_method_if_invalid,
+)
+def test_checkout_lines_update_using_line_id_and_variant_id(
+ mocked_update_shipping_method, user_api_client, checkout_with_item
+):
+ checkout = checkout_with_item
+ lines, _ = fetch_checkout_lines(checkout)
+ assert checkout.lines.count() == 1
+ assert calculate_checkout_quantity(lines) == 3
+ line = checkout.lines.first()
+ variant = line.variant
+ assert line.quantity == 3
+ previous_last_change = checkout.last_change
+
+ line_id = graphene.Node.to_global_id("CheckoutLine", line.pk)
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+
+ variables = {
+ "id": to_global_id_or_none(checkout_with_item),
+ "lines": [
+ {"lineId": line_id, "quantity": 1},
+ {"variantId": variant_id, "quantity": 1},
+ ],
+ }
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)
+ content = get_graphql_content(response)
+
+ data = content["data"]["checkoutLinesUpdate"]
+ assert not data["errors"]
+ checkout.refresh_from_db()
+ lines, _ = fetch_checkout_lines(checkout)
+ assert checkout.lines.count() == 1
+ line = checkout.lines.first()
+ assert line.variant == variant
+ assert line.quantity == 2
+ assert calculate_checkout_quantity(lines) == 2
+
+ manager = get_plugins_manager()
+ lines, _ = fetch_checkout_lines(checkout)
+ checkout_info = fetch_checkout_info(checkout, lines, [], manager)
+ mocked_update_shipping_method.assert_called_once_with(checkout_info, lines)
+ assert checkout.last_change != previous_last_change
+
+
+def test_checkout_lines_update_block_when_variant_id_and_same_variant_in_multiple_lines(
+ user_api_client, checkout_with_same_items_in_multiple_lines
+):
+ # given
+ checkout = checkout_with_same_items_in_multiple_lines
+ lines, _ = fetch_checkout_lines(checkout)
+ assert checkout.lines.count() == 2
+ assert calculate_checkout_quantity(lines) == 2
+ line = checkout.lines.first()
+ variant = line.variant
+
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "lines": [{"variantId": variant_id, "quantity": 2}],
+ }
+
+ # when
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["checkoutLinesUpdate"]
+
+ # then
+
+ assert data["errors"][0]["code"] == CheckoutErrorCode.INVALID.name
+ assert data["errors"][0]["field"] == "variantId"
+
+
+def test_checkout_lines_update_block_when_variant_id_and_line_id_provided(
+ user_api_client, checkout_with_item
+):
+ # given
+ checkout = checkout_with_item
+ lines, _ = fetch_checkout_lines(checkout)
+ assert checkout.lines.count() == 1
+ assert calculate_checkout_quantity(lines) == 3
+ line = checkout.lines.first()
+ variant = line.variant
+
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ line_id = graphene.Node.to_global_id("CheckoutLine", line.pk)
+
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "lines": [{"variantId": variant_id, "lineId": line_id, "quantity": 2}],
+ }
+
+ # when
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)
+ content = get_graphql_content(response)
+
+ data = content["data"]["checkoutLinesUpdate"]
+ expected_message = "Argument 'line_id' cannot be combined with 'variant_id'"
+
+ # then
+ assert data["errors"][0]["code"] == CheckoutErrorCode.GRAPHQL_ERROR.name
+ assert data["errors"][0]["message"] == expected_message
+
+
def test_checkout_lines_update_checkout_with_voucher(
user_api_client, checkout_with_item, voucher_percentage
):
diff --git a/saleor/graphql/checkout/tests/mutations/test_utils.py b/saleor/graphql/checkout/tests/mutations/test_utils.py
index 046ea2c76d..24ee36efad 100644
--- a/saleor/graphql/checkout/tests/mutations/test_utils.py
+++ b/saleor/graphql/checkout/tests/mutations/test_utils.py
@@ -1,80 +1,181 @@
-import pytest
+import graphene
+from .....checkout.fetch import fetch_checkout_lines
from ...mutations.utils import (
CheckoutLineData,
- group_quantity_and_custom_prices_by_variants,
+ group_lines_input_data_on_update,
+ group_lines_input_on_add,
)
- "lines, expected",
- [
- (
- [
- {"quantity": 6, "variant_id": "abc", "price": 1.22},
- {"quantity": 6, "variant_id": "abc"},
- {"quantity": 1, "variant_id": "def", "price": 33.2},
- {"quantity": 1, "variant_id": "def", "price": 10},
- ],
- [
- CheckoutLineData(
- quantity=12,
- quantity_to_update=True,
- custom_price=1.22,
- custom_price_to_update=True,
- ),
- CheckoutLineData(
- quantity=2,
- quantity_to_update=True,
- custom_price=10,
- custom_price_to_update=True,
- ),
- ],
+def test_group_on_add_when_same_variants_in_multiple_lines():
+ variant_1_id = graphene.Node.to_global_id("ProductVariant", 1)
+ variant_2_id = graphene.Node.to_global_id("ProductVariant", 2)
+ variant_3_id = graphene.Node.to_global_id("ProductVariant", 3)
+ variant_4_id = graphene.Node.to_global_id("ProductVariant", 4)
+ variant_5_id = graphene.Node.to_global_id("ProductVariant", 5)
+
+ lines_data = [
+ {"quantity": 8, "variant_id": variant_1_id},
+ {"quantity": 2, "variant_id": variant_1_id},
+ {"quantity": 6, "variant_id": variant_2_id},
+ {"quantity": 1, "variant_id": variant_3_id},
+ {"quantity": 6, "variant_id": variant_2_id},
+ {"quantity": 1, "variant_id": variant_3_id},
+ {"quantity": 8, "variant_id": variant_1_id},
+ {"quantity": 2, "variant_id": variant_1_id},
+ {"quantity": 922, "variant_id": variant_4_id},
+ {"quantity": 6, "variant_id": variant_2_id},
+ {"quantity": 1, "variant_id": variant_3_id},
+ {"quantity": 6, "variant_id": variant_2_id},
+ {"quantity": 1, "variant_id": variant_3_id},
+ {"quantity": 1000, "variant_id": variant_5_id},
+ ]
+
+ expected = [
+ CheckoutLineData(
+ variant_id=str(id + 1),
+ line_id=None,
+ quantity=quantity,
+ quantity_to_update=True,
+ custom_price=None,
+ custom_price_to_update=False,
+ )
+ for id, quantity in enumerate([20, 24, 4, 922, 1000])
+ ]
+
+ assert expected == group_lines_input_on_add(lines_data)
+
+
+def test_group_on_add_when_same_variants_in_multiple_lines_and_price_provided():
+ variant_1_id = graphene.Node.to_global_id("ProductVariant", 1)
+ variant_2_id = graphene.Node.to_global_id("ProductVariant", 2)
+
+ lines_data = [
+ {"quantity": 6, "variant_id": variant_1_id, "price": 1.22},
+ {"quantity": 6, "variant_id": variant_1_id},
+ {"quantity": 1, "variant_id": variant_2_id, "price": 33.2},
+ {"quantity": 1, "variant_id": variant_2_id, "price": 10},
+ ]
+
+ expected = [
+ CheckoutLineData(
+ variant_id="1",
+ line_id=None,
+ quantity=12,
+ quantity_to_update=True,
+ custom_price=1.22,
+ custom_price_to_update=True,
),
- (
- [
- {"quantity": 8, "variant_id": "ghi"},
- {"quantity": 2, "variant_id": "ghi"},
- {"quantity": 6, "variant_id": "abc"},
- {"quantity": 1, "variant_id": "def"},
- {"quantity": 6, "variant_id": "abc"},
- {"quantity": 1, "variant_id": "def"},
- {"quantity": 8, "variant_id": "ghi"},
- {"quantity": 2, "variant_id": "ghi"},
- {"quantity": 922, "variant_id": "xyz"},
- {"quantity": 6, "variant_id": "abc"},
- {"quantity": 1, "variant_id": "def"},
- {"quantity": 6, "variant_id": "abc"},
- {"quantity": 1, "variant_id": "def"},
- {"quantity": 1000, "variant_id": "jkl"},
- {"quantity": 999, "variant_id": "zzz"},
- ],
- [
- CheckoutLineData(
- quantity=quantity,
- quantity_to_update=True,
- custom_price=None,
- custom_price_to_update=False,
- )
- for quantity in [20, 24, 4, 922, 1000, 999]
- ],
+ CheckoutLineData(
+ variant_id="2",
+ line_id=None,
+ quantity=2,
+ quantity_to_update=True,
+ custom_price=10,
+ custom_price_to_update=True,
),
- (
- [
- {"quantity": 100, "variant_id": name}
- for name in (l1 + l2 for l1 in "abcdef" for l2 in "ghijkl")
- ],
- [
- CheckoutLineData(
- quantity=100,
- quantity_to_update=True,
- custom_price=None,
- custom_price_to_update=False,
- )
- ]
- * 36,
+ ]
+
+ assert expected == group_lines_input_on_add(lines_data)
+
+
+def test_group_on_add_when_same_variants_in_multiple_lines_and_force_new_line():
+ variant_1_id = graphene.Node.to_global_id("ProductVariant", 1)
+ variant_2_id = graphene.Node.to_global_id("ProductVariant", 2)
+
+ lines_data = [
+ {"quantity": 6, "variant_id": variant_1_id, "price": 1.22},
+ {"quantity": 6, "variant_id": variant_1_id, "force_new_line": True},
+ {"quantity": 1, "variant_id": variant_2_id, "price": 33.2},
+ {"quantity": 1, "variant_id": variant_2_id, "price": 10},
+ ]
+
+ expected = [
+ CheckoutLineData(
+ variant_id="1",
+ line_id=None,
+ quantity=6,
+ quantity_to_update=True,
+ custom_price=None,
+ custom_price_to_update=False,
),
- ],
-)
-def test_group_by_variants(lines, expected):
- assert expected == group_quantity_and_custom_prices_by_variants(lines)
+ CheckoutLineData(
+ variant_id="1",
+ line_id=None,
+ quantity=6,
+ quantity_to_update=True,
+ custom_price=1.22,
+ custom_price_to_update=True,
+ ),
+ CheckoutLineData(
+ variant_id="2",
+ line_id=None,
+ quantity=2,
+ quantity_to_update=True,
+ custom_price=10,
+ custom_price_to_update=True,
+ ),
+ ]
+
+ assert expected == group_lines_input_on_add(lines_data)
+
+
+def test_group_on_update_when_line_id_as_parameter_provided():
+ line_1_id = graphene.Node.to_global_id("CheckoutLine", "abc")
+ line_2_id = graphene.Node.to_global_id("CheckoutLine", "qwe")
+
+ lines_data = [
+ {"quantity": 6, "line_id": line_1_id, "price": 1.22},
+ {"quantity": 1, "line_id": line_2_id, "price": 10},
+ ]
+
+ expected = [
+ CheckoutLineData(
+ variant_id=None,
+ line_id="abc",
+ quantity=6,
+ quantity_to_update=True,
+ custom_price=1.22,
+ custom_price_to_update=True,
+ ),
+ CheckoutLineData(
+ variant_id=None,
+ line_id="qwe",
+ quantity=1,
+ quantity_to_update=True,
+ custom_price=10,
+ custom_price_to_update=True,
+ ),
+ ]
+
+ assert expected == group_lines_input_data_on_update(lines_data)
+
+
+def test_group_on_update_when_one_line_and_mixed_parameters_provided(
+ checkout_with_item,
+):
+ line = checkout_with_item.lines.first()
+ variant_id = graphene.Node.to_global_id("ProductVariant", line.variant_id)
+ line_id = graphene.Node.to_global_id("CheckoutLine", line.id)
+
+ existing_checkout_lines, _ = fetch_checkout_lines(checkout_with_item)
+
+ lines_data = [
+ {"quantity": 6, "variant_id": variant_id, "price": 1.22},
+ {"quantity": 1, "line_id": line_id, "price": 10},
+ ]
+
+ expected = [
+ CheckoutLineData(
+ variant_id=str(line.variant_id),
+ line_id=str(line.id),
+ quantity=7,
+ quantity_to_update=True,
+ custom_price=10,
+ custom_price_to_update=True,
+ )
+ ]
+ assert expected == group_lines_input_data_on_update(
+ lines_data, existing_checkout_lines
+ )
diff --git a/saleor/graphql/order/mutations/draft_order_create.py b/saleor/graphql/order/mutations/draft_order_create.py
index fa3130a0b5..3b4384be7b 100644
--- a/saleor/graphql/order/mutations/draft_order_create.py
+++ b/saleor/graphql/order/mutations/draft_order_create.py
@@ -1,4 +1,5 @@
-from typing import List, Tuple
+from collections import defaultdict
+from typing import Dict, List
import graphene
from django.core.exceptions import ValidationError
@@ -14,20 +15,22 @@ from ....order import OrderOrigin, OrderStatus, events, models
from ....order.error_codes import OrderErrorCode
from ....order.search import update_order_search_vector
from ....order.utils import (
- add_variant_to_order,
+ create_order_line,
invalidate_order_prices,
recalculate_order_weight,
)
from ...account.i18n import I18nMixin
from ...account.types import AddressInput
from ...channel.types import Channel
+from ...core.descriptions import ADDED_IN_36, PREVIEW_FEATURE
from ...core.mutations import ModelMutation
from ...core.scalars import PositiveDecimal
from ...core.types import NonNullList, OrderError
from ...product.types import ProductVariant
from ...shipping.utils import get_shipping_model_by_object_id
-from ..types import Order, OrderLine
+from ..types import Order
from ..utils import (
+ OrderLineData,
validate_product_is_published_in_channel,
validate_variant_channel_listings,
)
@@ -43,6 +46,14 @@ class OrderLineCreateInput(OrderLineInput):
variant_id = graphene.ID(
description="Product variant ID.", name="variantId", required=True
)
+ force_new_line = graphene.Boolean(
+ required=False,
+ default_value=False,
+ description=(
+ "Flag that allow force splitting the same variant into multiple lines "
+ "by skipping the matching logic. " + ADDED_IN_36 + PREVIEW_FEATURE
+ ),
+ )
class DraftOrderInput(InputObjectType):
@@ -171,6 +182,9 @@ class DraftOrderCreate(ModelMutation, I18nMixin):
@classmethod
def clean_lines(cls, cleaned_input, lines, channel):
if lines:
+ grouped_lines_data: List[OrderLineData] = []
+ lines_data_map: Dict[str, OrderLineData] = defaultdict(OrderLineData)
+
variant_ids = [line.get("variant_id") for line in lines]
variants = cls.get_nodes_or_error(variant_ids, "variants", ProductVariant)
validate_product_is_published_in_channel(variants, channel)
@@ -185,8 +199,27 @@ class DraftOrderCreate(ModelMutation, I18nMixin):
)
}
)
- cleaned_input["variants"] = variants
- cleaned_input["quantities"] = quantities
+
+ for line in lines:
+ variant_id = line.get("variant_id")
+ _, variant_db_id = graphene.Node.from_global_id(variant_id)
+ variant = list(
+ filter(lambda x: (x.pk == int(variant_db_id)), variants)
+ )[0]
+
+ if line.get("force_new_line"):
+ line_data = OrderLineData(variant_id=variant_db_id, variant=variant)
+ grouped_lines_data.append(line_data)
+ else:
+ line_data = lines_data_map[variant_db_id]
+ line_data.variant_id = variant_db_id
+ line_data.variant = variant
+
+ if (quantity := line.get("quantity")) is not None:
+ line_data.quantity += quantity
+
+ grouped_lines_data += list(lines_data_map.values())
+ cleaned_input["lines_data"] = grouped_lines_data
@classmethod
def clean_addresses(
@@ -235,20 +268,17 @@ class DraftOrderCreate(ModelMutation, I18nMixin):
instance.billing_address = billing_address.get_copy()
@staticmethod
- def _save_lines(info, instance, quantities, variants):
- if variants and quantities:
- lines: List[Tuple[int, OrderLine]] = []
- for variant, quantity in zip(variants, quantities):
- line = add_variant_to_order(
+ def _save_lines(info, instance, lines_data):
+ if lines_data:
+ lines = []
+ for line_data in lines_data:
+ new_line = create_order_line(
instance,
- variant,
- quantity,
- info.context.user,
- info.context.app,
+ line_data,
info.context.plugins,
info.context.site.settings,
)
- lines.append((quantity, line))
+ lines.append(new_line)
# New event
events.order_added_products_event(
@@ -294,12 +324,7 @@ class DraftOrderCreate(ModelMutation, I18nMixin):
try:
# Process any lines to add
- cls._save_lines(
- info,
- instance,
- cleaned_input.get("quantities"),
- cleaned_input.get("variants"),
- )
+ cls._save_lines(info, instance, cleaned_input.get("lines_data"))
except TaxError as tax_error:
raise ValidationError(
"Unable to calculate taxes - %s" % str(tax_error),
diff --git a/saleor/graphql/order/mutations/order_line_delete.py b/saleor/graphql/order/mutations/order_line_delete.py
index 2e19e46a6a..c460a68ab5 100644
--- a/saleor/graphql/order/mutations/order_line_delete.py
+++ b/saleor/graphql/order/mutations/order_line_delete.py
@@ -78,7 +78,7 @@ class OrderLineDelete(EditableOrderValidationMixin, BaseMutation):
order=order,
user=info.context.user,
app=info.context.app,
- order_lines=[(line.quantity, line)],
+ order_lines=[line],
)
invalidate_order_prices(order)
diff --git a/saleor/graphql/order/mutations/order_lines_create.py b/saleor/graphql/order/mutations/order_lines_create.py
index c6ea7ba93e..6d097c9f71 100644
--- a/saleor/graphql/order/mutations/order_lines_create.py
+++ b/saleor/graphql/order/mutations/order_lines_create.py
@@ -1,4 +1,5 @@
-from typing import List, Tuple
+from collections import defaultdict
+from typing import Dict, List
import graphene
from django.core.exceptions import ValidationError
@@ -9,6 +10,7 @@ from ....core.taxes import TaxError
from ....core.tracing import traced_atomic_transaction
from ....order import events
from ....order.error_codes import OrderErrorCode
+from ....order.fetch import fetch_order_lines
from ....order.search import update_order_search_vector
from ....order.utils import (
add_variant_to_order,
@@ -20,6 +22,7 @@ from ...core.types import NonNullList, OrderError
from ...product.types import ProductVariant
from ..types import Order, OrderLine
from ..utils import (
+ OrderLineData,
validate_product_is_published_in_channel,
validate_variant_channel_listings,
)
@@ -49,17 +52,46 @@ class OrderLinesCreate(EditableOrderValidationMixin, BaseMutation):
errors_mapping = {"lines": "input", "channel": "input"}
@classmethod
- def validate_lines(cls, info, data):
- lines_to_add = []
+ def validate_lines(cls, info, data, existing_lines_info):
+ grouped_lines_data: List[OrderLineData] = []
+ lines_data_map: Dict[str, OrderLineData] = defaultdict(OrderLineData)
+
+ variants_from_existing_lines = [
+ line_info.line.variant_id for line_info in existing_lines_info
+ ]
+
invalid_ids = []
for input_line in data.get("input"):
variant_id = input_line["variant_id"]
+ force_new_line = input_line["force_new_line"]
variant = cls.get_node_or_error(
info, variant_id, "variant_id", only_type=ProductVariant
)
quantity = input_line["quantity"]
+
if quantity > 0:
- lines_to_add.append((quantity, variant))
+ if force_new_line or variants_from_existing_lines.count(variant.pk) > 1:
+ grouped_lines_data.append(
+ OrderLineData(
+ variant_id=str(variant.id),
+ variant=variant,
+ quantity=quantity,
+ )
+ )
+ else:
+ line_id = cls._find_line_id_for_variant_if_exist(
+ variant.pk, existing_lines_info
+ )
+
+ if line_id:
+ line_data = lines_data_map[line_id]
+ line_data.line_id = line_id
+ else:
+ line_data = lines_data_map[str(variant.id)]
+ line_data.variant_id = str(variant.id)
+
+ line_data.variant = variant
+ line_data.quantity += quantity
else:
invalid_ids.append(variant_id)
if invalid_ids:
@@ -72,7 +104,9 @@ class OrderLinesCreate(EditableOrderValidationMixin, BaseMutation):
),
}
)
- return lines_to_add
+
+ grouped_lines_data += list(lines_data_map.values())
+ return grouped_lines_data
@classmethod
def validate_variants(cls, order, variants):
@@ -85,16 +119,13 @@ class OrderLinesCreate(EditableOrderValidationMixin, BaseMutation):
raise ValidationError(error)
@staticmethod
- def add_lines_to_order(
- order, lines_to_add, user, app, manager, settings, discounts
- ):
- added_lines: List[Tuple[int, OrderLine]] = []
+ def add_lines_to_order(order, lines_data, user, app, manager, settings, discounts):
+ added_lines: List[OrderLine] = []
try:
- for quantity, variant in lines_to_add:
+ for line_data in lines_data:
line = add_variant_to_order(
order,
- variant,
- quantity,
+ line_data,
user,
app,
manager,
@@ -102,7 +133,7 @@ class OrderLinesCreate(EditableOrderValidationMixin, BaseMutation):
discounts=discounts,
allocate_stock=order.is_unconfirmed(),
)
- added_lines.append((quantity, line))
+ added_lines.append(line)
except TaxError as tax_error:
raise ValidationError(
"Unable to calculate taxes - %s" % str(tax_error),
@@ -115,8 +146,10 @@ class OrderLinesCreate(EditableOrderValidationMixin, BaseMutation):
def perform_mutation(cls, _root, info, **data):
order = cls.get_node_or_error(info, data.get("id"), only_type=Order)
cls.validate_order(order)
- lines_to_add = cls.validate_lines(info, data)
- variants = [line[1] for line in lines_to_add]
+ existing_lines_info = fetch_order_lines(order)
+
+ lines_to_add = cls.validate_lines(info, data, existing_lines_info)
+ variants = [line.variant for line in lines_to_add]
cls.validate_variants(order, variants)
added_lines = cls.add_lines_to_order(
@@ -137,8 +170,6 @@ class OrderLinesCreate(EditableOrderValidationMixin, BaseMutation):
order_lines=added_lines,
)
- lines = [line for _, line in added_lines]
-
invalidate_order_prices(order)
recalculate_order_weight(order)
update_order_search_vector(order, save=False)
@@ -153,4 +184,19 @@ class OrderLinesCreate(EditableOrderValidationMixin, BaseMutation):
func = get_webhook_handler_by_order_status(order.status, info)
transaction.on_commit(lambda: func(order))
- return OrderLinesCreate(order=order, order_lines=lines)
+ return OrderLinesCreate(order=order, order_lines=added_lines)
+
+ @classmethod
+ def _find_line_id_for_variant_if_exist(cls, variant_id, lines_info):
+ """Return line id by using provided variantId parameter."""
+ if not lines_info:
+ return
+
+ line_info = list(
+ filter(lambda x: (x.variant.pk == int(variant_id)), lines_info)
+ )
+
+ if not line_info or len(line_info) > 1:
+ return
+
+ return str(line_info[0].line.id)
diff --git a/saleor/graphql/order/tests/test_order.py b/saleor/graphql/order/tests/test_order.py
index 381ac11672..f09b54400b 100644
--- a/saleor/graphql/order/tests/test_order.py
+++ b/saleor/graphql/order/tests/test_order.py
@@ -2617,6 +2617,101 @@ def test_draft_order_create(
assert event_parameters["lines"][1]["quantity"] == 1
+def test_draft_order_create_with_same_variant_and_force_new_line(
+ staff_api_client,
+ permission_manage_orders,
+ staff_user,
+ customer_user,
+ shipping_method,
+ variant,
+ voucher,
+ channel_USD,
+ graphql_address_data,
+):
+ variant_0 = variant
+ query = DRAFT_ORDER_CREATE_MUTATION
+
+ # Ensure no events were created yet
+ assert not OrderEvent.objects.exists()
+
+ user_id = graphene.Node.to_global_id("User", customer_user.id)
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant_0.id)
+
+ discount = "10"
+ customer_note = "Test note"
+ variant_list = [
+ {"variantId": variant_id, "quantity": 2},
+ {"variantId": variant_id, "quantity": 1, "forceNewLine": True},
+ ]
+ shipping_address = graphql_address_data
+ shipping_id = graphene.Node.to_global_id("ShippingMethod", shipping_method.id)
+ voucher_id = graphene.Node.to_global_id("Voucher", voucher.id)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ redirect_url = "https://www.example.com"
+
+ variables = {
+ "user": user_id,
+ "discount": discount,
+ "lines": variant_list,
+ "billingAddress": shipping_address,
+ "shippingAddress": shipping_address,
+ "shippingMethod": shipping_id,
+ "voucher": voucher_id,
+ "customerNote": customer_note,
+ "channel": channel_id,
+ "redirectUrl": redirect_url,
+ }
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ assert not content["data"]["draftOrderCreate"]["errors"]
+ data = content["data"]["draftOrderCreate"]["order"]
+ assert data["status"] == OrderStatus.DRAFT.upper()
+ assert data["voucher"]["code"] == voucher.code
+ assert data["customerNote"] == customer_note
+ assert data["redirectUrl"] == redirect_url
+ assert (
+ data["billingAddress"]["streetAddress1"]
+ == graphql_address_data["streetAddress1"]
+ )
+ assert (
+ data["shippingAddress"]["streetAddress1"]
+ == graphql_address_data["streetAddress1"]
+ )
+
+ order = Order.objects.first()
+ assert order.user == customer_user
+ assert order.shipping_method == shipping_method
+ assert order.billing_address
+ assert order.shipping_address
+ assert order.search_vector
+
+ # Ensure the correct event was created
+ created_draft_event = OrderEvent.objects.get(
+ type=order_events.OrderEvents.DRAFT_CREATED
+ )
+ assert created_draft_event.user == staff_user
+ assert created_draft_event.parameters == {}
+
+ # Ensure the order_added_products_event was created properly
+ added_products_event = OrderEvent.objects.get(
+ type=order_events.OrderEvents.ADDED_PRODUCTS
+ )
+ event_parameters = added_products_event.parameters
+ assert event_parameters
+ assert len(event_parameters["lines"]) == 2
+
+ order_lines = list(order.lines.all())
+ assert event_parameters["lines"][0]["item"] == str(order_lines[0])
+ assert event_parameters["lines"][0]["line_pk"] == str(order_lines[0].pk)
+ assert event_parameters["lines"][0]["quantity"] == 1
+
+ assert event_parameters["lines"][1]["item"] == str(order_lines[1])
+ assert event_parameters["lines"][1]["line_pk"] == str(order_lines[1].pk)
+ assert event_parameters["lines"][1]["quantity"] == 2
+
+
def test_draft_order_create_with_inactive_channel(
staff_api_client,
permission_manage_orders,
@@ -2836,9 +2931,9 @@ def test_draft_order_create_variant_with_0_price(
assert created_draft_event.parameters == {}
-@patch("saleor.graphql.order.mutations.draft_order_create.add_variant_to_order")
+@patch("saleor.graphql.order.mutations.draft_order_create.create_order_line")
def test_draft_order_create_tax_error(
- add_variant_to_order_mock,
+ create_order_line_mock,
staff_api_client,
permission_manage_orders,
staff_user,
@@ -2852,7 +2947,7 @@ def test_draft_order_create_tax_error(
):
variant_0 = variant
err_msg = "Test error"
- add_variant_to_order_mock.side_effect = TaxError(err_msg)
+ create_order_line_mock.side_effect = TaxError(err_msg)
query = DRAFT_ORDER_CREATE_MUTATION
# Ensure no events were created yet
assert not OrderEvent.objects.exists()
@@ -4862,9 +4957,17 @@ def test_draft_order_complete_not_draft_order(
ORDER_LINES_CREATE_MUTATION = """
- mutation OrderLinesCreate($orderId: ID!, $variantId: ID!, $quantity: Int!) {
+ mutation OrderLinesCreate(
+ $orderId: ID!, $variantId: ID!, $quantity: Int!, $forceNewLine: Boolean
+ ) {
orderLinesCreate(id: $orderId,
- input: [{variantId: $variantId, quantity: $quantity}]) {
+ input: [
+ {
+ variantId: $variantId,
+ quantity: $quantity,
+ forceNewLine: $forceNewLine
+ }
+ ]) {
errors {
field
@@ -5144,6 +5247,112 @@ def test_order_lines_create_with_existing_variant(
)
[email protected]("status", (OrderStatus.DRAFT, OrderStatus.UNCONFIRMED))
+@patch("saleor.plugins.manager.PluginsManager.draft_order_updated")
+@patch("saleor.plugins.manager.PluginsManager.order_updated")
+def test_order_lines_create_with_same_variant_and_force_new_line(
+ order_updated_webhook_mock,
+ draft_order_updated_webhook_mock,
+ status,
+ order_with_lines,
+ permission_manage_orders,
+ staff_api_client,
+):
+ query = ORDER_LINES_CREATE_MUTATION
+ order = order_with_lines
+ order.status = status
+ order.save(update_fields=["status"])
+ lines = order.lines.all()
+ assert len(lines) == 2
+ line = lines[0]
+ variant = line.variant
+
+ quantity = 1
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ variables = {
+ "orderId": order_id,
+ "variantId": variant_id,
+ "quantity": quantity,
+ "forceNewLine": True,
+ }
+
+ # mutation should fail without proper permissions
+ response = staff_api_client.post_graphql(query, variables)
+ assert_no_permission(response)
+ assert not OrderEvent.objects.exists()
+ order_updated_webhook_mock.assert_not_called()
+ draft_order_updated_webhook_mock.assert_not_called()
+
+ # assign permissions
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ response = staff_api_client.post_graphql(query, variables)
+ assert order.lines.count() == 3
+ assert OrderEvent.objects.count() == 1
+ assert OrderEvent.objects.last().type == order_events.OrderEvents.ADDED_PRODUCTS
+ content = get_graphql_content(response)
+ data = content["data"]["orderLinesCreate"]
+ assert data["orderLines"][0]["productSku"] == variant.sku
+ assert data["orderLines"][0]["productVariantId"] == variant.get_global_id()
+ assert data["orderLines"][0]["quantity"] == quantity
+ assert_proper_webhook_called_once(
+ order, status, draft_order_updated_webhook_mock, order_updated_webhook_mock
+ )
+
+
[email protected]("status", (OrderStatus.DRAFT, OrderStatus.UNCONFIRMED))
+@patch("saleor.plugins.manager.PluginsManager.draft_order_updated")
+@patch("saleor.plugins.manager.PluginsManager.order_updated")
+def test_order_lines_create_when_variant_already_in_multiple_lines(
+ order_updated_webhook_mock,
+ draft_order_updated_webhook_mock,
+ status,
+ order_with_lines,
+ permission_manage_orders,
+ staff_api_client,
+):
+ order = order_with_lines
+ order.status = status
+ order.save(update_fields=["status"])
+
+ line = order.lines.first()
+ variant = line.variant
+
+ # copy line and add to order
+ line.id = None
+ line.save()
+
+ assert order.lines.count() == 3
+
+ quantity = 1
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ variables = {
+ "orderId": order_id,
+ "variantId": variant_id,
+ "quantity": quantity,
+ "forceNewLine": True,
+ }
+
+ # assign permissions
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ response = staff_api_client.post_graphql(ORDER_LINES_CREATE_MUTATION, variables)
+
+ assert order.lines.count() == 4
+ assert OrderEvent.objects.count() == 1
+ assert OrderEvent.objects.last().type == order_events.OrderEvents.ADDED_PRODUCTS
+ content = get_graphql_content(response)
+ data = content["data"]["orderLinesCreate"]
+ assert data["orderLines"][0]["productSku"] == variant.sku
+ assert data["orderLines"][0]["productVariantId"] == variant.get_global_id()
+ assert data["orderLines"][0]["quantity"] == quantity
+ assert_proper_webhook_called_once(
+ order, status, draft_order_updated_webhook_mock, order_updated_webhook_mock
+ )
+
+
@pytest.mark.parametrize("status", (OrderStatus.DRAFT, OrderStatus.UNCONFIRMED))
@patch("saleor.plugins.manager.PluginsManager.draft_order_updated")
@patch("saleor.plugins.manager.PluginsManager.order_updated")
@@ -5690,11 +5899,10 @@ def test_retrieving_event_lines_with_deleted_line(
):
order = order_with_lines
lines = order_with_lines.lines.all()
- quantities_per_lines = [(line.quantity, line) for line in lines]
# Create the test event
order_events.order_added_products_event(
- order=order, user=staff_user, app=None, order_lines=quantities_per_lines
+ order=order, user=staff_user, app=None, order_lines=lines
)
# Delete a line
@@ -5709,9 +5917,10 @@ def test_retrieving_event_lines_with_deleted_line(
data = content["data"]["orders"]["edges"][0]["node"]["events"][0]
# Check every line is returned and the one deleted is None
- assert len(data["lines"]) == len(quantities_per_lines)
- for expected_data, received_line in zip(quantities_per_lines, data["lines"]):
- quantity, line = expected_data
+ assert len(data["lines"]) == len(lines)
+ for expected_data, received_line in zip(lines, data["lines"]):
+ quantity = expected_data.quantity
+ line = expected_data
if line is deleted_line:
assert received_line["orderLine"] is None
@@ -5729,11 +5938,10 @@ def test_retrieving_event_lines_with_missing_line_pk_in_data(
):
order = order_with_lines
line = order_with_lines.lines.first()
- quantities_per_lines = [(line.quantity, line)]
# Create the test event
event = order_events.order_added_products_event(
- order=order, user=staff_user, app=None, order_lines=quantities_per_lines
+ order=order, user=staff_user, app=None, order_lines=[line]
)
del event.parameters["lines"][0]["line_pk"]
event.save(update_fields=["parameters"])
diff --git a/saleor/graphql/order/utils.py b/saleor/graphql/order/utils.py
index 58cfc76c00..d66ee3bf71 100644
--- a/saleor/graphql/order/utils.py
+++ b/saleor/graphql/order/utils.py
@@ -17,10 +17,19 @@ from ..core.validators import validate_variants_available_in_channel
if TYPE_CHECKING:
from ...channel.models import Channel
from ...order.models import Order
+from dataclasses import dataclass
T_ERRORS = Dict[str, List[ValidationError]]
+@dataclass
+class OrderLineData:
+ variant_id: Optional[str] = None
+ variant: Optional[ProductVariant] = None
+ line_id: Optional[str] = None
+ quantity: int = 0
+
+
def validate_total_quantity(order: "Order", errors: T_ERRORS):
if order.get_total_quantity() == 0:
errors["lines"].append(
diff --git a/saleor/graphql/product/bulk_mutations/products.py b/saleor/graphql/product/bulk_mutations/products.py
index adf6254440..c2cf6079e1 100644
--- a/saleor/graphql/product/bulk_mutations/products.py
+++ b/saleor/graphql/product/bulk_mutations/products.py
@@ -165,9 +165,8 @@ class ProductBulkDelete(ModelBulkDeleteMutation):
# run order event for deleted lines
for order, order_lines in draft_order_lines_data.order_to_lines_mapping.items():
- lines_data = [(line.quantity, line) for line in order_lines]
order_events.order_line_product_removed_event(
- order, info.context.user, info.context.app, lines_data
+ order, info.context.user, info.context.app, order_lines
)
order_pks = draft_order_lines_data.order_pks
@@ -630,9 +629,8 @@ class ProductVariantBulkDelete(ModelBulkDeleteMutation):
# run order event for deleted lines
for order, order_lines in draft_order_lines_data.order_to_lines_mapping.items():
- lines_data = [(line.quantity, line) for line in order_lines]
order_events.order_line_variant_removed_event(
- order, info.context.user, info.context.app, lines_data
+ order, info.context.user, info.context.app, order_lines
)
order_pks = draft_order_lines_data.order_pks
diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.py
index f29ba622de..5cc727a3b9 100644
--- a/saleor/graphql/product/mutations/products.py
+++ b/saleor/graphql/product/mutations/products.py
@@ -767,9 +767,8 @@ class ProductDelete(ModelDeleteMutation):
# run order event for deleted lines
for order, order_lines in draft_order_lines_data.order_to_lines_mapping.items():
- lines_data = [(line.quantity, line) for line in order_lines]
order_events.order_line_product_removed_event(
- order, info.context.user, info.context.app, lines_data
+ order, info.context.user, info.context.app, order_lines
)
order_pks = draft_order_lines_data.order_pks
@@ -1183,9 +1182,8 @@ class ProductVariantDelete(ModelDeleteMutation):
# run order event for deleted lines
for order, order_lines in draft_order_lines_data.order_to_lines_mapping.items():
- lines_data = [(line.quantity, line) for line in order_lines]
order_events.order_line_variant_removed_event(
- order, info.context.user, info.context.app, lines_data
+ order, info.context.user, info.context.app, order_lines
)
order_pks = draft_order_lines_data.order_pks
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index ac6a8cc42b..5701bf0a00 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -17421,6 +17421,15 @@ input OrderLineCreateInput {
"""Product variant ID."""
variantId: ID!
+
+ """
+ Flag that allow force splitting the same variant into multiple lines by skipping the matching logic.
+
+ Added in Saleor 3.6.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ forceNewLine: Boolean = false
}
"""
@@ -19502,6 +19511,15 @@ input CheckoutLineInput {
Note: this API is currently in Feature Preview and can be subject to changes at later point.
"""
price: PositiveDecimal
+
+ """
+ Flag that allow force splitting the same variant into multiple lines by skipping the matching logic.
+
+ Added in Saleor 3.6.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ forceNewLine: Boolean = false
}
input CheckoutValidationRules {
@@ -19582,14 +19600,18 @@ type CheckoutLinesUpdate {
}
input CheckoutLineUpdateInput {
+ """
+ ID of the product variant.
+
+ DEPRECATED: this field will be removed in Saleor 4.0. Use `lineId` instead.
+ """
+ variantId: ID
+
"""
The number of items purchased. Optional for apps, required for any other users.
"""
quantity: Int
- """ID of the product variant."""
- variantId: ID!
-
"""
Custom price of the item. Can be set only by apps with `HANDLE_CHECKOUTS` permission. When the line with the same variant will be provided multiple times, the last price will be used.
@@ -19598,6 +19620,13 @@ input CheckoutLineUpdateInput {
Note: this API is currently in Feature Preview and can be subject to changes at later point.
"""
price: PositiveDecimal
+
+ """
+ ID of the line.
+
+ Added in Saleor 3.6.
+ """
+ lineId: ID
}
"""Remove a gift card or a voucher from a checkout."""
diff --git a/saleor/order/actions.py b/saleor/order/actions.py
index 327153d4ea..6fc506e6a2 100644
--- a/saleor/order/actions.py
+++ b/saleor/order/actions.py
@@ -1124,7 +1124,7 @@ def create_replace_order(
order_line.quantity_fulfilled = 0
order_line_to_create[order_line_id] = order_line
- lines_to_create = order_line_to_create.values()
+ lines_to_create = list(order_line_to_create.values())
OrderLine.objects.bulk_create(lines_to_create)
draft_order_created_from_replace_event(
@@ -1132,7 +1132,7 @@ def create_replace_order(
original_order=original_order,
user=user,
app=app,
- lines=[(line.quantity, line) for line in lines_to_create],
+ lines=lines_to_create,
)
return replace_order
@@ -1301,12 +1301,11 @@ def process_replace(
order_lines_to_replace=order_lines,
fulfillment_lines_to_replace=fulfillment_lines,
)
- replaced_lines = [(line.quantity, line) for line in new_order.lines.all()]
fulfillment_replaced_event(
order=order,
user=user,
app=app,
- replaced_lines=replaced_lines,
+ replaced_lines=list(new_order.lines.all()),
)
order_replacement_created(
original_order=order,
diff --git a/saleor/order/events.py b/saleor/order/events.py
index eb59ca0c6f..55cbb8dddd 100644
--- a/saleor/order/events.py
+++ b/saleor/order/events.py
@@ -23,10 +23,9 @@ def _line_per_quantity_to_line_object(quantity, line):
return {"quantity": quantity, "line_pk": line.pk, "item": str(line)}
-def _lines_per_quantity_to_line_object_list(quantities_per_order_line):
+def _lines_per_quantity_to_line_object_list(order_lines):
return [
- _line_per_quantity_to_line_object(quantity, line)
- for quantity, line in quantities_per_order_line
+ _line_per_quantity_to_line_object(line.quantity, line) for line in order_lines
]
@@ -274,16 +273,23 @@ def order_added_products_event(
order: Order,
user: UserType,
app: AppType,
- order_lines: List[Tuple[int, OrderLine]]
+ order_lines: List[OrderLine],
+ quantity_diff: int = None
) -> OrderEvent:
if not user_is_valid(user):
user = None
+
+ if quantity_diff:
+ lines = [_line_per_quantity_to_line_object(quantity_diff, order_lines[0])]
+ else:
+ lines = _lines_per_quantity_to_line_object_list(order_lines)
+
return OrderEvent.objects.create(
order=order,
type=OrderEvents.ADDED_PRODUCTS,
user=user,
app=app,
- parameters={"lines": _lines_per_quantity_to_line_object_list(order_lines)},
+ parameters={"lines": lines},
)
@@ -292,16 +298,23 @@ def order_removed_products_event(
order: Order,
user: UserType,
app: AppType,
- order_lines: List[Tuple[int, OrderLine]]
+ order_lines: List[OrderLine],
+ quantity_diff: int = None
) -> OrderEvent:
if not user_is_valid(user):
user = None
+
+ if quantity_diff:
+ lines = [_line_per_quantity_to_line_object(quantity_diff, order_lines[0])]
+ else:
+ lines = _lines_per_quantity_to_line_object_list(order_lines)
+
return OrderEvent.objects.create(
order=order,
type=OrderEvents.REMOVED_PRODUCTS,
user=user,
app=app,
- parameters={"lines": _lines_per_quantity_to_line_object_list(order_lines)},
+ parameters={"lines": lines},
)
@@ -311,7 +324,7 @@ def draft_order_created_from_replace_event(
original_order: Order,
user: UserType,
app: AppType,
- lines: List[Tuple[int, OrderLine]]
+ lines: List[OrderLine]
):
if not user_is_valid(user):
user = None
@@ -614,7 +627,12 @@ def order_returned_event(
type=OrderEvents.FULFILLMENT_RETURNED,
user=user,
app=app,
- parameters={"lines": _lines_per_quantity_to_line_object_list(returned_lines)},
+ parameters={
+ "lines": [
+ _line_per_quantity_to_line_object(quantity, line)
+ for quantity, line in returned_lines
+ ]
+ },
)
@@ -623,7 +641,7 @@ def fulfillment_replaced_event(
order: Order,
user: UserType,
app: AppType,
- replaced_lines: List[Tuple[int, OrderLine]],
+ replaced_lines: List[OrderLine],
):
if not user_is_valid(user):
user = None
@@ -653,7 +671,10 @@ def fulfillment_refunded_event(
user=user,
app=app,
parameters={
- "lines": _lines_per_quantity_to_line_object_list(refunded_lines),
+ "lines": [
+ _line_per_quantity_to_line_object(quantity, line)
+ for quantity, line in refunded_lines
+ ],
"amount": amount,
"shipping_costs_included": shipping_costs_included,
},
diff --git a/saleor/order/tests/test_notifications.py b/saleor/order/tests/test_notifications.py
index d6b0751377..326fcf3a7c 100644
--- a/saleor/order/tests/test_notifications.py
+++ b/saleor/order/tests/test_notifications.py
@@ -11,6 +11,7 @@ from ...core.notify_events import NotifyEventType
from ...core.prices import quantize_price
from ...discount import DiscountValueType
from ...graphql.core.utils import to_global_id_or_none
+from ...graphql.order.utils import OrderLineData
from ...order import notifications
from ...order.fetch import fetch_order_info
from ...plugins.manager import get_plugins_manager
@@ -389,11 +390,15 @@ def test_send_confirmation_emails_without_addresses_for_payment(
payment_dummy,
):
order = payment_dummy.order
+ line_data = OrderLineData(
+ variant_id=str(digital_content.product_variant.id),
+ variant=digital_content.product_variant,
+ quantity=1,
+ )
line = add_variant_to_order(
order,
- digital_content.product_variant,
- quantity=1,
+ line_data,
user=info.context.user,
app=info.context.app,
manager=info.context.plugins,
@@ -436,11 +441,15 @@ def test_send_confirmation_emails_without_addresses_for_order(
):
assert not order.lines.count()
+ line_data = OrderLineData(
+ variant_id=str(digital_content.product_variant.id),
+ variant=digital_content.product_variant,
+ quantity=1,
+ )
line = add_variant_to_order(
order,
- digital_content.product_variant,
- quantity=1,
+ line_data,
user=info.context.user,
app=info.context.app,
manager=info.context.plugins,
diff --git a/saleor/order/tests/test_order.py b/saleor/order/tests/test_order.py
index 45f21da5d9..7b20634c3c 100644
--- a/saleor/order/tests/test_order.py
+++ b/saleor/order/tests/test_order.py
@@ -16,6 +16,7 @@ from ...discount.models import (
)
from ...discount.utils import validate_voucher_in_order
from ...graphql.core.utils import to_global_id_or_none
+from ...graphql.order.utils import OrderLineData
from ...graphql.tests.utils import get_graphql_content
from ...payment import ChargeStatus
from ...payment.models import Payment
@@ -95,10 +96,11 @@ def test_add_variant_to_order_adds_line_for_new_variant(
variant = product.variants.get()
lines_before = order.lines.count()
settings.LANGUAGE_CODE = "fr"
+ line_data = OrderLineData(variant_id=str(variant.id), variant=variant, quantity=1)
+
add_variant_to_order(
order,
- variant,
- 1,
+ line_data,
info.context.user,
info.context.app,
info.context.plugins,
@@ -135,11 +137,11 @@ def test_add_variant_to_order_adds_line_for_new_variant_on_sale(
sale.variants.add(variant)
lines_before = order.lines.count()
settings.LANGUAGE_CODE = "fr"
+ line_data = OrderLineData(variant_id=str(variant.id), variant=variant, quantity=1)
add_variant_to_order(
order,
- variant,
- 1,
+ line_data,
info.context.user,
info.context.app,
info.context.plugins,
@@ -179,10 +181,11 @@ def test_add_variant_to_draft_order_adds_line_for_variant_with_price_0(
lines_before = order.lines.count()
settings.LANGUAGE_CODE = "fr"
+ line_data = OrderLineData(variant_id=str(variant.id), variant=variant, quantity=1)
+
add_variant_to_order(
order,
- variant,
- 1,
+ line_data,
info.context.user,
info.context.app,
info.context.plugins,
@@ -207,10 +210,10 @@ def test_add_variant_to_order_not_allocates_stock_for_new_variant(
stock_before = get_quantity_allocated_for_stock(stock)
+ line_data = OrderLineData(variant_id=str(variant.id), variant=variant, quantity=1)
add_variant_to_order(
order_with_lines,
- variant,
- 1,
+ line_data,
info.context.user,
info.context.app,
info.context.plugins,
@@ -228,11 +231,13 @@ def test_add_variant_to_order_edits_line_for_existing_variant(
variant = existing_line.variant
lines_before = order_with_lines.lines.count()
line_quantity_before = existing_line.quantity
+ line_data = OrderLineData(
+ line_id=str(existing_line.pk), variant=variant, quantity=1
+ )
add_variant_to_order(
order_with_lines,
- variant,
- 1,
+ line_data,
info.context.user,
info.context.app,
info.context.plugins,
@@ -255,11 +260,13 @@ def test_add_variant_to_order_not_allocates_stock_for_existing_variant(
stock_before = get_quantity_allocated_for_stock(stock)
quantity_before = existing_line.quantity
quantity_unfulfilled_before = existing_line.quantity_unfulfilled
+ line_data = OrderLineData(
+ line_id=str(existing_line.id), variant=variant, quantity=1
+ )
add_variant_to_order(
order_with_lines,
- variant,
- 1,
+ line_data,
info.context.user,
info.context.app,
info.context.plugins,
@@ -537,10 +544,11 @@ def test_calculate_order_weight(order_with_lines):
def test_order_weight_add_more_variant(order_with_lines, info, site_settings):
variant = order_with_lines.lines.first().variant
+ line_data = OrderLineData(variant_id=str(variant.id), variant=variant, quantity=2)
+
add_variant_to_order(
order_with_lines,
- variant,
- 2,
+ line_data,
info.context.user,
info.context.app,
info.context.plugins,
@@ -555,11 +563,11 @@ def test_order_weight_add_more_variant(order_with_lines, info, site_settings):
def test_order_weight_add_new_variant(order_with_lines, product, info, site_settings):
variant = product.variants.first()
+ line_data = OrderLineData(variant_id=str(variant.id), variant=variant, quantity=2)
add_variant_to_order(
order_with_lines,
- variant,
- 2,
+ line_data,
info.context.user,
info.context.app,
info.context.plugins,
@@ -602,10 +610,11 @@ def test_get_order_weight_non_existing_product(
# Removing product should not affect order's weight
order = order_with_lines
variant = product.variants.first()
+ line_data = OrderLineData(variant_id=str(variant.id), variant=variant, quantity=1)
+
add_variant_to_order(
order,
- variant,
- 1,
+ line_data,
info.context.user,
info.context.app,
info.context.plugins,
diff --git a/saleor/order/tests/test_order_utils.py b/saleor/order/tests/test_order_utils.py
index 1f0253be55..6a53103edb 100644
--- a/saleor/order/tests/test_order_utils.py
+++ b/saleor/order/tests/test_order_utils.py
@@ -7,6 +7,7 @@ from ...checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ...discount import DiscountValueType, OrderDiscountType
from ...giftcard import GiftCardEvents
from ...giftcard.models import GiftCardEvent
+from ...graphql.order.utils import OrderLineData
from ...plugins.manager import get_plugins_manager
from .. import OrderStatus
from ..events import OrderEvents
@@ -269,10 +270,12 @@ def test_add_variant_to_order(
undiscounted_total_price = undiscounted_unit_price * quantity
# when
+ line_data = OrderLineData(
+ variant_id=str(variant.id), variant=variant, quantity=quantity
+ )
line = add_variant_to_order(
order,
- variant,
- quantity,
+ line_data,
customer_user,
None,
manager,
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index a027b34122..91ea1760a2 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -197,111 +197,89 @@ def update_order_status(order):
@traced_atomic_transaction()
-def add_variant_to_order(
+def create_order_line(
order,
- variant,
- quantity,
- user,
- app,
+ line_data,
manager,
site_settings,
discounts=None,
allocate_stock=False,
):
- """Add total_quantity of variant to order.
-
- Returns an order line the variant was added to.
- """
channel = order.channel
- try:
- line = order.lines.get(variant=variant)
- old_quantity = line.quantity
- new_quantity = old_quantity + quantity
- line_info = OrderLineInfo(line=line, quantity=old_quantity)
- change_order_line_quantity(
- user,
- app,
- line_info,
- old_quantity,
- new_quantity,
- channel.slug,
- manager=manager,
- send_event=False,
+ variant = line_data.variant
+ quantity = line_data.quantity
+
+ product = variant.product
+ collections = product.collections.all()
+ channel_listing = variant.channel_listings.get(channel=channel)
+
+ # vouchers are not applied for new lines in unconfirmed/draft orders
+ untaxed_unit_price = variant.get_price(
+ product, collections, channel, channel_listing, discounts
+ )
+ if not discounts:
+ untaxed_undiscounted_price = untaxed_unit_price
+ else:
+ untaxed_undiscounted_price = variant.get_price(
+ product, collections, channel, channel_listing, []
)
- except OrderLine.DoesNotExist:
- product = variant.product
- collections = product.collections.all()
- channel_listing = variant.channel_listings.get(channel=channel)
-
- # vouchers are not applied for new lines in unconfirmed/draft orders
- untaxed_unit_price = variant.get_price(
- product, collections, channel, channel_listing, discounts
+ unit_price = TaxedMoney(net=untaxed_unit_price, gross=untaxed_unit_price)
+ undiscounted_unit_price = TaxedMoney(
+ net=untaxed_undiscounted_price, gross=untaxed_undiscounted_price
+ )
+ total_price = unit_price * quantity
+ undiscounted_total_price = undiscounted_unit_price * quantity
+
+ product_name = str(product)
+ variant_name = str(variant)
+ translated_product_name = str(product.translated)
+ translated_variant_name = str(variant.translated)
+ if translated_product_name == product_name:
+ translated_product_name = ""
+ if translated_variant_name == variant_name:
+ translated_variant_name = ""
+ line = order.lines.create(
+ product_name=product_name,
+ variant_name=variant_name,
+ translated_product_name=translated_product_name,
+ translated_variant_name=translated_variant_name,
+ product_sku=variant.sku,
+ product_variant_id=variant.get_global_id(),
+ is_shipping_required=variant.is_shipping_required(),
+ is_gift_card=variant.is_gift_card(),
+ quantity=quantity,
+ unit_price=unit_price,
+ undiscounted_unit_price=undiscounted_unit_price,
+ base_unit_price=untaxed_unit_price,
+ undiscounted_base_unit_price=untaxed_undiscounted_price,
+ total_price=total_price,
+ undiscounted_total_price=undiscounted_total_price,
+ variant=variant,
+ )
+
+ manager.update_taxes_for_order_lines(order, list(order.lines.all()))
+
+ unit_discount = line.undiscounted_unit_price - line.unit_price
+ if unit_discount.gross:
+ sale_id = get_sale_id_applied_as_a_discount(
+ product=product,
+ price=channel_listing.price,
+ discounts=discounts,
+ collections=collections,
+ channel=channel,
+ variant_id=variant.id,
)
- if not discounts:
- untaxed_undiscounted_price = untaxed_unit_price
+ taxes_included_in_prices = site_settings.include_taxes_in_prices
+ if taxes_included_in_prices:
+ discount_amount = unit_discount.gross
else:
- untaxed_undiscounted_price = variant.get_price(
- product, collections, channel, channel_listing, []
- )
- unit_price = TaxedMoney(net=untaxed_unit_price, gross=untaxed_unit_price)
- undiscounted_unit_price = TaxedMoney(
- net=untaxed_undiscounted_price, gross=untaxed_undiscounted_price
- )
- total_price = unit_price * quantity
- undiscounted_total_price = undiscounted_unit_price * quantity
-
- product_name = str(product)
- variant_name = str(variant)
- translated_product_name = str(product.translated)
- translated_variant_name = str(variant.translated)
- if translated_product_name == product_name:
- translated_product_name = ""
- if translated_variant_name == variant_name:
- translated_variant_name = ""
- line = order.lines.create(
- product_name=product_name,
- variant_name=variant_name,
- translated_product_name=translated_product_name,
- translated_variant_name=translated_variant_name,
- product_sku=variant.sku,
- product_variant_id=variant.get_global_id(),
- is_shipping_required=variant.is_shipping_required(),
- is_gift_card=variant.is_gift_card(),
- quantity=quantity,
- unit_price=unit_price,
- undiscounted_unit_price=undiscounted_unit_price,
- base_unit_price=untaxed_unit_price,
- undiscounted_base_unit_price=untaxed_undiscounted_price,
- total_price=total_price,
- undiscounted_total_price=undiscounted_total_price,
- variant=variant,
+ discount_amount = unit_discount.net
+ line.unit_discount = discount_amount
+ line.unit_discount_value = discount_amount.amount
+ line.unit_discount_reason = (
+ f"Sale: {graphene.Node.to_global_id('Sale', sale_id)}"
)
-
- manager.update_taxes_for_order_lines(order, list(order.lines.all()))
-
- unit_discount = line.undiscounted_unit_price - line.unit_price
- if unit_discount.gross:
- sale_id = get_sale_id_applied_as_a_discount(
- product=product,
- price=channel_listing.price,
- discounts=discounts,
- collections=collections,
- channel=channel,
- variant_id=variant.id,
- )
- taxes_included_in_prices = site_settings.include_taxes_in_prices
- if taxes_included_in_prices:
- discount_amount = unit_discount.gross
- else:
- discount_amount = unit_discount.net
- line.unit_discount = discount_amount
- line.unit_discount_value = discount_amount.amount
- line.unit_discount_reason = (
- f"Sale: {graphene.Node.to_global_id('Sale', sale_id)}"
- )
- line.sale_id = (
- graphene.Node.to_global_id("Sale", sale_id) if sale_id else None
- )
+ line.sale_id = graphene.Node.to_global_id("Sale", sale_id) if sale_id else None
line.save(
update_fields=[
@@ -329,6 +307,66 @@ def add_variant_to_order(
return line
+@traced_atomic_transaction()
+def add_variant_to_order(
+ order,
+ line_data,
+ user,
+ app,
+ manager,
+ site_settings,
+ discounts=None,
+ allocate_stock=False,
+):
+ """Add total_quantity of variant to order.
+
+ Returns an order line the variant was added to.
+ """
+ channel = order.channel
+
+ if line_data.line_id:
+ line = order.lines.get(pk=line_data.line_id)
+ old_quantity = line.quantity
+ new_quantity = old_quantity + line_data.quantity
+ line_info = OrderLineInfo(line=line, quantity=old_quantity)
+ change_order_line_quantity(
+ user,
+ app,
+ line_info,
+ old_quantity,
+ new_quantity,
+ channel.slug,
+ manager=manager,
+ send_event=False,
+ )
+
+ if allocate_stock:
+ increase_allocations(
+ [
+ OrderLineInfo(
+ line=line,
+ quantity=line_data.quantity,
+ variant=line_data.variant,
+ warehouse_pk=None,
+ )
+ ],
+ channel.slug,
+ manager=manager,
+ )
+
+ return line
+
+ if line_data.variant_id:
+ return create_order_line(
+ order,
+ line_data,
+ manager,
+ site_settings,
+ discounts,
+ allocate_stock,
+ )
+
+
def add_gift_cards_to_order(
checkout_info: "CheckoutInfo",
order: Order,
@@ -471,14 +509,19 @@ def change_order_line_quantity(
def create_order_event(line, user, app, quantity_diff):
if quantity_diff > 0:
events.order_removed_products_event(
- order=line.order, user=user, app=app, order_lines=[(quantity_diff, line)]
+ order=line.order,
+ user=user,
+ app=app,
+ order_lines=[line],
+ quantity_diff=quantity_diff,
)
elif quantity_diff < 0:
events.order_added_products_event(
order=line.order,
user=user,
app=app,
- order_lines=[(quantity_diff * -1, line)],
+ order_lines=[line],
+ quantity_diff=quantity_diff * -1,
)
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 459d7a195d..3babbcac0f 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -323,6 +323,16 @@ def checkout_with_item(checkout, product):
return checkout
+def checkout_with_same_items_in_multiple_lines(checkout, product):
+ variant = product.variants.first()
+ checkout_info = fetch_checkout_info(checkout, [], [], get_plugins_manager())
+ add_variant_to_checkout(checkout_info, variant, 1)
+ add_variant_to_checkout(checkout_info, variant, 1, force_new_line=True)
+ checkout.save()
+ return checkout
+
+
@pytest.fixture
def checkout_with_item_and_voucher_specific_products(
checkout_with_item, voucher_specific_product_type
@@ -3988,7 +3998,8 @@ def order_with_lines_and_events(order_with_lines, staff_user):
order=order_with_lines,
user=staff_user,
app=None,
- order_lines=[(1, order_with_lines.lines.first())],
+ order_lines=[order_with_lines.lines.first()],
+ quantity_diff=1,
)
return order_with_lines