Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Custom prices (#9393)
Iga Karbowiak620569b3a246
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7b0e0795ec..83e3cb789a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -22,6 +22,9 @@ All notable, unreleased changes to this project will be documented in this file.- Add `language_code` field to webhook payload for `Order`, `Checkout` and `Customer` - #9433 by @rafalp- Add handling webhook payload via GraphQL subscriptions (#9394) @jakubkuc- Fix access to own resources by App - #9425 by @korycins+- Introduce custom prices - #9393 by @IKarbowiak+ - Add `HANDLE_CHECKOUTS` permission (only for apps)+# 3.1.7diff --git a/saleor/checkout/base_calculations.py b/saleor/checkout/base_calculations.pyindex 5ef9f2561d..c16aea195b 100644--- a/saleor/checkout/base_calculations.py+++ b/saleor/checkout/base_calculations.py@@ -46,6 +46,7 @@ def calculate_base_line_unit_price(channel,line_info.channel_listing,discounts or [],+ line_info.line.price_override,)if not discounts:@@ -57,6 +58,7 @@ def calculate_base_line_unit_price(channel,line_info.channel_listing,[],+ line_info.line.price_override,)if line_info.voucher and not line_info.voucher.apply_once_per_order:diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.pyindex f9ca8732ca..e74a331445 100644--- a/saleor/checkout/complete_checkout.py+++ b/saleor/checkout/complete_checkout.py@@ -15,7 +15,7 @@ import graphenefrom django.contrib.sites.models import Sitefrom django.core.exceptions import ValidationErrorfrom django.db import transaction-from prices import TaxedMoney+from prices import Money, TaxedMoneyfrom ..account.error_codes import AccountErrorCodefrom ..account.models import Address, User@@ -199,9 +199,16 @@ def _create_line_for_order(unit_price_data.price_with_sale,)+ price_override = checkout_line_info.line.price_override+ channel_listing = checkout_line_info.channel_listing+ price = (+ channel_listing.price+ if price_override is None+ else Money(price_override, channel_listing.currency)+ )sale_id = get_sale_id_applied_as_a_discount(product=checkout_line_info.product,- price=checkout_line_info.channel_listing.price,+ price=price,discounts=discounts,collections=checkout_line_info.collections,channel=checkout_info.channel,diff --git a/saleor/checkout/fetch.py b/saleor/checkout/fetch.pyindex 924243e16b..6e11c10298 100644--- a/saleor/checkout/fetch.py+++ b/saleor/checkout/fetch.py@@ -334,6 +334,7 @@ def _apply_voucher_on_product(channel=channel,channel_listing=line_info.channel_listing,discounts=discounts,+ price_override=line_info.line.price_override,)if not cheapest_line or cheapest_line_price > line_price:cheapest_line_price = line_pricediff --git a/saleor/checkout/migrations/0040_add_handle_checkouts_permission.py b/saleor/checkout/migrations/0040_add_handle_checkouts_permission.pyindex d187f10978..241b56a057 100644--- a/saleor/checkout/migrations/0040_add_handle_checkouts_permission.py+++ b/saleor/checkout/migrations/0040_add_handle_checkouts_permission.py@@ -4,7 +4,7 @@ from django.core.management.sql import emit_post_migrate_signalfrom django.db import migrations-def assing_permissions(apps, schema_editor):+def assign_permissions(apps, schema_editor):# force post signal as permissions are created in post migrate signals# related Django issue https://code.djangoproject.com/ticket/23422emit_post_migrate_signal(2, False, "default")@@ -51,5 +51,5 @@ class Migration(migrations.Migration):),},),- migrations.RunPython(assing_permissions, migrations.RunPython.noop),+ migrations.RunPython(assign_permissions, migrations.RunPython.noop),]diff --git a/saleor/checkout/migrations/0041_checkoutline_price_override.py b/saleor/checkout/migrations/0041_checkoutline_price_override.pynew file mode 100644index 0000000000..18e1c3b291--- /dev/null+++ b/saleor/checkout/migrations/0041_checkoutline_price_override.py@@ -0,0 +1,20 @@+# Generated by Django 3.2.12 on 2022-03-09 12:17++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("checkout", "0040_add_handle_checkouts_permission"),+ ]++ operations = [+ migrations.AddField(+ model_name="checkoutline",+ name="price_override",+ field=models.DecimalField(+ blank=True, decimal_places=3, max_digits=12, null=True+ ),+ ),+ ]diff --git a/saleor/checkout/models.py b/saleor/checkout/models.pyindex e70fd8374d..11257347ff 100644--- a/saleor/checkout/models.py+++ b/saleor/checkout/models.py@@ -185,6 +185,12 @@ class CheckoutLine(models.Model):"product.ProductVariant", related_name="+", on_delete=models.CASCADE)quantity = models.PositiveIntegerField(validators=[MinValueValidator(1)])+ price_override = models.DecimalField(+ max_digits=settings.DEFAULT_MAX_DIGITS,+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,+ blank=True,+ null=True,+ )class Meta:ordering = ("id",)diff --git a/saleor/checkout/tests/test_base_calculations.py b/saleor/checkout/tests/test_base_calculations.pyindex cf3dd3c015..7ce35b3e99 100644--- a/saleor/checkout/tests/test_base_calculations.py+++ b/saleor/checkout/tests/test_base_calculations.py@@ -38,6 +38,30 @@ def test_calculate_base_line_unit_price(checkout_with_single_item):assert prices_data.price_with_discounts == expected_price+def test_calculate_base_line_unit_price_with_custom_price(checkout_with_single_item):+ # given+ line = checkout_with_single_item.lines.first()+ price_override = Decimal("12.22")+ line.price_override = price_override+ line.save(update_fields=["price_override"])++ checkout_lines_info, _ = fetch_checkout_lines(checkout_with_single_item)+ checkout_line_info = checkout_lines_info[0]+ assert not checkout_line_info.voucher++ # when+ prices_data = calculate_base_line_unit_price(+ checkout_line_info, checkout_with_single_item.channel, discounts=[]+ )++ # then+ currency = checkout_line_info.channel_listing.currency+ expected_price = Money(price_override, currency)+ assert prices_data.undiscounted_price == expected_price+ assert prices_data.price_with_sale == expected_price+ assert prices_data.price_with_discounts == expected_price++def test_calculate_base_line_unit_price_with_variant_on_sale(checkout_with_single_item, discount_info, category):@@ -72,8 +96,48 @@ def test_calculate_base_line_unit_price_with_variant_on_sale(channel=checkout_with_single_item.channel,variant_id=variant.id,)- sale_discount_amount = sale_discount(expected_undiscounted_price)- expected_price = expected_undiscounted_price - sale_discount_amount+ expected_price = sale_discount(expected_undiscounted_price)++ assert prices_data.undiscounted_price == expected_undiscounted_price+ assert prices_data.price_with_sale == expected_price+ assert prices_data.price_with_discounts == expected_price+++def test_calculate_base_line_unit_price_with_variant_on_sale_custom_price(+ checkout_with_single_item, discount_info, category+):+ # given+ line = checkout_with_single_item.lines.first()+ price_override = Decimal("20.00")+ line.price_override = price_override+ line.save(update_fields=["price_override"])++ checkout_lines_info, _ = fetch_checkout_lines(checkout_with_single_item)+ checkout_line_info = checkout_lines_info[0]+ assert not checkout_line_info.voucher+ variant = checkout_line_info.variant+ # set category on sale+ variant.product.category = category+ variant.product.save()+ checkout_line_info.product = variant.product++ # when+ prices_data = calculate_base_line_unit_price(+ checkout_line_info, checkout_with_single_item.channel, discounts=[discount_info]+ )++ # then+ currency = checkout_line_info.channel_listing.currency+ expected_undiscounted_price = Money(price_override, currency)+ product_collections = set(pc.id for pc in checkout_line_info.collections)+ _, sale_discount = get_product_discount_on_sale(+ product=checkout_line_info.product,+ product_collections=product_collections,+ discount=discount_info,+ channel=checkout_with_single_item.channel,+ variant_id=variant.id,+ )+ expected_price = sale_discount(expected_undiscounted_price)assert prices_data.undiscounted_price == expected_undiscounted_priceassert prices_data.price_with_sale == expected_price@@ -119,6 +183,42 @@ def test_calculate_base_line_unit_price_with_fixed_voucher(assert prices_data.price_with_discounts == expected_price - voucher_amount+def test_calculate_base_line_unit_price_with_fixed_voucher_custom_prices(+ checkout_with_single_item, voucher, channel_USD+):+ # given+ checkout_line = checkout_with_single_item.lines.first()+ price_override = Decimal("20.00")+ checkout_line.price_override = price_override+ checkout_line.save(update_fields=["price_override"])++ voucher.products.add(checkout_line.variant.product)+ voucher.type = VoucherType.SPECIFIC_PRODUCT+ voucher.save()++ voucher_amount = Money(Decimal(3), checkout_with_single_item.currency)+ voucher_channel_listing = voucher.channel_listings.get(channel=channel_USD)+ voucher_channel_listing.discount = voucher_amount+ voucher_channel_listing.save()++ checkout_with_single_item.voucher_code = voucher.code+ checkout_lines_info, _ = fetch_checkout_lines(checkout_with_single_item)+ checkout_line_info = checkout_lines_info[0]+ assert checkout_line_info.voucher++ # when+ prices_data = calculate_base_line_unit_price(+ checkout_line_info, checkout_with_single_item.channel, discounts=[]+ )++ # then+ currency = checkout_line_info.channel_listing.currency+ expected_price = Money(price_override, currency)+ assert prices_data.undiscounted_price == expected_price+ assert prices_data.price_with_sale == expected_price+ assert prices_data.price_with_discounts == expected_price - voucher_amount++def test_calculate_base_line_unit_price_with_percentage_voucher(checkout_with_single_item, voucher, channel_USD):@@ -160,6 +260,46 @@ def test_calculate_base_line_unit_price_with_percentage_voucher(assert prices_data.price_with_discounts == expected_price - expected_voucher_amount+def test_calculate_base_line_unit_price_with_percentage_voucher_custom_prices(+ checkout_with_single_item, voucher, channel_USD+):+ # given+ checkout_line = checkout_with_single_item.lines.first()+ price_override = Decimal("20.00")+ checkout_line.price_override = price_override+ checkout_line.save(update_fields=["price_override"])++ voucher.products.add(checkout_line.variant.product)+ voucher.type = VoucherType.SPECIFIC_PRODUCT+ voucher.discount_value_type = DiscountValueType.PERCENTAGE+ voucher.save()++ voucher_percent_value = Decimal(10)+ voucher_channel_listing = voucher.channel_listings.get(channel=channel_USD)+ voucher_channel_listing.discount_value = voucher_percent_value+ voucher_channel_listing.save()++ checkout_with_single_item.voucher_code = voucher.code+ checkout_lines_info, _ = fetch_checkout_lines(checkout_with_single_item)+ checkout_line_info = checkout_lines_info[0]+ assert checkout_line_info.voucher++ # when+ prices_data = calculate_base_line_unit_price(+ checkout_line_info, checkout_with_single_item.channel, discounts=[]+ )++ # then+ currency = checkout_line_info.channel_listing.currency+ expected_price = Money(price_override, currency)+ expected_voucher_amount = Money(+ price_override * voucher_percent_value / 100, checkout_with_single_item.currency+ )+ assert prices_data.undiscounted_price == expected_price+ assert prices_data.price_with_sale == expected_price+ assert prices_data.price_with_discounts == expected_price - expected_voucher_amount++def test_calculate_base_line_unit_price_with_discounts_apply_once_per_order(checkout_with_single_item, voucher, channel_USD):@@ -202,6 +342,45 @@ def test_calculate_base_line_unit_price_with_discounts_apply_once_per_order(assert prices_data.price_with_discounts == expected_price+def test_calculate_base_line_unit_price_with_discounts_once_per_order_custom_prices(+ checkout_with_single_item, voucher, channel_USD+):+ # given+ checkout_line = checkout_with_single_item.lines.first()+ price_override = Decimal("20.00")+ checkout_line.price_override = price_override+ checkout_line.save(update_fields=["price_override"])++ voucher.products.add(checkout_line.variant.product)+ voucher.type = VoucherType.SPECIFIC_PRODUCT+ voucher.apply_once_per_order = True+ voucher.discount_value_type = DiscountValueType.PERCENTAGE+ voucher.save()++ voucher_percent_value = Decimal(10)+ voucher_channel_listing = voucher.channel_listings.get(channel=channel_USD)+ voucher_channel_listing.discount_value = voucher_percent_value+ voucher_channel_listing.save()++ checkout_with_single_item.voucher_code = voucher.code+ checkout_lines_info, _ = fetch_checkout_lines(checkout_with_single_item)+ checkout_line_info = checkout_lines_info[0]+ assert checkout_line_info.voucher++ # when+ prices_data = calculate_base_line_unit_price(+ checkout_line_info, checkout_with_single_item.channel, discounts=[]+ )++ # then+ currency = checkout_line_info.channel_listing.currency+ expected_price = Money(price_override, currency)+ assert prices_data.undiscounted_price == expected_price+ assert prices_data.price_with_sale == expected_price+ # apply once per order is applied when calculating line total.+ assert prices_data.price_with_discounts == expected_price++def test_calculate_base_line_unit_price_with_variant_on_sale_and_voucher(checkout_with_single_item, discount_info, category, voucher, channel_USD):diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex 982bf3f4b9..6b8e6bb9ab 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -45,6 +45,8 @@ from .models import Checkout, CheckoutLineif TYPE_CHECKING:# flake8: noqa+ from decimal import Decimal+from prices import TaxedMoneyfrom ..account.models import Address@@ -99,6 +101,7 @@ def add_variant_to_checkout(checkout_info: "CheckoutInfo",variant: product_models.ProductVariant,quantity: int = 1,+ price_override: Optional["Decimal"] = None,replace: bool = False,check_quantity: bool = True,):@@ -136,7 +139,10 @@ def add_variant_to_checkout(line = Noneelif line is None:line = checkout.lines.create(- checkout=checkout, variant=variant, quantity=new_quantity+ checkout=checkout,+ variant=variant,+ quantity=new_quantity,+ price_override=price_override,)elif new_quantity > 0:line.quantity = new_quantity@@ -152,7 +158,7 @@ def calculate_checkout_quantity(lines: Iterable["CheckoutLineInfo"]):def add_variants_to_checkout(checkout,variants,- quantities,+ checkout_lines_data,channel_slug,replace=False,replace_reservations=False,@@ -168,28 +174,21 @@ def add_variants_to_checkout(checkout_lines = checkout.lines.select_related("variant")variant_ids_in_lines = {line.variant_id: line for line in checkout_lines}- to_create = []- to_update = []- to_delete = []- for variant, quantity in zip(variants, quantities):- if variant.pk in variant_ids_in_lines:- line = variant_ids_in_lines[variant.pk]- if quantity > 0:- if replace:- line.quantity = quantity- else:- line.quantity += quantity- to_update.append(line)- else:- to_delete.append(line)- elif quantity > 0:- to_create.append(- CheckoutLine(checkout=checkout, variant=variant, quantity=quantity)- )+ 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+ )if to_delete:CheckoutLine.objects.filter(pk__in=[line.pk for line in to_delete]).delete()if to_update:- CheckoutLine.objects.bulk_update(to_update, ["quantity"])+ CheckoutLine.objects.bulk_update(to_update, ["quantity", "price_override"])if to_create:CheckoutLine.objects.bulk_create(to_create)@@ -213,6 +212,51 @@ 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]+ if line_data.quantity_to_update:+ quantity = line_data.quantity+ if quantity > 0:+ if replace:+ line.quantity = quantity+ else:+ line.quantity += quantity+ to_update.append(line)+ if line_data.custom_price_to_update:+ if line not in to_delete:+ line.price_override = line_data.custom_price+ 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]+ 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:+ if line_data.quantity > 0:+ to_create.append(+ CheckoutLine(+ checkout=checkout,+ variant=variant,+ quantity=line_data.quantity,+ price_override=line_data.custom_price,+ )+ )++def _check_new_checkout_address(checkout, address, address_type):"""Check if and address in checkout has changed and if to remove old one."""if address_type == AddressType.BILLING:diff --git a/saleor/core/management/commands/populatedb.py b/saleor/core/management/commands/populatedb.pyindex de28de50ad..6ed96d1005 100644--- a/saleor/core/management/commands/populatedb.py+++ b/saleor/core/management/commands/populatedb.py@@ -10,6 +10,7 @@ from ....account.utils import create_superuserfrom ...utils.random_data import (add_address_to_admin,create_channels,+ create_checkout_with_custom_prices,create_checkout_with_preorders,create_gift_cards,create_menus,@@ -114,6 +115,8 @@ class Command(BaseCommand):self.stdout.write(msg)for msg in create_checkout_with_preorders():self.stdout.write(msg)+ for msg in create_checkout_with_custom_prices():+ self.stdout.write(msg)if options["createsuperuser"]:credentials = {diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.pyindex 51483bfef7..81586c0770 100644--- a/saleor/core/utils/random_data.py+++ b/saleor/core/utils/random_data.py@@ -1703,3 +1703,18 @@ 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}"+++def create_checkout_with_custom_prices():+ channel = Channel.objects.get(currency_code="USD")+ 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())+ 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}."+ )diff --git a/saleor/graphql/checkout/mutations/checkout_create.py b/saleor/graphql/checkout/mutations/checkout_create.pyindex 047d0b1bf9..b0fa90015a 100644--- a/saleor/graphql/checkout/mutations/checkout_create.py+++ b/saleor/graphql/checkout/mutations/checkout_create.py@@ -12,27 +12,39 @@ from ....warehouse.reservations import get_reservation_length, is_reservation_enfrom ...account.i18n import I18nMixinfrom ...account.types import AddressInputfrom ...channel.utils import clean_channel-from ...core.descriptions import DEPRECATED_IN_3X_FIELD+from ...core.descriptions import ADDED_IN_31, DEPRECATED_IN_3X_FIELD, PREVIEW_FEATUREfrom ...core.enums import LanguageCodeEnumfrom ...core.mutations import ModelMutation+from ...core.scalars import PositiveDecimalfrom ...core.types import CheckoutError, NonNullListfrom ...core.validators import validate_variants_available_in_channelfrom ...product.types import ProductVariantfrom ..types import Checkoutfrom .utils import (check_lines_quantity,- group_quantity_by_variants,+ check_permissions_for_custom_prices,+ group_quantity_and_custom_prices_by_variants,validate_variants_are_published,validate_variants_available_for_purchase,)if TYPE_CHECKING:from ....account.models import Address+ from .utils import CheckoutLineDataclass CheckoutLineInput(graphene.InputObjectType):quantity = graphene.Int(required=True, description="The number of items purchased.")variant_id = graphene.ID(required=True, description="ID of the product variant.")+ price = PositiveDecimal(+ required=False,+ description=(+ f"{ADDED_IN_31} 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. "+ f"{PREVIEW_FEATURE}"+ ),+ )class CheckoutCreateInput(graphene.InputObjectType):@@ -88,7 +100,8 @@ class CheckoutCreate(ModelMutation, I18nMixin):@classmethoddef clean_checkout_lines(cls, info, lines, country, channel- ) -> Tuple[List[product_models.ProductVariant], List[int]]:+ ) -> Tuple[List[product_models.ProductVariant], List["CheckoutLineData"]]:+ check_permissions_for_custom_prices(info.context.app, lines)variant_ids = [line["variant_id"] for line in lines]variants = cls.get_nodes_or_error(variant_ids,@@ -99,7 +112,7 @@ class CheckoutCreate(ModelMutation, I18nMixin):),)- quantities = group_quantity_by_variants(lines)+ checkout_lines_data = group_quantity_and_custom_prices_by_variants(lines)variant_db_ids = {variant.id for variant in variants}validate_variants_available_for_purchase(variant_db_ids, channel.id)@@ -107,6 +120,7 @@ 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]check_lines_quantity(variants,quantities,@@ -115,7 +129,7 @@ class CheckoutCreate(ModelMutation, I18nMixin):info.context.site.settings.limit_quantity_per_checkout,check_reservations=is_reservation_enabled(info.context.site.settings),)- return variants, quantities+ return variants, checkout_lines_data@classmethoddef retrieve_shipping_address(cls, user, data: dict) -> Optional["Address"]:@@ -159,7 +173,7 @@ class CheckoutCreate(ModelMutation, I18nMixin):if lines:(cleaned_input["variants"],- cleaned_input["quantities"],+ cleaned_input["lines_data"],) = cls.clean_checkout_lines(info,lines,@@ -192,12 +206,12 @@ class CheckoutCreate(ModelMutation, I18nMixin):# Create checkout lineschannel = cleaned_input["channel"]variants = cleaned_input.get("variants")- quantities = cleaned_input.get("quantities")- if variants and quantities:+ checkout_lines_data = cleaned_input.get("lines_data")+ if variants and checkout_lines_data:add_variants_to_checkout(instance,variants,- quantities,+ checkout_lines_data,channel.slug,info.context.site.settings.limit_quantity_per_checkout,reservation_length=get_reservation_length(info.context),diff --git a/saleor/graphql/checkout/mutations/checkout_lines_add.py b/saleor/graphql/checkout/mutations/checkout_lines_add.pyindex dd51897a9f..9e19b10967 100644--- a/saleor/graphql/checkout/mutations/checkout_lines_add.py+++ b/saleor/graphql/checkout/mutations/checkout_lines_add.py@@ -21,8 +21,9 @@ from ..types import Checkoutfrom .checkout_create import CheckoutLineInputfrom .utils import (check_lines_quantity,+ check_permissions_for_custom_prices,get_checkout_by_token,- group_quantity_by_variants,+ group_quantity_and_custom_prices_by_variants,update_checkout_shipping_method_if_invalid,validate_variants_are_published,validate_variants_available_for_purchase,@@ -62,11 +63,12 @@ class CheckoutLinesAdd(BaseMutation):cls,info,variants,- quantities,+ checkout_lines_data,country,channel_slug,lines=None,):+ quantities = [line_data.quantity for line_data in checkout_lines_data]check_lines_quantity(variants,quantities,@@ -83,7 +85,7 @@ class CheckoutLinesAdd(BaseMutation):info,checkout,variants,- quantities,+ checkout_lines_data,checkout_info,lines,manager,@@ -95,7 +97,7 @@ class CheckoutLinesAdd(BaseMutation):cls.validate_checkout_lines(info,variants,- quantities,+ checkout_lines_data,checkout.get_country(),channel_slug,lines=lines,@@ -103,8 +105,8 @@ class CheckoutLinesAdd(BaseMutation):variants_ids_to_validate = {variant.id- for variant, quantity in zip(variants, quantities)- if quantity != 0+ for variant, line_data in zip(variants, checkout_lines_data)+ if line_data.quantity_to_update and line_data.quantity != 0}# validate variant only when line quantity is bigger than 0@@ -121,11 +123,11 @@ class CheckoutLinesAdd(BaseMutation):variants_ids_to_validate, checkout.channel_id)- if variants and quantities:+ if variants and checkout_lines_data:checkout = add_variants_to_checkout(checkout,variants,- quantities,+ checkout_lines_data,channel_slug,replace=replace,replace_reservations=True,@@ -154,6 +156,7 @@ class CheckoutLinesAdd(BaseMutation):validate_one_of_args_is_in_mutation(CheckoutErrorCode, "checkout_id", checkout_id, "token", token)+ check_permissions_for_custom_prices(info.context.app, lines)if token:checkout = get_checkout_by_token(token)@@ -168,7 +171,7 @@ class CheckoutLinesAdd(BaseMutation):variant_ids = [line.get("variant_id") for line in lines]variants = cls.get_nodes_or_error(variant_ids, "variant_id", ProductVariant)- input_quantities = group_quantity_by_variants(lines)+ checkout_lines_data = group_quantity_and_custom_prices_by_variants(lines)shipping_channel_listings = checkout.channel.shipping_method_listings.all()checkout_info = fetch_checkout_info(@@ -180,7 +183,7 @@ class CheckoutLinesAdd(BaseMutation):info,checkout,variants,- input_quantities,+ checkout_lines_data,checkout_info,lines,manager,diff --git a/saleor/graphql/checkout/mutations/checkout_lines_update.py b/saleor/graphql/checkout/mutations/checkout_lines_update.pyindex 6ab480b4b4..fa341e1e70 100644--- a/saleor/graphql/checkout/mutations/checkout_lines_update.py+++ b/saleor/graphql/checkout/mutations/checkout_lines_update.py@@ -1,15 +1,47 @@import graphene+from django.forms import ValidationError+from ....checkout.error_codes import CheckoutErrorCodefrom ....warehouse.reservations import is_reservation_enabled-from ...core.types import CheckoutError+from ...core.descriptions import DEPRECATED_IN_3X_INPUT+from ...core.scalars import UUID+from ...core.types import CheckoutError, NonNullListfrom ..types import Checkout+from .checkout_create import CheckoutLineInputfrom .checkout_lines_add import CheckoutLinesAddfrom .utils import check_lines_quantity+class CheckoutLineUpdateInput(CheckoutLineInput):+ quantity = graphene.Int(+ required=False,+ description=(+ "The number of items purchased. "+ "Optional for apps, required for any other users."+ ),+ )++class CheckoutLinesUpdate(CheckoutLinesAdd):checkout = graphene.Field(Checkout, description="An updated checkout.")+ class Arguments:+ checkout_id = graphene.ID(+ description=(+ f"The ID of the checkout. {DEPRECATED_IN_3X_INPUT} Use token instead."+ ),+ required=False,+ )+ token = UUID(description="Checkout token.", required=False)+ lines = NonNullList(+ CheckoutLineUpdateInput,+ required=True,+ description=(+ "A list of checkout lines, each containing information about "+ "an item in the checkout."+ ),+ )+class Meta:description = "Updates checkout line in the existing checkout."error_type_class = CheckoutError@@ -20,13 +52,20 @@ class CheckoutLinesUpdate(CheckoutLinesAdd):cls,info,variants,- quantities,+ checkout_lines_data,country,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)+check_lines_quantity(- variants,+ variants_to_validate,quantities,country,channel_slug,@@ -37,6 +76,48 @@ class CheckoutLinesUpdate(CheckoutLinesAdd):check_reservations=is_reservation_enabled(info.context.site.settings),)+ @classmethod+ def clean_input(+ cls,+ info,+ checkout,+ variants,+ checkout_lines_data,+ checkout_info,+ lines,+ manager,+ discounts,+ replace,+ ):+ # if the requestor is not app, the quantity is required for all lines+ if not info.context.app:+ if any(+ [+ line_data.quantity_to_update is False+ for line_data in checkout_lines_data+ ]+ ):+ raise ValidationError(+ {+ "quantity": ValidationError(+ "The quantity is required for all lines.",+ code=CheckoutErrorCode.REQUIRED.value,+ )+ }+ )++ return super().clean_input(+ info,+ checkout,+ variants,+ checkout_lines_data,+ checkout_info,+ lines,+ manager,+ discounts,+ replace,+ )+@classmethoddef perform_mutation(cls, root, info, lines, checkout_id=None, token=None):return super().perform_mutation(diff --git a/saleor/graphql/checkout/mutations/utils.py b/saleor/graphql/checkout/mutations/utils.pyindex 01c4d978fa..831282ec47 100644--- a/saleor/graphql/checkout/mutations/utils.py+++ b/saleor/graphql/checkout/mutations/utils.py@@ -1,7 +1,9 @@import datetimeimport uuidfrom collections import defaultdict-from typing import Any, Dict, Iterable, List, Optional, Union+from dataclasses import dataclass+from decimal import Decimal+from typing import Any, Dict, Iterable, List, Optional, Union, castimport graphenefrom django.core.exceptions import ObjectDoesNotExist, ValidationError@@ -15,7 +17,8 @@ from ....checkout.utils import (clear_delivery_method,is_shipping_required,)-from ....core.exceptions import InsufficientStock+from ....core.exceptions import InsufficientStock, PermissionDenied+from ....core.permissions import CheckoutPermissionsfrom ....product import models as product_modelsfrom ....product.models import ProductChannelListingfrom ....shipping import interface as shipping_interface@@ -25,6 +28,14 @@ from ....warehouse.availability import check_stock_and_preorder_quantity_bulkERROR_DOES_NOT_SHIP = "This checkout doesn't need shipping"+@dataclass+class CheckoutLineData:+ quantity: int = 0+ quantity_to_update: bool = False+ custom_price: Optional[Decimal] = None+ custom_price_to_update: bool = False++def clean_delivery_method(checkout_info: "CheckoutInfo",lines: Iterable[CheckoutLineInfo],@@ -213,10 +224,33 @@ def get_checkout_by_token(token: uuid.UUID, qs=None):return checkout-def group_quantity_by_variants(lines: List[Dict[str, Any]]) -> List[int]:- variant_quantity_map: Dict[str, int] = defaultdict(int)+def group_quantity_and_custom_prices_by_variants(+ lines: List[Dict[str, Any]]+) -> List[CheckoutLineData]:+ variant_checkout_line_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]+ 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())+- for quantity, variant_id in (line.values() for line in lines):- variant_quantity_map[variant_id] += quantity+def check_permissions_for_custom_prices(app, lines):+ """Raise PermissionDenied when custom price is changed by user or app without perm.- return list(variant_quantity_map.values())+ Checkout line custom price can be changed only by app with+ handle checkout permission.+ """+ if any(["price" in line for line in lines]) and (+ not app or not app.has_perm(CheckoutPermissions.HANDLE_CHECKOUTS)+ ):+ raise PermissionDenied(permissions=[CheckoutPermissions.HANDLE_CHECKOUTS])diff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.pyindex c8765fc97a..174b7245c3 100644--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py@@ -13,6 +13,7 @@ from .....plugins.manager import get_plugins_managerfrom .....product.models import ProductVariant, ProductVariantChannelListingfrom .....warehouse.models import Stockfrom ....tests.utils import get_graphql_content+from ...mutations.utils import CheckoutLineDataFRAGMENT_PRICE = """fragment Price on TaxedMoney {@@ -579,7 +580,7 @@ def test_add_billing_address_to_checkout(MUTATION_CHECKOUT_LINES_UPDATE = (FRAGMENT_CHECKOUT_LINE+ """- mutation updateCheckoutLine($token: UUID, $lines: [CheckoutLineInput!]!){+ mutation updateCheckoutLine($token: UUID, $lines: [CheckoutLineUpdateInput!]!){checkoutLinesUpdate(token: $token, lines: $lines) {checkout {id@@ -700,7 +701,15 @@ def test_update_checkout_lines_with_reservations(add_variants_to_checkout(checkout,variants,- [2] * 10,+ [+ CheckoutLineData(+ quantity=2,+ quantity_to_update=True,+ custom_price=None,+ custom_price_to_update=False,+ )+ ]+ * 10,channel_USD.slug,replace_reservations=True,reservation_length=5,diff --git a/saleor/graphql/checkout/tests/deprecated/test_checkout_lines_update.py b/saleor/graphql/checkout/tests/deprecated/test_checkout_lines_update.pyindex 204340e724..849421fe92 100644--- a/saleor/graphql/checkout/tests/deprecated/test_checkout_lines_update.py+++ b/saleor/graphql/checkout/tests/deprecated/test_checkout_lines_update.py@@ -11,7 +11,7 @@ from ...mutations.utils import update_checkout_shipping_method_if_invalidMUTATION_CHECKOUT_LINES_UPDATE = """mutation checkoutLinesUpdate(- $checkoutId: ID, $token: UUID, $lines: [CheckoutLineInput!]!) {+ $checkoutId: ID, $token: UUID, $lines: [CheckoutLineUpdateInput!]!) {checkoutLinesUpdate(checkoutId: $checkoutId, token: $token, lines: $lines) {checkout {tokendiff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.pyindex 3ea07409ef..b89f503650 100644--- a/saleor/graphql/checkout/tests/test_checkout.py+++ b/saleor/graphql/checkout/tests/test_checkout.py@@ -18,7 +18,7 @@ from prices import Moneyfrom ....account.models import Userfrom ....channel.utils import DEPRECATION_WARNING_MESSAGE-from ....checkout import AddressType, calculations+from ....checkout import AddressType, base_calculations, calculationsfrom ....checkout.checkout_cleaner import (clean_checkout_payment,clean_checkout_shipping,@@ -649,6 +649,136 @@ def test_checkout_create(api_client, stock, graphql_address_data, channel_USD):assert not Reservation.objects.exists()+def test_checkout_create_with_custom_price(+ app_api_client,+ stock,+ graphql_address_data,+ channel_USD,+ permission_handle_checkouts,+):+ """Ensure that app with handle checkouts permission can set custom price."""+ variant = stock.product_variant+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)+ test_email = "[email protected]"+ shipping_address = graphql_address_data+ price = 12.25+ variables = {+ "checkoutInput": {+ "channel": channel_USD.slug,+ "lines": [{"quantity": 1, "variantId": variant_id, "price": price}],+ "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]+ )+ content = get_graphql_content(response)["data"]["checkoutCreate"]++ new_checkout = Checkout.objects.first()+ assert new_checkout is not None+ checkout_data = content["checkout"]+ assert checkout_data["token"] == str(new_checkout.token)+ assert new_checkout.lines.count() == 1+ checkout_line = new_checkout.lines.first()+ assert checkout_line.variant == variant+ assert checkout_line.quantity == 1+ assert checkout_line.price_override == price+++def test_checkout_create_with_custom_price_duplicated_items(+ app_api_client,+ stock,+ graphql_address_data,+ channel_USD,+ permission_handle_checkouts,+):+ """Ensure that when the same item with a custom price is provided multiple times,+ the price from the last occurrence will be set."""+ variant = stock.product_variant+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)+ test_email = "[email protected]"+ shipping_address = graphql_address_data+ price_1 = 12.25+ price_2 = 20.25+ variables = {+ "checkoutInput": {+ "channel": channel_USD.slug,+ "lines": [+ {"quantity": 1, "variantId": variant_id, "price": price_1},+ {"quantity": 1, "variantId": variant_id, "price": price_2},+ ],+ "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]+ )+ content = get_graphql_content(response)["data"]["checkoutCreate"]++ new_checkout = Checkout.objects.first()+ assert new_checkout is not None+ checkout_data = content["checkout"]+ assert checkout_data["token"] == str(new_checkout.token)+ assert new_checkout.lines.count() == 1+ checkout_line = new_checkout.lines.first()+ assert checkout_line.variant == variant+ assert checkout_line.quantity == 2+ assert checkout_line.price_override == price_2+++def test_checkout_create_with_custom_price_by_app_no_perm(+ app_api_client, stock, graphql_address_data, channel_USD+):+ """Ensure that app without handle checkouts permission cannot set custom price."""+ variant = stock.product_variant+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)+ test_email = "[email protected]"+ shipping_address = graphql_address_data+ price = 12.25+ variables = {+ "checkoutInput": {+ "channel": channel_USD.slug,+ "lines": [{"quantity": 1, "variantId": variant_id, "price": price}],+ "email": test_email,+ "shippingAddress": shipping_address,+ }+ }+ assert not Checkout.objects.exists()+ response = app_api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)+ assert_no_permission(response)+++def test_checkout_create_with_custom_price_by_staff_with_handle_checkouts(+ staff_api_client,+ stock,+ graphql_address_data,+ channel_USD,+ permission_handle_checkouts,+):+ """Ensure that staff with handle checkouts permission cannot set custom price."""+ staff_api_client.user.user_permissions.add(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+ price = 12.25+ variables = {+ "checkoutInput": {+ "channel": channel_USD.slug,+ "lines": [{"quantity": 1, "variantId": variant_id, "price": price}],+ "email": test_email,+ "shippingAddress": shipping_address,+ }+ }+ assert not Checkout.objects.exists()+ response = staff_api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)+ assert_no_permission(response)++def test_checkout_create_no_email(api_client, stock, graphql_address_data, channel_USD):"""Create checkout object using GraphQL API."""variant = stock.product_variant@@ -3469,8 +3599,7 @@ def test_fetch_checkout_invalid_token(user_api_client, channel_USD):assert data is None-def test_checkout_prices(user_api_client, checkout_with_item):- query = """+QUERY_CHECKOUT_PRICES = """query getCheckout($token: UUID!) {checkout(token: $token) {token,@@ -3496,7 +3625,11 @@ def test_checkout_prices(user_api_client, checkout_with_item):}}}- """+"""+++def test_checkout_prices(user_api_client, checkout_with_item):+ query = QUERY_CHECKOUT_PRICESvariables = {"token": str(checkout_with_item.token)}response = user_api_client.post_graphql(query, variables)content = get_graphql_content(response)@@ -3522,6 +3655,40 @@ def test_checkout_prices(user_api_client, checkout_with_item):assert data["subtotalPrice"]["gross"]["amount"] == (subtotal.gross.amount)+def test_checkout_prices_checkout_with_custom_prices(+ user_api_client, checkout_with_item+):+ query = QUERY_CHECKOUT_PRICES++ checkout_line = checkout_with_item.lines.first()+ price_override = Decimal("20.00")+ checkout_line.price_override = price_override+ checkout_line.save(update_fields=["price_override"])++ variables = {"token": str(checkout_with_item.token)}++ response = user_api_client.post_graphql(query, variables)++ content = get_graphql_content(response)+ data = content["data"]["checkout"]+ assert data["token"] == str(checkout_with_item.token)+ assert len(data["lines"]) == checkout_with_item.lines.count()+ manager = get_plugins_manager()+ lines, _ = fetch_checkout_lines(checkout_with_item)+ checkout_info = fetch_checkout_info(checkout_with_item, lines, [], manager)+ shipping_price = base_calculations.base_checkout_delivery_price(+ checkout_info, lines+ )+ assert (+ data["totalPrice"]["gross"]["amount"]+ == checkout_line.quantity * price_override + shipping_price.gross.amount+ )+ assert (+ data["subtotalPrice"]["gross"]["amount"]+ == checkout_line.quantity * price_override+ )++MUTATION_UPDATE_SHIPPING_METHOD = """mutation checkoutShippingMethodUpdate($token: UUID, $shippingMethodId: ID!){diff --git a/saleor/graphql/checkout/tests/test_checkout_lines.py b/saleor/graphql/checkout/tests/test_checkout_lines.pyindex b1754e361a..f5c50ab837 100644--- a/saleor/graphql/checkout/tests/test_checkout_lines.py+++ b/saleor/graphql/checkout/tests/test_checkout_lines.py@@ -9,16 +9,17 @@ from django.utils import timezonefrom ....checkout.error_codes import CheckoutErrorCodefrom ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines-from ....checkout.models import Checkout+from ....checkout.models import Checkout, CheckoutLinefrom ....checkout.utils import add_variant_to_checkout, calculate_checkout_quantityfrom ....plugins.manager import get_plugins_managerfrom ....product.models import ProductChannelListingfrom ....warehouse import WarehouseClickAndCollectOptionfrom ....warehouse.models import Reservation, Stockfrom ....warehouse.tests.utils import get_available_quantity_for_stock-from ...tests.utils import get_graphql_content+from ...tests.utils import assert_no_permission, get_graphql_contentfrom ..mutations.utils import (- group_quantity_by_variants,+ CheckoutLineData,+ group_quantity_and_custom_prices_by_variants,update_checkout_shipping_method_if_invalid,)@@ -235,6 +236,124 @@ def test_checkout_lines_add_existing_variant(user_api_client, checkout_with_itemassert checkout.last_change != previous_last_change+def test_checkout_lines_add_custom_price(+ app_api_client, checkout, stock, permission_handle_checkouts+):+ variant = stock.product_variant+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ price = Decimal("13.11")++ variables = {+ "token": checkout.token,+ "lines": [{"variantId": variant_id, "quantity": 1, "price": price}],+ "channelSlug": checkout.channel.slug,+ }+ response = app_api_client.post_graphql(+ MUTATION_CHECKOUT_LINES_ADD,+ variables,+ permissions=[permission_handle_checkouts],+ )+ content = get_graphql_content(response)+ data = content["data"]["checkoutLinesAdd"]+ assert not data["errors"]+ checkout.refresh_from_db()+ line = checkout.lines.latest("pk")+ assert line.variant == variant+ assert line.quantity == 1+ assert line.price_override == price+++def test_checkout_lines_add_existing_variant_with_custom_price(+ app_api_client, checkout_with_item, permission_handle_checkouts+):+ checkout = checkout_with_item+ line = checkout.lines.first()+ variant_id = graphene.Node.to_global_id("ProductVariant", line.variant.pk)+ price = Decimal("13.11")++ variables = {+ "token": checkout.token,+ "lines": [{"variantId": variant_id, "quantity": 7, "price": price}],+ "channelSlug": checkout.channel.slug,+ }+ response = app_api_client.post_graphql(+ MUTATION_CHECKOUT_LINES_ADD,+ variables,+ permissions=[permission_handle_checkouts],+ )+ content = get_graphql_content(response)+ data = content["data"]["checkoutLinesAdd"]+ assert not data["errors"]+ checkout.refresh_from_db()+ line = checkout.lines.latest("pk")+ assert line.quantity == 10+ assert line.price_override == price+++def test_checkout_lines_add_existing_variant_override_previous_custom_price(+ app_api_client, checkout_with_item, permission_handle_checkouts+):+ checkout = checkout_with_item+ line = checkout.lines.first()+ line.price_override = 8.22+ line.save(update_fields=["price_override"])++ variant_id = graphene.Node.to_global_id("ProductVariant", line.variant.pk)+ price = Decimal("13.11")++ variables = {+ "token": checkout.token,+ "lines": [{"variantId": variant_id, "quantity": 7, "price": price}],+ "channelSlug": checkout.channel.slug,+ }+ response = app_api_client.post_graphql(+ MUTATION_CHECKOUT_LINES_ADD,+ variables,+ permissions=[permission_handle_checkouts],+ )+ content = get_graphql_content(response)+ data = content["data"]["checkoutLinesAdd"]+ assert not data["errors"]+ checkout.refresh_from_db()+ line = checkout.lines.latest("pk")+ assert line.quantity == 10+ assert line.price_override == price+++def test_checkout_lines_add_custom_price_app_no_perm(app_api_client, checkout, stock):+ variant = stock.product_variant+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ price = Decimal("13.11")++ variables = {+ "token": checkout.token,+ "lines": [{"variantId": variant_id, "quantity": 1, "price": price}],+ "channelSlug": checkout.channel.slug,+ }+ response = app_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)+ assert_no_permission(response)+++def test_checkout_lines_add_custom_price_permission_denied_for_staff_user(+ staff_api_client, checkout, stock, permission_handle_checkouts+):+ variant = stock.product_variant+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ price = Decimal("13.11")++ variables = {+ "token": checkout.token,+ "lines": [{"variantId": variant_id, "quantity": 1, "price": price}],+ "channelSlug": checkout.channel.slug,+ }+ response = staff_api_client.post_graphql(+ MUTATION_CHECKOUT_LINES_ADD,+ variables,+ permissions=[permission_handle_checkouts],+ )+ assert_no_permission(response)++def test_checkout_lines_add_existing_variant_over_allowed_stock(user_api_client, checkout_with_item):@@ -625,7 +744,7 @@ def test_checkout_lines_invalid_variant_id(user_api_client, checkout, stock):MUTATION_CHECKOUT_LINES_UPDATE = """mutation checkoutLinesUpdate(- $token: UUID, $lines: [CheckoutLineInput!]!) {+ $token: UUID, $lines: [CheckoutLineUpdateInput!]!) {checkoutLinesUpdate(token: $token, lines: $lines) {checkout {id@@ -779,11 +898,11 @@ def test_checkout_lines_update_against_reserved_stock(assert data["errors"][0]["field"] == "quantity"checkout.refresh_from_db()- lines, _ = fetch_checkout_lines(checkout)assert checkout.lines.count() == 1line = checkout.lines.first()assert line.variant == variantassert line.quantity == 3+ lines, _ = fetch_checkout_lines(checkout)assert calculate_checkout_quantity(lines) == 3reservation.refresh_from_db()assert Reservation.objects.count() == 1@@ -850,6 +969,272 @@ def test_checkout_lines_update_other_lines_reservations_expirations(reservation.refresh_from_db()+def test_checkout_lines_update_quantity_and_custom_price(+ app_api_client, checkout_with_item, permission_handle_checkouts+):+ 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++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ price = Decimal("22.22")++ variables = {+ "token": checkout_with_item.token,+ "lines": [{"variantId": variant_id, "quantity": 1, "price": price}],+ }+ response = app_api_client.post_graphql(+ MUTATION_CHECKOUT_LINES_UPDATE,+ variables,+ permissions=[permission_handle_checkouts],+ )+ content = get_graphql_content(response)++ data = content["data"]["checkoutLinesUpdate"]+ assert not data["errors"]+ checkout.refresh_from_db()+ assert checkout.lines.count() == 1+ line = checkout.lines.first()+ assert line.variant == variant+ assert line.quantity == 1+ assert line.price_override == price+ lines, _ = fetch_checkout_lines(checkout)+ assert calculate_checkout_quantity(lines) == 1+++def test_checkout_lines_update_custom_price(+ app_api_client, checkout_with_item, permission_handle_checkouts+):+ 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+ previous_quantity = line.quantity++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ price = Decimal("22.22")++ variables = {+ "token": checkout_with_item.token,+ "lines": [{"variantId": variant_id, "price": price}],+ }+ response = app_api_client.post_graphql(+ MUTATION_CHECKOUT_LINES_UPDATE,+ variables,+ permissions=[permission_handle_checkouts],+ )+ content = get_graphql_content(response)++ data = content["data"]["checkoutLinesUpdate"]+ assert not data["errors"]+ checkout.refresh_from_db()+ assert checkout.lines.count() == 1+ line = checkout.lines.first()+ assert line.variant == variant+ assert line.quantity == previous_quantity+ assert line.price_override == price+ lines, _ = fetch_checkout_lines(checkout)+ assert calculate_checkout_quantity(lines) == 3+++def test_checkout_lines_update_with_custom_price_override_existing_price(+ app_api_client, checkout_with_item, permission_handle_checkouts+):+ checkout = checkout_with_item+ lines, _ = fetch_checkout_lines(checkout)+ assert checkout.lines.count() == 1+ assert calculate_checkout_quantity(lines) == 3+ line = checkout.lines.first()+ line.price_override = Decimal("10.12")+ line.save(update_fields=["price_override"])+ variant = line.variant+ assert line.quantity == 3++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ price = Decimal("22.10")++ variables = {+ "token": checkout_with_item.token,+ "lines": [{"variantId": variant_id, "quantity": 1, "price": price}],+ }+ response = app_api_client.post_graphql(+ MUTATION_CHECKOUT_LINES_UPDATE,+ variables,+ permissions=[permission_handle_checkouts],+ )+ content = get_graphql_content(response)++ data = content["data"]["checkoutLinesUpdate"]+ assert not data["errors"]+ checkout.refresh_from_db()+ assert checkout.lines.count() == 1+ line = checkout.lines.first()+ assert line.variant == variant+ assert line.quantity == 1+ assert line.price_override == price+ lines, _ = fetch_checkout_lines(checkout)+ assert calculate_checkout_quantity(lines) == 1+++def test_checkout_lines_update_clear_custom_price(+ app_api_client, checkout_with_item, permission_handle_checkouts+):+ checkout = checkout_with_item+ lines, _ = fetch_checkout_lines(checkout)+ assert checkout.lines.count() == 1+ assert calculate_checkout_quantity(lines) == 3+ line = checkout.lines.first()+ line.price_override = Decimal("10.12")+ line.save(update_fields=["price_override"])+ variant = line.variant+ assert line.quantity == 3++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ variables = {+ "token": checkout_with_item.token,+ "lines": [{"variantId": variant_id, "quantity": 1, "price": None}],+ }+ response = app_api_client.post_graphql(+ MUTATION_CHECKOUT_LINES_UPDATE,+ variables,+ permissions=[permission_handle_checkouts],+ )+ content = get_graphql_content(response)++ data = content["data"]["checkoutLinesUpdate"]+ assert not data["errors"]+ checkout.refresh_from_db()+ assert checkout.lines.count() == 1+ line = checkout.lines.first()+ assert line.variant == variant+ assert line.quantity == 1+ assert line.price_override is None+ lines, _ = fetch_checkout_lines(checkout)+ assert calculate_checkout_quantity(lines) == 1+++def test_checkout_lines_update_set_quantity_to_0_then_update_customer_price(+ app_api_client, checkout_with_item, permission_handle_checkouts+):+ """Ensure an error is not raised and the line is deleted when the line quantity+ is set to 0 firstly and then the custom price is changed."""++ checkout = checkout_with_item+ lines, _ = fetch_checkout_lines(checkout)+ assert checkout.lines.count() == 1+ assert calculate_checkout_quantity(lines) == 3+ line = checkout.lines.first()+ line.price_override = Decimal("10.12")+ line.save(update_fields=["price_override"])+ variant = line.variant+ assert line.quantity == 3++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ variables = {+ "token": checkout_with_item.token,+ "lines": [+ {"variantId": variant_id, "quantity": 0},+ {"variantId": variant_id, "price": 10},+ ],+ }+ response = app_api_client.post_graphql(+ MUTATION_CHECKOUT_LINES_UPDATE,+ variables,+ permissions=[permission_handle_checkouts],+ )+ content = get_graphql_content(response)++ data = content["data"]["checkoutLinesUpdate"]+ assert not data["errors"]+ checkout.refresh_from_db()+ assert checkout.lines.count() == 0+ with pytest.raises(CheckoutLine.DoesNotExist):+ line.refresh_from_db()+++def test_checkout_lines_update_with_custom_price_by_app_no_perm(+ app_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++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ price = Decimal("22.22")++ variables = {+ "token": checkout_with_item.token,+ "lines": [{"variantId": variant_id, "quantity": 1, "price": price}],+ }+ response = app_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)+ assert_no_permission(response)+++def test_checkout_lines_update_with_custom_price_raise_permission_denied_for_staff(+ staff_api_client, checkout_with_item, permission_handle_checkouts+):+ 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++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)+ price = Decimal("22.22")++ variables = {+ "token": checkout_with_item.token,+ "lines": [{"variantId": variant_id, "quantity": 1, "price": price}],+ }+ response = staff_api_client.post_graphql(+ MUTATION_CHECKOUT_LINES_UPDATE,+ variables,+ permissions=[permission_handle_checkouts],+ )+ assert_no_permission(response)+++def test_checkout_lines_update_no_quantity_provided(+ 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++ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ variables = {+ "token": checkout_with_item.token,+ "lines": [{"variantId": variant_id}],+ }+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)+ content = get_graphql_content(response)++ data = content["data"]["checkoutLinesUpdate"]+ errors = data["errors"]+ assert len(errors) == 1+ assert errors[0]["code"] == CheckoutErrorCode.REQUIRED.name+ assert errors[0]["field"] == "quantity"++def test_checkout_lines_update_with_unavailable_variant(user_api_client, checkout_with_item):@@ -1299,41 +1684,70 @@ def tests_checkout_lines_delete_invalid_lines_ids(user_api_client, checkout_with[([- {"quantity": 6, "variantId": "abc"},- {"quantity": 6, "variantId": "abc"},- {"quantity": 1, "variantId": "def"},- {"quantity": 1, "variantId": "def"},+ {"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,+ ),],- [12, 2],),([- {"quantity": 8, "variantId": "ghi"},- {"quantity": 2, "variantId": "ghi"},- {"quantity": 6, "variantId": "abc"},- {"quantity": 1, "variantId": "def"},- {"quantity": 6, "variantId": "abc"},- {"quantity": 1, "variantId": "def"},- {"quantity": 8, "variantId": "ghi"},- {"quantity": 2, "variantId": "ghi"},- {"quantity": 922, "variantId": "xyz"},- {"quantity": 6, "variantId": "abc"},- {"quantity": 1, "variantId": "def"},- {"quantity": 6, "variantId": "abc"},- {"quantity": 1, "variantId": "def"},- {"quantity": 1000, "variantId": "jkl"},- {"quantity": 999, "variantId": "zzz"},+ {"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]],- [20, 24, 4, 922, 1000, 999],),([- {"quantity": 100, "variantId": name}+ {"quantity": 100, "variant_id": name}for name in (l1 + l2 for l1 in "abcdef" for l2 in "ghijkl")],- [100] * 36,+ [+ CheckoutLineData(+ quantity=100,+ quantity_to_update=True,+ custom_price=None,+ custom_price_to_update=False,+ )+ ]+ * 36,),],)def test_group_by_variants(lines, expected):- assert expected == group_quantity_by_variants(lines)+ assert expected == group_quantity_and_custom_prices_by_variants(lines)diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 4da396860a..782f644bb3 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -9802,7 +9802,7 @@ type Mutation {"""A list of checkout lines, each containing information about an item in the checkout."""- lines: [CheckoutLineInput!]!+ lines: [CheckoutLineUpdateInput!]!"""Checkout token."""token: UUID@@ -14889,6 +14889,11 @@ input CheckoutLineInput {"""ID of the product variant."""variantId: ID!++ """+ New in Saleor 3.1. 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. Note: this feature is in a preview state and can be subject to changes at later point.+ """+ price: PositiveDecimal}"""@@ -14952,6 +14957,21 @@ type CheckoutLinesUpdate {errors: [CheckoutError!]!}+input CheckoutLineUpdateInput {+ """+ The number of items purchased. Optional for apps, required for any other users.+ """+ quantity: Int++ """ID of the product variant."""+ variantId: ID!++ """+ New in Saleor 3.1. 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. Note: this feature is in a preview state and can be subject to changes at later point.+ """+ price: PositiveDecimal+}+"""Remove a gift card or a voucher from a checkout."""type CheckoutRemovePromoCode {"""The checkout with the removed gift card or voucher."""diff --git a/saleor/product/models.py b/saleor/product/models.pyindex 2f125cef23..337709fe5f 100644--- a/saleor/product/models.py+++ b/saleor/product/models.py@@ -36,6 +36,7 @@ from django_prices.models import MoneyFieldfrom measurement.measures import Weightfrom mptt.managers import TreeManagerfrom mptt.models import MPTTModel+from prices import Moneyfrom versatileimagefield.fields import PPOIField, VersatileImageFieldfrom ..channel.models import Channel@@ -61,8 +62,9 @@ from . import ProductMediaTypes, ProductTypeKindif TYPE_CHECKING:# flake8: noqa+ from decimal import Decimal+from django.db.models import OrderBy- from prices import Moneyfrom ..account.models import Userfrom ..app.models import App@@ -612,11 +614,16 @@ class ProductVariant(SortableModel, ModelWithMetadata):channel: Channel,channel_listing: "ProductVariantChannelListing",discounts: Optional[Iterable[DiscountInfo]] = None,+ price_override: Optional["Decimal"] = None,) -> "Money":-+ price = (+ channel_listing.price+ if price_override is None+ else Money(price_override, channel_listing.currency)+ )return calculate_discounted_price(product=product,- price=channel_listing.price,+ price=price,discounts=discounts,collections=collections,channel=channel,diff --git a/saleor/webhook/serializers.py b/saleor/webhook/serializers.pyindex 98a0a9aad6..36089800fd 100644--- a/saleor/webhook/serializers.py+++ b/saleor/webhook/serializers.py@@ -27,8 +27,14 @@ def serialize_checkout_lines(channel_listing = line_info.channel_listingcollections = line_info.collectionsproduct = variant.product+ price_override = line_info.line.price_overridebase_price = variant.get_price(- product, collections, channel, channel_listing, discounts or []+ product,+ collections,+ channel,+ channel_listing,+ discounts or [],+ price_override,)data.append({diff --git a/saleor/webhook/tests/test_webhook_payloads.py b/saleor/webhook/tests/test_webhook_payloads.pyindex a887977a5d..e856cd7dec 100644--- a/saleor/webhook/tests/test_webhook_payloads.py+++ b/saleor/webhook/tests/test_webhook_payloads.py@@ -771,6 +771,23 @@ def test_generate_checkout_lines_payload(checkout_with_single_item):assert line["variant_id"] == variant.get_global_id()+def test_generate_checkout_lines_payload_custom_price(checkout_with_single_item):+ line = checkout_with_single_item.lines.first()+ price_override = Decimal("11.11")+ line.price_override = price_override+ line.save(update_fields=["price_override"])++ payload = json.loads(generate_checkout_payload(checkout_with_single_item))[0]+ assert payload.get("lines")++ variant = line.variant++ line_data = payload["lines"][0]+ assert line_data["sku"] == variant.sku+ assert line_data["variant_id"] == variant.get_global_id()+ assert line_data["base_price"] == str(price_override)++def test_generate_product_translation_payload(product_translation_fr):payload = generate_translation_payload(product_translation_fr)data = json.loads(payload)