Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add gift promotion (#15259)
Iga Karbowiake580e2df7557
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex af3f2310f9..573b5ba737 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,8 @@ All notable, unreleased changes to this project will be documented in this file.# 3.19.0 [Unreleased]### Highlights+- Introduce `order` promotion rules that allow applying discounts during checkout calculations when the checkout meets certain conditions. - #14696 by @IKarbowiak, @zedzior+- Introduce gift reward as `order` promotion rule reward - #15259 by @zedzior, @IKarbowiak### Breaking changes- Drop `OrderBulkCreateInput.voucher` field. Use `OrderBulkCreateInput.voucherCode` instead. - #14553 by @zedzior@@ -16,7 +18,6 @@ All notable, unreleased changes to this project will be documented in this file.- Add taxes to undiscounted prices - #14095 by @jakubkuc- Mark as deprecated: `ordersTotal`, `reportProductSales` and `homepageEvents` - #14806 by @8r2y5- Add `identifier` field to App graphql object. Identifier field is the same as Manifest.id field (explicit ID set by the app).-- Introduce `checkoutAndOrder` promotion rules that allow applying discounts during checkout calculations when the checkout meets certain conditions. - #14696 by @IKarbowiak, @zedzior### Saleor Appsdiff --git a/saleor/checkout/base_calculations.py b/saleor/checkout/base_calculations.pyindex 04292fd558..6d193dc704 100644--- a/saleor/checkout/base_calculations.py+++ b/saleor/checkout/base_calculations.py@@ -50,6 +50,7 @@ def calculate_base_line_total_price(The price includes catalogue promotions, specific product and applied once per ordervoucher discounts.The price does not include order promotions and the entire order vouchers.+ When the line is gift reward, the price is zero."""variant = line_info.variantcurrency = line_info.channel_listing.currencydiff --git a/saleor/checkout/calculations.py b/saleor/checkout/calculations.pyindex 6507de8bf1..79b94d8842 100644--- a/saleor/checkout/calculations.py+++ b/saleor/checkout/calculations.py@@ -1,6 +1,6 @@from collections.abc import Iterablefrom decimal import Decimal-from typing import TYPE_CHECKING, Optional+from typing import TYPE_CHECKING, Optional, castfrom django.conf import settingsfrom django.utils import timezone@@ -20,6 +20,7 @@ from ..tax.utils import (get_tax_calculation_strategy_for_checkout,normalize_tax_rate_for_db,)+from .fetch import find_checkout_line_infofrom .models import Checkoutfrom .payment_utils import update_checkout_payment_statuses@@ -134,21 +135,6 @@ def checkout_total(return quantize_price(checkout_info.checkout.total, currency)-def _find_checkout_line_info(- lines: Iterable["CheckoutLineInfo"],- checkout_line_info: "CheckoutLineInfo",-) -> "CheckoutLineInfo":- """Return checkout line info from lines parameter.-- The return value represents the updated version of checkout_line_info parameter.- """- return next(- line_info- for line_info in lines- if line_info.line.pk == checkout_line_info.line.pk- )--def checkout_line_total(*,manager: "PluginsManager",@@ -168,7 +154,7 @@ def checkout_line_total(lines=lines,address=address,)- checkout_line = _find_checkout_line_info(lines, checkout_line_info).line+ checkout_line = find_checkout_line_info(lines, checkout_line_info.line.id).linereturn quantize_price(checkout_line.total_price, currency)@@ -191,7 +177,7 @@ def checkout_line_unit_price(lines=lines,address=address,)- checkout_line = _find_checkout_line_info(lines, checkout_line_info).line+ checkout_line = find_checkout_line_info(lines, checkout_line_info.line.id).lineunit_price = checkout_line.total_price / checkout_line.quantityreturn quantize_price(unit_price, currency)@@ -214,7 +200,7 @@ def checkout_line_tax_rate(lines=lines,address=address,)- checkout_line_info = _find_checkout_line_info(lines, checkout_line_info)+ checkout_line_info = find_checkout_line_info(lines, checkout_line_info.line.id)return checkout_line_info.line.tax_rate@@ -246,6 +232,7 @@ def _fetch_checkout_prices_if_expired(charge_taxes = get_charge_taxes_for_checkout(checkout_info, lines)should_charge_tax = charge_taxes and not checkout.tax_exemption+ lines = cast(list, lines)create_or_update_discount_objects_from_promotion_for_checkout(checkout_info, lines)if prices_entered_with_tax:diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.pyindex c8a257cbc8..da8c39ab18 100644--- a/saleor/checkout/complete_checkout.py+++ b/saleor/checkout/complete_checkout.py@@ -30,7 +30,6 @@ from ..discount.models import CheckoutDiscount, NotApplicable, OrderLineDiscountfrom ..discount.utils import (get_sale_id,increase_voucher_usage,- prepare_promotion_discount_reason,release_voucher_code_usage,)from ..graphql.checkout.utils import (@@ -292,6 +291,7 @@ def _create_line_for_order(is_gift_card=variant.is_gift_card(),quantity=quantity,variant=variant,+ is_gift=checkout_line.is_gift,unit_price=unit_price, # money field not supported by mypy_django_pluginundiscounted_unit_price=undiscounted_unit_price, # money field not supported by mypy_django_plugin # noqa: E501undiscounted_total_price=undiscounted_total_price, # money field not supported by mypy_django_plugin # noqa: E501@@ -310,15 +310,12 @@ def _create_line_for_order(line_discounts = _create_order_line_discounts(checkout_line_info, line)if line_discounts:- # Currently only one promotion can be applied on the single line.- # This is temporary solution until the discount API is implemented.- # Ultimately, this info should be taken from the orderLineDiscount instances.-- promotion = checkout_line_info.rules_info[0].promotion- sale_id = get_sale_id(promotion)- line.sale_id = sale_id- promotion_discount_reason = prepare_promotion_discount_reason(- promotion, sale_id+ # We might have catalogue and gift predicate promotion so there might be more+ # than one sale_id.+ # The sale_id will be set only for the catalogue discount if exists.+ line.sale_id = _get_sale_id(line_discounts)+ promotion_discount_reason = " & ".join(+ [discount.reason for discount in line_discounts if discount.reason])unit_discount_reason = (f"{unit_discount_reason} & {promotion_discount_reason}"@@ -355,6 +352,13 @@ def _create_order_line_discounts(return line_discounts+def _get_sale_id(line_discounts: list[OrderLineDiscount]):+ for discount in line_discounts:+ if discount.type == DiscountType.PROMOTION:+ if rule := discount.promotion_rule:+ return get_sale_id(rule.promotion)++def _create_lines_for_order(manager: "PluginsManager",checkout_info: "CheckoutInfo",@@ -473,7 +477,10 @@ def _prepare_order_data()undiscounted_total = (sum(- [line.line.undiscounted_total_price for line in order_data["lines"]],+ [+ line_data.line.undiscounted_total_price+ for line_data in order_data["lines"]+ ],start=zero_taxed_money(taxed_total.currency),)+ shipping_total@@ -1233,7 +1240,7 @@ def _create_order_from_checkout(# update undiscounted order totalundiscounted_total = (sum(- [line.line.undiscounted_total_price for line in order_lines_info],+ [line_info.line.undiscounted_total_price for line_info in order_lines_info],start=zero_taxed_money(taxed_total.currency),)+ shipping_totaldiff --git a/saleor/checkout/error_codes.py b/saleor/checkout/error_codes.pyindex b5e6daebea..9c9ccd9493 100644--- a/saleor/checkout/error_codes.py+++ b/saleor/checkout/error_codes.py@@ -30,6 +30,8 @@ class CheckoutErrorCode(Enum):EMAIL_NOT_SET = "email_not_set"NO_LINES = "no_lines"INACTIVE_PAYMENT = "inactive_payment"+ NON_EDITABLE_GIFT_LINE = "non_editable_gift_line"+ NON_REMOVABLE_GIFT_LINE = "non_removable_gift_line"class OrderCreateFromCheckoutErrorCode(Enum):diff --git a/saleor/checkout/fetch.py b/saleor/checkout/fetch.pyindex 5a35eabdf9..72a2c42177 100644--- a/saleor/checkout/fetch.py+++ b/saleor/checkout/fetch.py@@ -61,6 +61,13 @@ class CheckoutLineInfo:voucher: Optional["Voucher"] = Nonedef get_promotion_discounts(self) -> list["CheckoutLineDiscount"]:+ return [+ discount+ for discount in self.discounts+ if discount.type in [DiscountType.PROMOTION, DiscountType.ORDER_PROMOTION]+ ]++ def get_catalogue_discounts(self) -> list["CheckoutLineDiscount"]:return [discountfor discount in self.discounts@@ -246,7 +253,7 @@ def fetch_checkout_lines("variant__channel_listings__channel","variant__channel_listings__variantlistingpromotionrule__promotion_rule__promotion__translations","variant__channel_listings__variantlistingpromotionrule__promotion_rule__translations",- "discounts",+ "discounts__promotion_rule__promotion",]if prefetch_variant_attributes:prefetch_related_fields.extend(@@ -274,8 +281,10 @@ def fetch_checkout_lines(variant, checkout.channel_id)translation_language_code = checkout.language_code- rules_info = fetch_variant_rules_info(- variant_channel_listing, translation_language_code+ rules_info = (+ fetch_variant_rules_info(variant_channel_listing, translation_language_code)+ if not line.is_gift+ else [])if not skip_recalculation and not _is_variant_valid(@@ -325,7 +334,7 @@ def fetch_checkout_lines(return lines_info, unavailable_variant_pksif voucher.type == VoucherType.SPECIFIC_PRODUCT or voucher.apply_once_per_order:voucher_info = fetch_voucher_info(voucher)- apply_voucher_to_checkout_line(voucher_info, checkout, lines_info)+ apply_voucher_to_checkout_line(voucher_info, lines_info)return lines_info, unavailable_variant_pks@@ -374,7 +383,6 @@ def _get_product_channel_listing(def apply_voucher_to_checkout_line(voucher_info: "VoucherInfo",- checkout: "Checkout",lines_info: Iterable[CheckoutLineInfo],):"""Attach voucher to valid checkout lines info.@@ -679,3 +687,14 @@ def update_checkout_info_delivery_method(checkout_info.delivery_method_info = get_delivery_method_info(delivery_method, checkout_info.shipping_address)+++def find_checkout_line_info(+ lines: Iterable["CheckoutLineInfo"],+ line_id: "UUID",+) -> "CheckoutLineInfo":+ """Return checkout line info from lines parameter.++ The return value represents the updated version of checkout_line_info parameter.+ """+ return next(line_info for line_info in lines if line_info.line.pk == line_id)diff --git a/saleor/checkout/migrations/0064_checkoutline_is_gift.py b/saleor/checkout/migrations/0064_checkoutline_is_gift.pynew file mode 100644index 0000000000..f62f044763--- /dev/null+++ b/saleor/checkout/migrations/0064_checkoutline_is_gift.py@@ -0,0 +1,25 @@+# Generated by Django 3.2.23 on 2024-01-19 14:02++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("checkout", "0063_checkout_base_total_and_subtotal"),+ ]++ operations = [+ migrations.AddField(+ model_name="checkoutline",+ name="is_gift",+ field=models.BooleanField(default=False),+ ),+ migrations.RunSQL(+ sql="""+ ALTER TABLE checkout_checkoutline+ ALTER COLUMN is_gift+ SET DEFAULT false;+ """,+ reverse_sql=migrations.RunSQL.noop,+ ),+ ]diff --git a/saleor/checkout/models.py b/saleor/checkout/models.pyindex be68eb11c9..664a5ca197 100644--- a/saleor/checkout/models.py+++ b/saleor/checkout/models.py@@ -287,6 +287,7 @@ class CheckoutLine(ModelWithMetadata):"product.ProductVariant", related_name="+", on_delete=models.CASCADE)quantity = models.PositiveIntegerField(validators=[MinValueValidator(1)])+ is_gift = models.BooleanField(default=False)price_override = models.DecimalField(max_digits=settings.DEFAULT_MAX_DIGITS,decimal_places=settings.DEFAULT_DECIMAL_PLACES,diff --git a/saleor/checkout/tests/test_base_calculations.py b/saleor/checkout/tests/test_base_calculations.pyindex 135595b3c4..33527b72bf 100644--- a/saleor/checkout/tests/test_base_calculations.py+++ b/saleor/checkout/tests/test_base_calculations.py@@ -942,3 +942,59 @@ def test_checkout_total_order_discount(- checkout.discount)assert total == expected_price+++def test_base_checkout_total_gift_promotion(+ checkout_with_item_and_gift_promotion, shipping_method+):+ # given+ manager = get_plugins_manager(allow_replica=False)+ checkout = checkout_with_item_and_gift_promotion+ channel = checkout.channel++ checkout.shipping_method = shipping_method+ checkout_lines, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, checkout_lines, manager)++ # when+ total = base_checkout_total(checkout_info, checkout_lines)++ # then+ variant = checkout.lines.get(is_gift=False).variant+ channel_listing = variant.channel_listings.get(channel=channel)+ net = variant.get_price(channel_listing)+ shipping_channel_listings = shipping_method.channel_listings.get(channel=channel)+ # the gift line price should not be included, the price should be equal to the sum+ # of the shipping price and the price of the variants that are not a gift+ expected_price = (+ net * checkout.lines.first().quantity + shipping_channel_listings.price+ )+ assert total == expected_price+++def test_checkout_total_gift_promotion(+ checkout_with_item_and_gift_promotion, shipping_method+):+ # given+ manager = get_plugins_manager(allow_replica=False)+ checkout = checkout_with_item_and_gift_promotion+ channel = checkout.channel++ checkout.shipping_method = shipping_method+ checkout_lines, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, checkout_lines, manager)++ # when+ total = checkout_total(checkout_info, checkout_lines)++ # then+ variant = checkout.lines.first().variant+ channel_listing = variant.channel_listings.get(channel=channel)+ net = variant.get_price(channel_listing)+ shipping_channel_listings = shipping_method.channel_listings.get(channel=channel)+ # the gift line price should not be included, the price should be equal to the sum+ # of the shipping price and the price of the variants that are not a gift+ expected_price = (+ net * checkout.lines.first().quantity + shipping_channel_listings.price+ )+ assert total == expected_pricediff --git a/saleor/checkout/tests/test_checkout.py b/saleor/checkout/tests/test_checkout.pyindex 8fc408fb64..7abf6d1de3 100644--- a/saleor/checkout/tests/test_checkout.py+++ b/saleor/checkout/tests/test_checkout.py@@ -1410,7 +1410,7 @@ def test_recalculate_checkout_discount_with_checkout_discount_voucher_not_applicassert not checkout.voucher_code-def test_recalculate_checkout_discount_with_checkout_discount_voucher_added(+def test_recalculate_checkout_discount_with_order_discount_voucher_added(checkout_with_item_and_order_discount,voucher_percentage,):@@ -1446,6 +1446,49 @@ def test_recalculate_checkout_discount_with_checkout_discount_voucher_added(checkout_discount.refresh_from_db()+def test_recalculate_checkout_discount_with_gift_reward_voucher_added(+ checkout_with_item_and_gift_promotion,+ voucher_percentage,+):+ # given+ checkout = checkout_with_item_and_gift_promotion+ gift_line = checkout.lines.get(is_gift=True)+ line_discount = gift_line.discounts.first()++ assert checkout.voucher_code is None+ channel = checkout.channel+ discount_value = voucher_percentage.channel_listings.get(+ channel=channel+ ).discount_value+ checkout.voucher_code = voucher_percentage.code+ checkout.save(update_fields=["voucher_code"])++ manager = get_plugins_manager(allow_replica=False)+ lines, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, manager)+ lines_count = len(lines)++ # when+ recalculate_checkout_discount(manager, checkout_info, lines)++ # then+ line_info = [line_info for line_info in lines if not line_info.line.is_gift][0]+ total_price = (+ line_info.variant.get_price(line_info.channel_listing) * line_info.line.quantity+ )++ checkout.refresh_from_db()+ assert checkout.discount_amount == total_price.amount * discount_value / 100+ assert checkout.discount_name == voucher_percentage.name+ assert checkout.voucher_code+ assert not checkout.discounts.all()+ assert len(lines) == lines_count - 1 == checkout.lines.count()+ with pytest.raises(line_discount._meta.model.DoesNotExist):+ line_discount.refresh_from_db()+ with pytest.raises(gift_line._meta.model.DoesNotExist):+ gift_line.refresh_from_db()++def test_recalculate_checkout_discount_voucher_not_applicable(checkout_with_voucher, voucher, channel_USD):@@ -1823,6 +1866,31 @@ def test_add_voucher_to_checkout_clears_order_promotion_discount(checkout_discount.refresh_from_db()+def test_add_voucher_to_checkout_clears_gift_reward(+ checkout_with_item_and_gift_promotion, voucher+):+ # given+ checkout = checkout_with_item_and_gift_promotion+ gift_line = checkout.lines.get(is_gift=True)+ line_discount = gift_line.discounts.first()+ assert checkout.voucher_code is None+ manager = get_plugins_manager(allow_replica=False)+ lines, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, manager)++ # when+ add_voucher_to_checkout(+ manager, checkout_info, lines, voucher, voucher.codes.first()+ )++ # then+ assert checkout.voucher_code == voucher.code+ with pytest.raises(line_discount._meta.model.DoesNotExist):+ line_discount.refresh_from_db()+ with pytest.raises(gift_line._meta.model.DoesNotExist):+ gift_line.refresh_from_db()++def test_get_last_active_payment(checkout_with_payments):# givenpayment = Payment.objects.create(diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex c1c0de6bed..5cec3662f5 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -21,10 +21,16 @@ from ..core.utils.promo_code import (from ..core.utils.translations import get_translationfrom ..discount import DiscountType, VoucherTypefrom ..discount.interface import VoucherInfo, fetch_voucher_info-from ..discount.models import CheckoutDiscount, NotApplicable, Voucher, VoucherCode+from ..discount.models import (+ CheckoutDiscount,+ NotApplicable,+ Voucher,+ VoucherCode,+)from ..discount.utils import (create_discount_objects_for_catalogue_promotions,create_discount_objects_for_order_promotions,+ delete_gift_line,get_products_voucher_discount,get_voucher_code_instance,validate_voucher_for_checkout,@@ -58,7 +64,7 @@ if TYPE_CHECKING:PRIVATE_META_APP_SHIPPING_ID = "external_app_shipping_id"-def invalidate_checkout_prices(+def invalidate_checkout(checkout_info: "CheckoutInfo",lines: Iterable["CheckoutLineInfo"],manager: "PluginsManager",@@ -67,11 +73,34 @@ def invalidate_checkout_prices(save: bool,) -> list[str]:"""Mark checkout as ready for prices recalculation."""- checkout = checkout_info.checkout-if recalculate_discount:- create_discount_objects_for_catalogue_promotions(lines)- recalculate_checkout_discount(manager, checkout_info, lines)+ recalculate_checkout_discounts(checkout_info, lines, manager)++ updated_fields = invalidate_checkout_prices(checkout_info, save=save)+ return updated_fields+++def recalculate_checkout_discounts(+ checkout_info: "CheckoutInfo",+ lines: Iterable["CheckoutLineInfo"],+ manager: "PluginsManager",+):+ """Recalculate checkout discounts.++ Update line and checkout discounts from vouchers and promotions.+ Create or remove gift line if needed.+ """+ create_discount_objects_for_catalogue_promotions(lines)+ recalculate_checkout_discount(manager, checkout_info, lines)+++def invalidate_checkout_prices(+ checkout_info: "CheckoutInfo",+ *,+ save: bool,+) -> list[str]:+ """Mark checkout as ready for prices recalculation."""+ checkout = checkout_info.checkoutcheckout.price_expiration = timezone.now()updated_fields = ["price_expiration", "last_change"]@@ -417,6 +446,8 @@ def get_discounted_lines(or voucher_info.variant_pks):for line_info in lines:+ if line_info.line.is_gift:+ continueline_variant = line_info.variantline_product = line_info.productline_category = line_info.product.category@@ -753,6 +784,8 @@ def add_voucher_to_checkout(checkout=checkout_info.checkout,type=DiscountType.ORDER_PROMOTION,).delete()+ # delete gift line if exists+ delete_gift_line(checkout_info.checkout, lines)def remove_promo_code_from_checkout(diff --git a/saleor/discount/__init__.py b/saleor/discount/__init__.pyindex a7b9b1dd55..e16538643c 100644--- a/saleor/discount/__init__.py+++ b/saleor/discount/__init__.py@@ -21,6 +21,7 @@ class DiscountType:ORDER_PROMOTION = "order_promotion"VOUCHER = "voucher"MANUAL = "manual"+CHOICES = [(SALE, "Sale"),(VOUCHER, "Voucher"),@@ -64,9 +65,11 @@ class RewardValueType:class RewardType:SUBTOTAL_DISCOUNT = "subtotal_discount"+ GIFT = "gift"CHOICES = [(SUBTOTAL_DISCOUNT, "subtotal_discount"),+ (GIFT, "gift"),]diff --git a/saleor/discount/error_codes.py b/saleor/discount/error_codes.pyindex ce5d3b3431..b05b10e987 100644--- a/saleor/discount/error_codes.py+++ b/saleor/discount/error_codes.py@@ -22,6 +22,8 @@ class PromotionCreateErrorCode(Enum):INVALID_PRECISION = "invalid_precision"MISSING_CHANNELS = "missing_channels"RULES_NUMBER_LIMIT = "rules_number_limit"+ GIFTS_NUMBER_LIMIT = "gifts_number_limit"+ INVALID_GIFT_TYPE = "invalid_gift_type"class PromotionUpdateErrorCode(Enum):@@ -45,6 +47,8 @@ class PromotionRuleCreateErrorCode(Enum):INVALID_PRECISION = "invalid_precision"MISSING_CHANNELS = "missing_channels"RULES_NUMBER_LIMIT = "rules_number_limit"+ GIFTS_NUMBER_LIMIT = "gifts_number_limit"+ INVALID_GIFT_TYPE = "invalid_gift_type"class PromotionRuleUpdateErrorCode(Enum):@@ -56,6 +60,8 @@ class PromotionRuleUpdateErrorCode(Enum):MISSING_CHANNELS = "missing_channels"MULTIPLE_CURRENCIES_NOT_ALLOWED = "multiple_currencies_not_allowed"INVALID_PRECISION = "invalid_precision"+ INVALID_GIFT_TYPE = "invalid_gift_type"+ GIFTS_NUMBER_LIMIT = "gifts_number_limit"class PromotionRuleDeleteErrorCode(Enum):diff --git a/saleor/discount/migrations/0075_promotionrule_gifts.py b/saleor/discount/migrations/0075_promotionrule_gifts.pynew file mode 100644index 0000000000..427d4a5005--- /dev/null+++ b/saleor/discount/migrations/0075_promotionrule_gifts.py@@ -0,0 +1,32 @@+# Generated by Django 3.2.23 on 2024-01-19 14:10++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("product", "0190_merge_20231221_1356"),+ ("discount", "0074_auto_20240119_1029"),+ ]++ operations = [+ migrations.AddField(+ model_name="promotionrule",+ name="gifts",+ field=models.ManyToManyField(+ blank=True,+ related_name="_discount_promotionrule_gifts_+",+ to="product.ProductVariant",+ ),+ ),+ migrations.AlterField(+ model_name="promotionrule",+ name="reward_type",+ field=models.CharField(+ blank=True,+ choices=[("subtotal_discount", "subtotal_discount"), ("gift", "gift")],+ max_length=255,+ null=True,+ ),+ ),+ ]diff --git a/saleor/discount/models.py b/saleor/discount/models.pyindex d2712bb87b..00458206b3 100644--- a/saleor/discount/models.py+++ b/saleor/discount/models.py@@ -396,6 +396,9 @@ class PromotionRule(models.Model):reward_type = models.CharField(max_length=255, choices=RewardType.CHOICES, blank=True, null=True)+ gifts = models.ManyToManyField(+ "product.ProductVariant", blank=True, related_name="+"+ )old_channel_listing_id = models.IntegerField(blank=True, null=True, unique=True)class Meta:diff --git a/saleor/discount/tests/test_utils/test_create_or_update_discount_objects_from_promotion_for_checkout.py b/saleor/discount/tests/test_utils/test_create_or_update_discount_objects_from_promotion_for_checkout.pyindex b92cb1d5c6..92d59f356d 100644--- a/saleor/discount/tests/test_utils/test_create_or_update_discount_objects_from_promotion_for_checkout.py+++ b/saleor/discount/tests/test_utils/test_create_or_update_discount_objects_from_promotion_for_checkout.py@@ -1,3 +1,4 @@+from datetime import timedeltafrom decimal import Decimalfrom unittest.mock import patch@@ -9,12 +10,19 @@ from freezegun import freeze_timefrom prices import Money, TaxedMoneyfrom ....checkout.base_calculations import base_checkout_total+from ....checkout.fetch import fetch_checkout_info, fetch_checkout_linesfrom ....discount.interface import VariantPromotionRuleInfo-from ....product.models import VariantChannelListingPromotionRule+from ....plugins.manager import get_plugins_manager+from ....product.models import (+ ProductChannelListing,+ ProductVariantChannelListing,+ VariantChannelListingPromotionRule,+)from ... import DiscountType, RewardType, RewardValueTypefrom ...models import CheckoutDiscount, CheckoutLineDiscount, PromotionRulefrom ...utils import (_create_or_update_checkout_discount,+ _get_best_gift_reward,create_discount_objects_for_order_promotions,create_or_update_discount_objects_from_promotion_for_checkout,)@@ -984,6 +992,38 @@ def test_one_of_promotion_rule_not_valid_anymore_one_updated(assert not checkout_line_info.discounts+def test_gift_promotion_not_valid_anymore(+ checkout_with_item_and_gift_promotion,+):+ # given+ checkout = checkout_with_item_and_gift_promotion++ # reduce quantity so the checkout will not apply for gift promotion anymore+ line = checkout.lines.get(is_gift=False)+ line.quantity = 1+ line.save(update_fields=["quantity"])++ manager = get_plugins_manager(allow_replica=False)+ lines, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, manager)++ gift_line_info = [line_info for line_info in lines if line_info.line.is_gift][0]+ line_discount = gift_line_info.discounts[0]+ gift_line = line_discount.line++ lines_count = len(lines)++ # when+ create_or_update_discount_objects_from_promotion_for_checkout(checkout_info, lines)++ # then+ assert len(lines) == lines_count - 1 == checkout.lines.count()+ with pytest.raises(line_discount._meta.model.DoesNotExist):+ line_discount.refresh_from_db()+ with pytest.raises(gift_line._meta.model.DoesNotExist):+ gift_line.refresh_from_db()++def test_create_discount_with_promotion_translation(checkout_info,checkout_lines_info,@@ -1177,6 +1217,66 @@ def test_create_discount_with_promotion_and_rule_translation(assert not checkout_line_info.discounts+def test_create_or_update_discount_for_gift_promotion_line(+ checkout_with_item_and_gift_promotion,+ catalogue_promotion_without_rules,+):+ # given+ checkout = checkout_with_item_and_gift_promotion+ manager = get_plugins_manager(allow_replica=False)+ lines, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, manager)+ gift_line_info = [line_info for line_info in lines if line_info.line.is_gift][0]+ gift_line_discount = gift_line_info.line.discounts.first()+ gift_product = gift_line_info.line.variant.product++ reward_value = Decimal("2")+ rule = catalogue_promotion_without_rules.rules.create(+ catalogue_predicate={+ "productPredicate": {+ "ids": [graphene.Node.to_global_id("Product", gift_product.id)]+ }+ },+ reward_value_type=RewardValueType.FIXED,+ reward_value=reward_value,+ )+ rule.channels.add(checkout.channel)++ listing = gift_line_info.channel_listing+ discounted_price = listing.price.amount - reward_value+ listing.discounted_price_amount = discounted_price+ listing.save(update_fields=["discounted_price_amount"])++ listing_promotion_rule = VariantChannelListingPromotionRule.objects.create(+ variant_channel_listing=listing,+ promotion_rule=rule,+ discount_amount=reward_value,+ currency=gift_line_info.channel.currency_code,+ )++ gift_line_info.rules_info = [+ VariantPromotionRuleInfo(+ rule=rule,+ variant_listing_promotion_rule=listing_promotion_rule,+ promotion=catalogue_promotion_without_rules,+ promotion_translation=None,+ rule_translation=None,+ )+ ]+ gift_line_info.discounts = [gift_line_discount]++ # when+ create_or_update_discount_objects_from_promotion_for_checkout(checkout_info, lines)++ # then+ assert len(gift_line_info.discounts) == 1+ discount_from_info = gift_line_info.discounts[0]+ assert gift_line_info.line.discounts.count() == 1+ assert discount_from_info == gift_line_discount+ assert discount_from_info.line == gift_line_info.line+ assert discount_from_info.type == DiscountType.ORDER_PROMOTION++def test_create_or_update_discount_objects_from_promotion_for_checkout_voucher_set(checkout_info, checkout_lines_info, order_promotion_rule, voucher):@@ -1225,10 +1325,10 @@ def test_create_or_update_discount_objects_from_promotion_no_applicable_rules(def test_create_or_update_discount_objects_from_promotion(checkout_info,checkout_lines_info,- catalogue_promotion_without_rules,+ order_promotion_without_rules,):# given- promotion = catalogue_promotion_without_rules+ promotion = order_promotion_without_rulescheckout = checkout_info.checkoutprice = Money("30", checkout_info.checkout.currency)checkout.total = TaxedMoney(net=price, gross=price)@@ -1299,10 +1399,10 @@ def test_create_or_update_discount_objects_from_promotion_best_rule_applies(delivery_price_mock,checkout_info,checkout_lines_info,- catalogue_promotion_without_rules,+ order_promotion_without_rules,):# given- promotion = catalogue_promotion_without_rules+ promotion = order_promotion_without_rulescheckout = checkout_info.checkoutdelivery_price = Money("10", checkout_info.checkout.currency)@@ -1382,7 +1482,9 @@ def test_create_or_update_discount_objects_from_promotion_best_rule_applies()# then- assert checkout_info.checkout.discounts.count() == 1+ checkout = checkout_info.checkout+ assert checkout.discounts.count() == 1+ assert checkout.discount_amount == rules[0].reward_valueassert len(checkout_info.discounts) == 1assert checkout_info.discounts[0].promotion_rule == rules[0]discount = checkout_info.discounts[0]@@ -1403,11 +1505,12 @@ def test_create_or_update_discount_objects_from_promotion_subtotal_price_discoundelivery_price_mock,checkout_info,checkout_lines_info,- catalogue_promotion_without_rules,+ order_promotion_without_rules,):# given- promotion = catalogue_promotion_without_rules+ promotion = order_promotion_without_rulescheckout = checkout_info.checkout+ lines_count = len(checkout_lines_info)delivery_price = Money("10", checkout_info.checkout.currency)price = Money("30", checkout_info.checkout.currency)@@ -1457,6 +1560,312 @@ def test_create_or_update_discount_objects_from_promotion_subtotal_price_discounassert checkout_info.discounts[0].promotion_rule == rules[0]discount = checkout_info.discounts[0]assert discount.amount_value == checkout.base_subtotal.amount * Decimal("0.5")+ checkout.refresh_from_db()+ assert checkout.lines.count() == lines_count+++def test_create_gift_discount(+ checkout_info,+ checkout_lines_info,+ gift_promotion_rule,+):+ # given+ rule = gift_promotion_rule+ promotion = rule.promotion+ variants = rule.gifts.all()+ variant_listings = ProductVariantChannelListing.objects.filter(variant__in=variants)+ top_price, variant_id = max(+ variant_listings.values_list("discounted_price_amount", "variant")+ )++ lines_count = len(checkout_lines_info)++ # when+ create_or_update_discount_objects_from_promotion_for_checkout(+ checkout_info, checkout_lines_info+ )++ # then+ checkout = checkout_info.checkout+ assert checkout.discounts.count() == 0+ assert checkout.discount_amount == 0+ assert checkout.lines.count() == lines_count + 1+ gift_line = checkout.lines.filter(is_gift=True).first()+ assert gift_line+ assert gift_line.variant_id == variant_id+ discount = gift_line.discounts.first()+ assert discount.promotion_rule == rule+ assert discount.type == DiscountType.ORDER_PROMOTION+ assert discount.value_type == RewardValueType.FIXED+ assert discount.value == top_price+ assert discount.amount_value == top_price+ assert discount.name == f"{promotion.name}: {rule.name}"+ promotion_id = graphene.Node.to_global_id("Promotion", promotion.id)+ assert discount.reason == f"Promotion: {promotion_id}"++ assert len(checkout_lines_info) == lines_count + 1+ assert checkout_lines_info[-1].discounts == [discount]+++def test_update_gift_discount(+ checkout_with_item_and_gift_promotion, variant, gift_promotion_rule+):+ # given+ checkout = checkout_with_item_and_gift_promotion++ gift_line = checkout.lines.get(is_gift=True)+ gift_line.variant = variant+ gift_line.save(update_fields=["variant"])++ gift_discount = gift_line.discounts.first()+ gift_discount.value = Decimal("2")+ gift_discount.save(update_fields=["value"])++ lines_info, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(+ checkout, lines_info, get_plugins_manager(allow_replica=False)+ )+ lines_count = len(lines_info)++ rule = gift_promotion_rule+ variants = rule.gifts.all()+ variant_listings = ProductVariantChannelListing.objects.filter(variant__in=variants)+ top_price, variant_id = max(+ variant_listings.values_list("discounted_price_amount", "variant")+ )++ # when+ create_or_update_discount_objects_from_promotion_for_checkout(+ checkout_info, lines_info+ )++ # then+ checkout = checkout_info.checkout+ assert checkout.discounts.count() == 0+ assert checkout.discount_amount == 0+ assert len(lines_info) == checkout.lines.count() == lines_count+ gift_line.refresh_from_db()+ assert gift_line+ assert gift_line.variant_id == variant_id+ discount = gift_line.discounts.first()+ assert discount.promotion_rule == rule+ assert discount.type == DiscountType.ORDER_PROMOTION+ assert discount.value_type == RewardValueType.FIXED+ assert discount.value == top_price+ assert discount.amount_value == top_price+ assert discount.name == f"{rule.promotion.name}: {rule.name}"+ promotion_id = graphene.Node.to_global_id("Promotion", rule.promotion.id)+ assert discount.reason == f"Promotion: {promotion_id}"++ assert lines_info[-1].discounts == [discount]+++@patch("saleor.discount.utils.base_checkout_delivery_price")+@patch("saleor.discount.utils.base_checkout_subtotal")+def test_create_or_update_discount_objects_from_promotion_gift_rule_applies(+ subtotal_mock,+ delivery_price_mock,+ checkout_info,+ checkout_lines_info,+ gift_promotion_rule,+):+ # given+ checkout = checkout_info.checkout++ promotion = gift_promotion_rule.promotion+ variants = gift_promotion_rule.gifts.all()+ variant_listings = ProductVariantChannelListing.objects.filter(variant__in=variants)+ top_price, variant_id = max(+ variant_listings.values_list("discounted_price_amount", "variant")+ )+ lines_count = len(checkout_lines_info)+ delivery_price = Money("10", checkout_info.checkout.currency)+ price = Money("30", checkout_info.checkout.currency)+ checkout.total = TaxedMoney(net=price, gross=price)+ checkout.subtotal = TaxedMoney(net=price, gross=price)+ checkout.save(+ update_fields=[+ "total_net_amount",+ "total_gross_amount",+ "subtotal_net_amount",+ "subtotal_gross_amount",+ ]+ )++ subtotal_mock.return_value = price+ delivery_price_mock.return_value = delivery_price++ rules = PromotionRule.objects.bulk_create(+ [+ PromotionRule(+ name="Order promotion rule 1",+ promotion=promotion,+ order_predicate={+ "base_total_price": {+ "range": {+ "gte": 10,+ }+ }+ },+ reward_value_type=RewardValueType.FIXED,+ reward_value=top_price - Decimal("1"),+ reward_type=RewardType.SUBTOTAL_DISCOUNT,+ ),+ PromotionRule(+ name="Order promotion rule 2",+ promotion=promotion,+ order_predicate={+ "base_subtotal_price": {+ "range": {+ "gte": 20,+ }+ }+ },+ reward_value_type=RewardValueType.PERCENTAGE,+ reward_value=top_price - Decimal("2"),+ reward_type=RewardType.SUBTOTAL_DISCOUNT,+ ),+ PromotionRule(+ name="Order promotion rule 1",+ promotion=promotion,+ order_predicate={+ "base_total_price": {+ "range": {+ "gte": 100,+ }+ }+ },+ reward_value_type=RewardValueType.PERCENTAGE,+ reward_value=top_price + Decimal("10"),+ reward_type=RewardType.SUBTOTAL_DISCOUNT,+ ),+ ]+ )+ for rule in rules:+ rule.channels.add(checkout_info.channel)++ # when+ create_or_update_discount_objects_from_promotion_for_checkout(+ checkout_info, checkout_lines_info+ )++ # then+ checkout = checkout_info.checkout+ assert checkout.discounts.count() == 0+ assert checkout.discount_amount == 0+ assert checkout.lines.count() == lines_count + 1+ gift_line = checkout.lines.filter(is_gift=True).first()+ assert gift_line+ assert gift_line.variant_id == variant_id+ discount = gift_line.discounts.first()+ assert discount.promotion_rule == gift_promotion_rule+ assert discount.type == DiscountType.ORDER_PROMOTION+ assert discount.value_type == RewardValueType.FIXED+ assert discount.value == top_price+ assert discount.amount_value == top_price+ assert discount.name == f"{promotion.name}: {gift_promotion_rule.name}"+ promotion_id = graphene.Node.to_global_id("Promotion", promotion.id)+ assert discount.reason == f"Promotion: {promotion_id}"+++@patch("saleor.discount.utils.base_checkout_delivery_price")+@patch("saleor.discount.utils.base_checkout_subtotal")+def test_create_or_update_discount_objects_from_promotion_gift_line_removed(+ subtotal_mock,+ delivery_price_mock,+ checkout_with_item_and_gift_promotion,+ gift_promotion_rule,+):+ """Ensure that gift line is removed when there is better discount available."""+ # given+ checkout = checkout_with_item_and_gift_promotion++ promotion = gift_promotion_rule.promotion+ variants = gift_promotion_rule.gifts.all()+ variant_listings = ProductVariantChannelListing.objects.filter(variant__in=variants)+ top_price, variant_id = max(+ variant_listings.values_list("discounted_price_amount", "variant")+ )+ delivery_price = Money("10", checkout.currency)+ price = Money("30", checkout.currency)+ checkout.total = TaxedMoney(net=price, gross=price)+ checkout.subtotal = TaxedMoney(net=price, gross=price)+ checkout.save(+ update_fields=[+ "total_net_amount",+ "total_gross_amount",+ "subtotal_net_amount",+ "subtotal_gross_amount",+ ]+ )++ subtotal_mock.return_value = price+ delivery_price_mock.return_value = delivery_price++ reward_value_1 = top_price + Decimal("2")+ reward_value_2 = top_price + Decimal("10")+ rules = PromotionRule.objects.bulk_create(+ [+ PromotionRule(+ name="Order promotion rule 1",+ promotion=promotion,+ order_predicate={+ "base_total_price": {+ "range": {+ "gte": 10,+ }+ }+ },+ reward_value_type=RewardValueType.FIXED,+ reward_value=reward_value_1,+ reward_type=RewardType.SUBTOTAL_DISCOUNT,+ ),+ PromotionRule(+ name="Order promotion rule 1",+ promotion=promotion,+ order_predicate={+ "base_total_price": {+ "range": {+ "gte": 100,+ }+ }+ },+ reward_value_type=RewardValueType.PERCENTAGE,+ reward_value=reward_value_2,+ reward_type=RewardType.SUBTOTAL_DISCOUNT,+ ),+ ]+ )+ for rule in rules:+ rule.channels.add(checkout.channel)++ lines_info, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(+ checkout, lines_info, get_plugins_manager(allow_replica=False)+ )+ lines_count = len(lines_info)++ # when+ create_or_update_discount_objects_from_promotion_for_checkout(+ checkout_info, lines_info+ )++ # then+ checkout = checkout_info.checkout+ assert checkout.discounts.count() == 1+ assert checkout.discount_amount == reward_value_1+ assert len(lines_info) == checkout.lines.count() == lines_count - 1+ assert not [line_info for line_info in lines_info if line_info.line.is_gift]+ assert not checkout.lines.filter(is_gift=True).first()+ discount = checkout.discounts.first()+ assert discount.promotion_rule == rules[0]+ assert discount.type == DiscountType.ORDER_PROMOTION+ assert discount.value_type == RewardValueType.FIXED+ assert discount.value == reward_value_1+ assert discount.amount_value == reward_value_1+ assert discount.name == f"{promotion.name}: {rules[0].name}"+ promotion_id = graphene.Node.to_global_id("Promotion", promotion.id)+ assert discount.reason == f"Promotion: {promotion_id}"def test_create_or_update_discount_from_promotion_voucher_code_set_checkout_discount(@@ -1735,8 +2144,10 @@ def test_create_or_update_checkout_discount_race_condition(_create_or_update_checkout_discount(checkout,checkout_info,+ checkout_lines_info,rule,- Money(reward_value, currency),+ reward_value,+ None,currency,promotion,True,@@ -1750,3 +2161,140 @@ def test_create_or_update_checkout_discount_race_condition(# thendiscounts = list(checkout_info.checkout.discounts.all())assert len(discounts) == 1+++def test_create_or_update_checkout_discount_gift_reward_race_condition(+ checkout_info,+ checkout_lines_info,+ gift_promotion_rule,+):+ # given+ rule = gift_promotion_rule+ promotion = gift_promotion_rule.promotion+ checkout = checkout_info.checkout+ channel = checkout_info.channel+ currency = channel.currency_code++ variants = gift_promotion_rule.gifts.all()+ variant_listings = ProductVariantChannelListing.objects.filter(variant__in=variants)+ listing = max(list(variant_listings), key=lambda x: x.discounted_price_amount)++ def call_update(*args, **kwargs):+ _create_or_update_checkout_discount(+ checkout,+ checkout_info,+ checkout_lines_info,+ rule,+ listing.discounted_price_amount,+ listing,+ currency,+ promotion,+ True,+ )++ with before_after.before(+ "saleor.discount.utils.get_rule_translations", call_update+ ):+ call_update()++ # then+ assert checkout_info.checkout.discounts.count() == 0+ assert checkout.lines.filter(is_gift=True).count() == 1+ line = checkout.lines.filter(is_gift=True).first()+ assert line.discounts.count() == 1+++def test_get_best_gift_reward(+ gift_promotion_rule, order_promotion_without_rules, channel_USD, product+):+ # given+ gift_rule_2 = PromotionRule.objects.create(+ name="Order promotion rule",+ promotion=order_promotion_without_rules,+ order_predicate={+ "base_total_price": {+ "range": {+ "gte": 20,+ }+ }+ },+ reward_type=RewardType.GIFT,+ )+ gift_rule_2.channels.add(channel_USD)+ gift_rule_2_variant = product.variants.first()+ gift_rule_2.gifts.set([gift_rule_2_variant])+ price_amount = gift_rule_2_variant.channel_listings.get(+ channel=channel_USD+ ).discounted_price_amount++ variants = gift_promotion_rule.gifts.all()+ variant_listings = ProductVariantChannelListing.objects.filter(variant__in=variants)+ top_listing = max(list(variant_listings), key=lambda x: x.discounted_price_amount)+ assert price_amount < top_listing.discounted_price_amount++ rules = [gift_rule_2, gift_promotion_rule]+ country = "US"++ # when+ rule, listing = _get_best_gift_reward(rules, channel_USD, country)++ # then+ assert rule.id == gift_promotion_rule.id+ assert listing.id == top_listing.id+++def test_get_best_gift_reward_insufficient_stock(+ gift_promotion_rule, channel_USD, product+):+ # given+ variant = product.variants.first()+ variant.stocks.all().delete()+ gift_promotion_rule.gifts.set([variant])++ rules = [gift_promotion_rule]+ country = "US"++ # when+ rule, listing = _get_best_gift_reward(rules, channel_USD, country)++ # then+ assert rule is None+ assert listing is None+++def test_get_best_gift_reward_no_available_for_purchase_variants(+ gift_promotion_rule, channel_USD+):+ # given+ variants = gift_promotion_rule.gifts.all()+ product_ids = [variant.product_id for variant in variants]+ ProductChannelListing.objects.filter(product__in=product_ids[:1]).update(+ available_for_purchase_at=timezone.now() + timedelta(days=1)+ )+ ProductChannelListing.objects.filter(product__in=product_ids[1:]).delete()++ rules = [gift_promotion_rule]+ country = "US"++ # when+ rule, listing = _get_best_gift_reward(rules, channel_USD, country)++ # then+ assert rule is None+ assert listing is None+++def test_get_best_gift_reward_no_variants_in_channel(gift_promotion_rule, channel_USD):+ # given+ variants = gift_promotion_rule.gifts.all()+ ProductVariantChannelListing.objects.filter(variant__in=variants).delete()++ rules = [gift_promotion_rule]+ country = "US"++ # when+ rule, listing = _get_best_gift_reward(rules, channel_USD, country)++ # then+ assert rule is None+ assert listing is Nonediff --git a/saleor/discount/utils.py b/saleor/discount/utils.pyindex 07bab1f949..ee03b29a4e 100644--- a/saleor/discount/utils.py+++ b/saleor/discount/utils.py@@ -1,4 +1,5 @@-from collections import defaultdict+import datetime+from collections import defaultdict, namedtuplefrom collections.abc import Iterable, Iteratorfrom decimal import ROUND_HALF_UP, Decimalfrom functools import partial@@ -6,6 +7,7 @@ from typing import TYPE_CHECKING, Callable, Optional, Union, castfrom uuid import UUIDimport graphene+import pytzfrom django.db import transactionfrom django.db.models import Exists, F, OuterRef, QuerySetfrom django.utils import timezone@@ -16,12 +18,18 @@ from ..checkout.base_calculations import (base_checkout_delivery_price,base_checkout_subtotal,)-from ..checkout.models import Checkout+from ..checkout.fetch import CheckoutLineInfo, find_checkout_line_info+from ..checkout.models import Checkout, CheckoutLine+from ..core.exceptions import InsufficientStockfrom ..core.taxes import zero_moneyfrom ..core.utils.promo_code import InvalidPromoCode-from ..discount.models import VoucherCustomer-from ..product.models import Product, ProductVariant-from . import DiscountType, PromotionRuleInfo, RewardType+from ..product.models import (+ Product,+ ProductChannelListing,+ ProductVariant,+ ProductVariantChannelListing,+)+from . import DiscountType, PromotionRuleInfo, RewardType, RewardValueTypefrom .interface import VariantPromotionRuleInfo, get_rule_translationsfrom .models import (CheckoutDiscount,@@ -32,16 +40,16 @@ from .models import (PromotionRule,Voucher,VoucherCode,+ VoucherCustomer,)if TYPE_CHECKING:from ..account.models import User- from ..checkout.fetch import CheckoutInfo, CheckoutLineInfo+ from ..checkout.fetch import CheckoutInfofrom ..order.models import Orderfrom ..plugins.manager import PluginsManagerfrom ..product.managers import ProductVariantQuerysetfrom ..product.models import (- ProductVariantChannelListing,VariantChannelListingPromotionRule,)@@ -355,16 +363,21 @@ def create_discount_objects_for_catalogue_promotions(discount_amount = _get_discount_amount(line_info.channel_listing, line.quantity)# get the existing discounts for the line- discounts_to_update = line_info.get_promotion_discounts()+ discounts_to_update = line_info.get_catalogue_discounts()rule_id_to_discount = {discount.promotion_rule_id: discount for discount in discounts_to_update}- # delete all existing discounts if the line is not discounted- if not discount_amount:+ # delete all existing discounts if the line is not discounted or it is a gift+ if not discount_amount or line.is_gift:ids_to_remove = [discount.id for discount in discounts_to_update]- CheckoutLineDiscount.objects.filter(id__in=ids_to_remove).delete()- line_info.discounts = []+ if ids_to_remove:+ line_discount_ids_to_remove.extend(ids_to_remove)+ line_info.discounts = [+ discount+ for discount in line_info.discounts+ if discount.id not in ids_to_remove+ ]continue# delete the discount objects that are not valid anymore@@ -489,13 +502,15 @@ def _update_discount(if discount_to_update.promotion_rule_id != rule.id:discount_to_update.promotion_rule_id = rule.idupdated_fields.append("promotion_rule_id")- if discount_to_update.value_type != rule.reward_value_type:- discount_to_update.value_type = (- rule.reward_value_type # type: ignore[assignment]- )+ # gift rule has empty reward_value_type+ value_type = rule.reward_value_type or RewardValueType.FIXED+ if discount_to_update.value_type != value_type:+ discount_to_update.value_type = value_typeupdated_fields.append("value_type")- if discount_to_update.value != rule.reward_value:- discount_to_update.value = rule.reward_value # type: ignore[assignment]+ # gift rule has empty reward_value+ value = rule.reward_value or rule_discount_amount+ if discount_to_update.value != value:+ discount_to_update.value = valueupdated_fields.append("value")if discount_to_update.amount_value != rule_discount_amount:discount_to_update.amount_value = rule_discount_amount@@ -529,37 +544,68 @@ def create_discount_objects_for_order_promotions(# Discount from order rules is applied only when the voucher is not setif checkout.voucher_code:- _clear_checkout_discount(checkout_info, save)+ _clear_checkout_discount(checkout_info, lines_info, save)+ return++ channel = checkout_info.channel+ rule_data = get_best_rule_for_checkout(+ checkout, channel, checkout_info.get_country()+ )+ if not rule_data:+ _clear_checkout_discount(checkout_info, lines_info, save)return+ best_rule, best_discount_amount, gift_listing = rule_data++ _create_or_update_checkout_discount(+ checkout,+ checkout_info,+ lines_info,+ best_rule,+ best_discount_amount,+ gift_listing,+ channel.currency_code,+ best_rule.promotion,+ save,+ )+++def get_best_rule_for_checkout(checkout: "Checkout", channel: "Channel", country: str):+ RuleDiscount = namedtuple(+ "RuleDiscount", ["rule", "discount_amount", "gift_listing"]+ )+ subtotal = checkout.base_subtotalrules = fetch_promotion_rules_for_checkout(checkout)if not rules:- _clear_checkout_discount(checkout_info, save)return- subtotal = checkout.base_subtotal- currency_code = checkout_info.channel.currency_code- rule_with_discount_amount = []+ currency_code = channel.currency_code+ rule_discounts: list[RuleDiscount] = []+ gift_rules = [rule for rule in rules if rule.reward_type == RewardType.GIFT]for rule in rules:+ if rule in gift_rules:+ continuediscount = rule.get_discount(currency_code)price = zero_money(currency_code)if rule.reward_type == RewardType.SUBTOTAL_DISCOUNT:price = subtotal- discount_amount = price - discount(price)- rule_with_discount_amount.append((rule, discount_amount))+ discount_amount = (price - discount(price)).amount+ rule_discounts.append(RuleDiscount(rule, discount_amount, None))++ if gift_rules:+ rule, gift_listing = _get_best_gift_reward(gift_rules, channel, country)+ if rule and gift_listing:+ rule_discounts.append(+ RuleDiscount(rule, gift_listing.discounted_price_amount, gift_listing)+ )- best_rule, best_discount_amount = max(rule_with_discount_amount, key=lambda x: x[1])- promotion = best_rule.promotion+ if not rule_discounts:+ return- _create_or_update_checkout_discount(- checkout,- checkout_info,- best_rule,- best_discount_amount,- currency_code,- promotion,- save,+ best_rule, best_discount_amount, gift_listing = max(+ rule_discounts, key=lambda x: x.discount_amount)+ return best_rule, best_discount_amount, gift_listingdef _set_checkout_base_prices(checkout_info, lines_info):@@ -581,7 +627,10 @@ def _set_checkout_base_prices(checkout_info, lines_info):checkout.save(update_fields=["base_total_amount", "base_subtotal_amount"])-def _clear_checkout_discount(checkout_info, save):+def _clear_checkout_discount(+ checkout_info: "CheckoutInfo", lines_info: Iterable["CheckoutLineInfo"], save: bool+):+ delete_gift_line(checkout_info.checkout, lines_info)if checkout_info.discounts:CheckoutDiscount.objects.filter(checkout=checkout_info.checkout,@@ -614,11 +663,94 @@ def _clear_checkout_discount(checkout_info, save):)+def _get_best_gift_reward(+ rules: Iterable["PromotionRule"], channel: "Channel", country: str+) -> tuple[Optional[PromotionRule], Optional[ProductVariantChannelListing]]:+ from ..warehouse.availability import check_stock_quantity_bulk++ rule_ids = [rule.id for rule in rules]+ PromotionRuleGift = PromotionRule.gifts.through+ rule_gifts = PromotionRuleGift.objects.filter(promotionrule_id__in=rule_ids)+ variants = ProductVariant.objects.filter(+ Exists(+ rule_gifts.values("productvariant_id").filter(+ productvariant_id=OuterRef("id")+ )+ )+ )+ variant_ids_with_insufficient_stock = set()+ if not variants:+ return None, None++ try:+ check_stock_quantity_bulk(+ variants,+ country,+ [1] * variants.count(),+ channel.slug,+ None,+ )+ except InsufficientStock as error:+ variant_ids_with_insufficient_stock = {+ item.variant.pk for item in error.items if item.variant+ }++ available_variant_ids = (+ set(variants.values_list("id", flat=True)) - variant_ids_with_insufficient_stock+ )++ if not available_variant_ids:+ return None, None++ # check if variant is available for purchase+ available_variant_ids = _get_available_for_purchase_variant_ids(+ available_variant_ids, channel+ )+ if not available_variant_ids:+ return None, None++ # check variant channel availability+ available_variant_listings = ProductVariantChannelListing.objects.filter(+ variant_id__in=available_variant_ids,+ channel_id=channel.id,+ price_amount__isnull=False,+ )+ if not available_variant_listings:+ return None, None++ listing = max(+ list(available_variant_listings),+ # sort over a top price+ key=lambda x: x.discounted_price_amount,+ )+ rule_gift = rule_gifts.filter(productvariant_id=listing.variant_id).first()+ rule = rule_gift.promotionrule if rule_gift else None+ return rule, listing+++def _get_available_for_purchase_variant_ids(+ available_variant_ids: set[int], channel: "Channel"+):+ today = datetime.datetime.now(pytz.UTC)+ variants = ProductVariant.objects.filter(id__in=available_variant_ids)+ product_listings = ProductChannelListing.objects.filter(+ Exists(variants.filter(product_id=OuterRef("product_id"))),+ available_for_purchase_at__lte=today,+ channel_id=channel.id,+ )+ available_variant_ids = ProductVariant.objects.filter(+ Exists(product_listings.filter(product_id=OuterRef("product_id")))+ ).values_list("id", flat=True)+ return set(available_variant_ids)++def _create_or_update_checkout_discount(checkout: "Checkout",checkout_info: "CheckoutInfo",+ lines_info: Iterable["CheckoutLineInfo"],best_rule: "PromotionRule",- best_discount_amount: Money,+ best_discount_amount: Decimal,+ gift_listing: Optional[ProductVariantChannelListing],currency_code: str,promotion: "Promotion",save: bool,@@ -634,39 +766,71 @@ def _create_or_update_checkout_discount(promotion_translation=promotion_translation,rule_translation=rule_translation,)- checkout_discount, created = checkout.discounts.get_or_create(+ # gift rule has empty reward_value and reward_value_type+ value_type = best_rule.reward_value_type or RewardValueType.FIXED+ amount_value = gift_listing.price_amount if gift_listing else best_discount_amount+ value = best_rule.reward_value or amount_value+ discount_object_defaults = {+ "promotion_rule": best_rule,+ "value_type": value_type,+ "value": value,+ "amount_value": amount_value,+ "currency": currency_code,+ "name": get_discount_name(best_rule, promotion),+ "translated_name": get_discount_translated_name(rule_info),+ "reason": prepare_promotion_discount_reason(promotion, get_sale_id(promotion)),+ }+ if gift_listing:+ _handle_gift_reward(+ checkout,+ checkout_info,+ lines_info,+ gift_listing,+ discount_object_defaults,+ rule_info,+ save,+ )+ else:+ _handle_order_promotion(+ checkout,+ checkout_info,+ lines_info,+ discount_object_defaults,+ rule_info,+ save,+ )+++def _handle_order_promotion(+ checkout: "Checkout",+ checkout_info: "CheckoutInfo",+ lines_info: Iterable["CheckoutLineInfo"],+ discount_object_defaults: dict,+ rule_info: VariantPromotionRuleInfo,+ save: bool,+):+ discount_object, created = checkout.discounts.get_or_create(type=DiscountType.ORDER_PROMOTION,- defaults={- "checkout": checkout,- "promotion_rule": best_rule,- "value_type": best_rule.reward_value_type,- "value": best_rule.reward_value,- "amount_value": best_discount_amount.amount,- "currency": currency_code,- "name": get_discount_name(best_rule, promotion),- "translated_name": get_discount_translated_name(rule_info),- "reason": prepare_promotion_discount_reason(- promotion, get_sale_id(promotion)- ),- },+ defaults=discount_object_defaults,)+ discount_amount = discount_object_defaults["amount_value"]if not created:fields_to_update: list[str] = []_update_discount(- best_rule,+ discount_object_defaults["promotion_rule"],rule_info,- best_discount_amount.amount,- checkout_discount,+ discount_amount,+ discount_object,fields_to_update,)if fields_to_update:- checkout_discount.save(update_fields=fields_to_update)+ discount_object.save(update_fields=fields_to_update)- checkout_info.discounts = [checkout_discount]- checkout.discount = best_discount_amount- checkout.discount_name = checkout_discount.name- checkout.translated_discount_name = checkout_discount.translated_name+ checkout_info.discounts = [discount_object]+ checkout.discount_amount = discount_amount+ checkout.discount_name = discount_object.name+ checkout.translated_discount_name = discount_object.translated_nameif save:checkout.save(update_fields=[@@ -676,6 +840,98 @@ def _create_or_update_checkout_discount(])+ delete_gift_line(checkout, lines_info)+++def delete_gift_line(checkout: "Checkout", lines_info: Iterable["CheckoutLineInfo"]):+ if gift_line_infos := [line for line in lines_info if line.line.is_gift]:+ CheckoutLine.objects.filter(checkout_id=checkout.pk, is_gift=True).delete()+ for gift_line_info in gift_line_infos:+ lines_info.remove(gift_line_info) # type: ignore[attr-defined]+++def _handle_gift_reward(+ checkout: "Checkout",+ checkout_info: "CheckoutInfo",+ lines_info: Iterable["CheckoutLineInfo"],+ gift_listing: ProductVariantChannelListing,+ discount_object_defaults: dict,+ rule_info: VariantPromotionRuleInfo,+ save: bool,+):+ with transaction.atomic():+ line, line_created = create_gift_line(checkout, gift_listing.variant_id)+ line_discount = None+ discount_created = False+ (+ line_discount,+ discount_created,+ ) = CheckoutLineDiscount.objects.get_or_create(+ type=DiscountType.ORDER_PROMOTION,+ line=line,+ defaults=discount_object_defaults,+ )++ if not discount_created:+ fields_to_update = []+ if line_discount.line_id != line.id:+ line_discount.line = line+ fields_to_update.append("line_id")+ _update_discount(+ discount_object_defaults["promotion_rule"],+ rule_info,+ discount_object_defaults["amount_value"],+ line_discount,+ fields_to_update,+ )+ if fields_to_update:+ line_discount.save(update_fields=fields_to_update)++ checkout_info.discounts = []+ checkout.discount_amount = Decimal("0")+ if save:+ checkout.save(update_fields=["discount_amount"])++ if line_created:+ variant = gift_listing.variant+ gift_line_info = CheckoutLineInfo(+ line=line,+ variant=variant,+ channel_listing=gift_listing,+ product=variant.product,+ product_type=variant.product.product_type,+ collections=[],+ discounts=[line_discount],+ rules_info=[rule_info],+ channel=checkout_info.channel,+ )+ lines_info.append(gift_line_info) # type: ignore[attr-defined]+ else:+ line_info = find_checkout_line_info(lines_info, line.id)+ line_info.line = line+ line_info.discounts = [line_discount]+++def create_gift_line(checkout: "Checkout", variant_id: int):+ defaults = {+ "variant_id": variant_id,+ "quantity": 1,+ "currency": checkout.currency,+ }+ line, created = CheckoutLine.objects.get_or_create(+ checkout=checkout, is_gift=True, defaults=defaults+ )+ if not created:+ fields_to_update = []+ for field, value in defaults.items():+ if getattr(line, field) != value:+ setattr(line, field, value)+ fields_to_update.append(field)+ if fields_to_update:+ line.save(update_fields=fields_to_update)++ return line, created+def get_variants_to_promotion_rules_map(variant_qs: "ProductVariantQueryset",diff --git a/saleor/graphql/checkout/dataloaders.py b/saleor/graphql/checkout/dataloaders.pyindex 9759b9da01..5805c664e2 100644--- a/saleor/graphql/checkout/dataloaders.py+++ b/saleor/graphql/checkout/dataloaders.py@@ -161,7 +161,6 @@ class CheckoutLinesInfoByCheckoutTokenLoader(DataLoader[str, list[CheckoutLineIn):apply_voucher_to_checkout_line(voucher_info=voucher_info,- checkout=checkout,lines_info=lines_info_map[checkout.pk],)return [lines_info_map[key] for key in keys]diff --git a/saleor/graphql/checkout/mutations/checkout_add_promo_code.py b/saleor/graphql/checkout/mutations/checkout_add_promo_code.pyindex 855a84d8bc..3382d91bb9 100644--- a/saleor/graphql/checkout/mutations/checkout_add_promo_code.py+++ b/saleor/graphql/checkout/mutations/checkout_add_promo_code.py@@ -7,7 +7,7 @@ from ....checkout.fetch import (fetch_checkout_lines,update_delivery_method_lists_for_checkout_info,)-from ....checkout.utils import add_promo_code_to_checkout, invalidate_checkout_prices+from ....checkout.utils import add_promo_code_to_checkout, invalidate_checkoutfrom ....webhook.event_types import WebhookEventAsyncTypefrom ...core import ResolveInfofrom ...core.descriptions import ADDED_IN_34, DEPRECATED_IN_3X_INPUT@@ -114,7 +114,7 @@ class CheckoutAddPromoCode(BaseMutation):)update_checkout_shipping_method_if_invalid(checkout_info, lines)- invalidate_checkout_prices(+ invalidate_checkout(checkout_info,lines,manager,diff --git a/saleor/graphql/checkout/mutations/checkout_billing_address_update.py b/saleor/graphql/checkout/mutations/checkout_billing_address_update.pyindex 09a5536ae0..032e1bc783 100644--- a/saleor/graphql/checkout/mutations/checkout_billing_address_update.py+++ b/saleor/graphql/checkout/mutations/checkout_billing_address_update.py@@ -4,7 +4,7 @@ from ....checkout import AddressTypefrom ....checkout.fetch import fetch_checkout_info, fetch_checkout_linesfrom ....checkout.utils import (change_billing_address_in_checkout,- invalidate_checkout_prices,+ invalidate_checkout,)from ....core.tracing import traced_atomic_transactionfrom ....webhook.event_types import WebhookEventAsyncType@@ -98,7 +98,7 @@ class CheckoutBillingAddressUpdate(CheckoutShippingAddressUpdate):)lines, _ = fetch_checkout_lines(checkout)checkout_info = fetch_checkout_info(checkout, lines, manager)- invalidate_prices_updated_fields = invalidate_checkout_prices(+ invalidate_prices_updated_fields = invalidate_checkout(checkout_info,lines,manager,diff --git a/saleor/graphql/checkout/mutations/checkout_create.py b/saleor/graphql/checkout/mutations/checkout_create.pyindex a793539a73..f757bb63e7 100644--- a/saleor/graphql/checkout/mutations/checkout_create.py+++ b/saleor/graphql/checkout/mutations/checkout_create.py@@ -35,6 +35,7 @@ from ...product.types import ProductVariantfrom ...site.dataloaders import get_site_promisefrom ..types import Checkoutfrom .utils import (+ apply_gift_reward_if_applicable_on_checkout_creation,check_lines_quantity,check_permissions_for_custom_prices,get_variants_and_total_quantities,@@ -388,5 +389,6 @@ class CheckoutCreate(ModelMutation, I18nMixin):response = super().perform_mutation(_root, info, input=input)manager = get_plugin_manager_promise(info.context).get()cls.call_event(manager.checkout_created, response.checkout)+ apply_gift_reward_if_applicable_on_checkout_creation(response.checkout)response.created = Truereturn responsediff --git a/saleor/graphql/checkout/mutations/checkout_create_from_order.py b/saleor/graphql/checkout/mutations/checkout_create_from_order.pyindex c7780cd182..a194eb6339 100644--- a/saleor/graphql/checkout/mutations/checkout_create_from_order.py+++ b/saleor/graphql/checkout/mutations/checkout_create_from_order.py@@ -27,6 +27,7 @@ from ..enums import (from ..types import Checkoutfrom .utils import (CheckoutLineData,+ apply_gift_reward_if_applicable_on_checkout_creation,get_not_available_variants_for_purchase,get_not_published_variants,get_variants_and_total_quantities,@@ -420,6 +421,7 @@ class CheckoutCreateFromOrder(BaseMutation):site=site, user=info.context.user),)+ apply_gift_reward_if_applicable_on_checkout_creation(checkout)return CheckoutCreateFromOrder(checkout=checkout, unavailable_variants=variant_errors)diff --git a/saleor/graphql/checkout/mutations/checkout_delivery_method_update.py b/saleor/graphql/checkout/mutations/checkout_delivery_method_update.pyindex 8e4d1f3beb..a52752cc0a 100644--- a/saleor/graphql/checkout/mutations/checkout_delivery_method_update.py+++ b/saleor/graphql/checkout/mutations/checkout_delivery_method_update.py@@ -14,7 +14,7 @@ from ....checkout.fetch import (from ....checkout.utils import (delete_external_shipping_id,get_or_create_checkout_metadata,- invalidate_checkout_prices,+ invalidate_checkout,is_shipping_required,set_external_shipping_id,)@@ -247,7 +247,7 @@ class CheckoutDeliveryMethodUpdate(BaseMutation):delete_external_shipping_id(checkout=checkout)checkout.shipping_method = shipping_methodcheckout.collection_point = collection_point- invalidate_prices_updated_fields = invalidate_checkout_prices(+ invalidate_prices_updated_fields = invalidate_checkout(checkout_info, lines, manager, save=False)checkout.save(diff --git a/saleor/graphql/checkout/mutations/checkout_line_delete.py b/saleor/graphql/checkout/mutations/checkout_line_delete.pyindex 68358da327..a832757a86 100644--- a/saleor/graphql/checkout/mutations/checkout_line_delete.py+++ b/saleor/graphql/checkout/mutations/checkout_line_delete.py@@ -1,7 +1,8 @@import graphene+from ....checkout.error_codes import CheckoutErrorCodefrom ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines-from ....checkout.utils import invalidate_checkout_prices+from ....checkout.utils import invalidate_checkoutfrom ....webhook.event_types import WebhookEventAsyncTypefrom ...core import ResolveInfofrom ...core.descriptions import ADDED_IN_34, DEPRECATED_IN_3X_INPUT@@ -9,7 +10,7 @@ from ...core.doc_category import DOC_CATEGORY_CHECKOUTfrom ...core.mutations import BaseMutationfrom ...core.scalars import UUIDfrom ...core.types import CheckoutError-from ...core.utils import WebhookEventInfo+from ...core.utils import WebhookEventInfo, raise_validation_errorfrom ...plugins.dataloaders import get_plugin_manager_promisefrom ..types import Checkout, CheckoutLinefrom .utils import get_checkout, update_checkout_shipping_method_if_invalid@@ -65,6 +66,13 @@ class CheckoutLineDelete(BaseMutation):info, line_id, only_type=CheckoutLine, field="line_id")+ if line.is_gift:+ raise_validation_error(+ message="Checkout line marked as gift can't be deleted.",+ field="line_id",+ code=CheckoutErrorCode.NON_REMOVABLE_GIFT_LINE.value,+ )+if line and line in checkout.lines.all():line.delete()@@ -72,7 +80,7 @@ class CheckoutLineDelete(BaseMutation):lines, _ = fetch_checkout_lines(checkout)checkout_info = fetch_checkout_info(checkout, lines, manager)update_checkout_shipping_method_if_invalid(checkout_info, lines)- invalidate_checkout_prices(checkout_info, lines, manager, save=True)+ invalidate_checkout(checkout_info, lines, manager, save=True)cls.call_event(manager.checkout_updated, checkout)return CheckoutLineDelete(checkout=checkout)diff --git a/saleor/graphql/checkout/mutations/checkout_lines_add.py b/saleor/graphql/checkout/mutations/checkout_lines_add.pyindex 4032bd9ad7..3fc8700c02 100644--- a/saleor/graphql/checkout/mutations/checkout_lines_add.py+++ b/saleor/graphql/checkout/mutations/checkout_lines_add.py@@ -6,7 +6,7 @@ from ....checkout.fetch import (fetch_checkout_lines,update_delivery_method_lists_for_checkout_info,)-from ....checkout.utils import add_variants_to_checkout, invalidate_checkout_prices+from ....checkout.utils import add_variants_to_checkout, invalidate_checkoutfrom ....warehouse.reservations import get_reservation_length, is_reservation_enabledfrom ....webhook.event_types import WebhookEventAsyncTypefrom ...app.dataloaders import get_app_promise@@ -213,7 +213,7 @@ class CheckoutLinesAdd(BaseMutation):)update_checkout_shipping_method_if_invalid(checkout_info, lines)- invalidate_checkout_prices(checkout_info, lines, manager, save=True)+ invalidate_checkout(checkout_info, lines, manager, save=True)cls.call_event(manager.checkout_updated, checkout)return CheckoutLinesAdd(checkout=checkout)diff --git a/saleor/graphql/checkout/mutations/checkout_lines_delete.py b/saleor/graphql/checkout/mutations/checkout_lines_delete.pyindex 146f93cdfe..db1eebcb9b 100644--- a/saleor/graphql/checkout/mutations/checkout_lines_delete.py+++ b/saleor/graphql/checkout/mutations/checkout_lines_delete.py@@ -1,8 +1,9 @@import graphenefrom django.core.exceptions import ValidationError+from ....checkout.error_codes import CheckoutErrorCodefrom ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines-from ....checkout.utils import invalidate_checkout_prices+from ....checkout.utils import invalidate_checkoutfrom ....webhook.event_types import WebhookEventAsyncTypefrom ...core import ResolveInfofrom ...core.descriptions import ADDED_IN_34, DEPRECATED_IN_3X_INPUT@@ -47,23 +48,36 @@ class CheckoutLinesDelete(BaseMutation):]@classmethod- def validate_lines(cls, checkout, lines_to_delete):+ def validate_lines(cls, checkout: Checkout, lines_to_delete_ids: list[str]):lines = checkout.lines.all()all_lines_ids = [str(line.id) for line in lines]- invalid_line_ids = list()- for line_to_delete in lines_to_delete:- if line_to_delete not in all_lines_ids:- line_to_delete = graphene.Node.to_global_id(- "CheckoutLine", line_to_delete- )- invalid_line_ids.append(line_to_delete)-+ gift_line_ids = [str(line.id) for line in lines if line.is_gift]+ invalid_line_ids = set(lines_to_delete_ids).difference(all_lines_ids)+ gift_line_to_delete_ids = set(gift_line_ids).intersection(lines_to_delete_ids)+ invalid_line_global_ids = [+ graphene.Node.to_global_id("CheckoutLine", pk) for pk in invalid_line_ids+ ]+ gift_line_to_delete_global_ids = [+ graphene.Node.to_global_id("CheckoutLine", pk)+ for pk in gift_line_to_delete_ids+ ]if invalid_line_ids:raise ValidationError({"line_id": ValidationError("Provided line_ids aren't part of checkout.",- params={"lines": invalid_line_ids},+ params={"lines": invalid_line_global_ids},+ )+ }+ )++ if gift_line_to_delete_ids:+ raise ValidationError(+ {+ "line_ids": ValidationError(+ "Checkout lines marked as gift can't be deleted.",+ params={"lines": gift_line_to_delete_global_ids},+ code=CheckoutErrorCode.NON_REMOVABLE_GIFT_LINE.value,)})@@ -85,7 +99,7 @@ class CheckoutLinesDelete(BaseMutation):manager = get_plugin_manager_promise(info.context).get()checkout_info = fetch_checkout_info(checkout, lines, manager)update_checkout_shipping_method_if_invalid(checkout_info, lines)- invalidate_checkout_prices(checkout_info, lines, manager, save=True)+ invalidate_checkout(checkout_info, lines, manager, save=True)cls.call_event(manager.checkout_updated, checkout)return CheckoutLinesDelete(checkout=checkout)diff --git a/saleor/graphql/checkout/mutations/checkout_lines_update.py b/saleor/graphql/checkout/mutations/checkout_lines_update.pyindex 8a3bafb6ee..8afe7fc643 100644--- a/saleor/graphql/checkout/mutations/checkout_lines_update.py+++ b/saleor/graphql/checkout/mutations/checkout_lines_update.py@@ -2,6 +2,7 @@ import graphenefrom django.forms import ValidationErrorfrom ....checkout.error_codes import CheckoutErrorCode+from ....checkout.fetch import CheckoutLineInfofrom ....warehouse.reservations import is_reservation_enabledfrom ....webhook.event_types import WebhookEventAsyncTypefrom ...app.dataloaders import get_app_promise@@ -23,6 +24,7 @@ from ...site.dataloaders import get_site_promisefrom ..types import Checkoutfrom .checkout_lines_add import CheckoutLinesAddfrom .utils import (+ CheckoutLineData,check_lines_quantity,get_variants_and_total_quantities,group_lines_input_data_on_update,@@ -136,7 +138,7 @@ class CheckoutLinesUpdate(CheckoutLinesAdd):variants,checkout_lines_data,checkout_info,- lines,+ lines_info,manager,replace,):@@ -158,13 +160,14 @@ class CheckoutLinesUpdate(CheckoutLinesAdd):})+ cls._validate_gift_line(checkout_lines_data, lines_info)return super().clean_input(info,checkout,variants,checkout_lines_data,checkout_info,- lines,+ lines_info,manager,replace,)@@ -221,3 +224,27 @@ class CheckoutLinesUpdate(CheckoutLinesAdd):@classmethoddef _get_grouped_lines_data(cls, lines, existing_lines_info):return group_lines_input_data_on_update(lines, existing_lines_info)++ @classmethod+ def _validate_gift_line(+ cls, lines_input: list[CheckoutLineData], lines_info: list[CheckoutLineInfo]+ ):+ existing_gift_ids = [+ str(line_info.line.id) for line_info in lines_info if line_info.line.is_gift+ ]+ if gift_lines_to_update := [+ line for line in lines_input if line.line_id in existing_gift_ids+ ]:+ global_ids = [+ graphene.Node.to_global_id("CheckoutLine", line.line_id)+ for line in gift_lines_to_update+ ]+ raise ValidationError(+ {+ "line_id": ValidationError(+ "Lines marked as gift can't be edited.",+ code=CheckoutErrorCode.NON_EDITABLE_GIFT_LINE.value,+ params={"lines": global_ids},+ )+ }+ )diff --git a/saleor/graphql/checkout/mutations/checkout_remove_promo_code.py b/saleor/graphql/checkout/mutations/checkout_remove_promo_code.pyindex 3b9e003e50..b27c3b9193 100644--- a/saleor/graphql/checkout/mutations/checkout_remove_promo_code.py+++ b/saleor/graphql/checkout/mutations/checkout_remove_promo_code.py@@ -8,7 +8,7 @@ from ....checkout import modelsfrom ....checkout.error_codes import CheckoutErrorCodefrom ....checkout.fetch import fetch_checkout_info, fetch_checkout_linesfrom ....checkout.utils import (- invalidate_checkout_prices,+ invalidate_checkout,remove_promo_code_from_checkout,remove_voucher_from_checkout,)@@ -101,7 +101,7 @@ class CheckoutRemovePromoCode(BaseMutation):if removed:lines, _ = fetch_checkout_lines(checkout)- invalidate_checkout_prices(+ invalidate_checkout(checkout_info,lines,manager,diff --git a/saleor/graphql/checkout/mutations/checkout_shipping_address_update.py b/saleor/graphql/checkout/mutations/checkout_shipping_address_update.pyindex 957832936d..536ba83eac 100644--- a/saleor/graphql/checkout/mutations/checkout_shipping_address_update.py+++ b/saleor/graphql/checkout/mutations/checkout_shipping_address_update.py@@ -13,7 +13,7 @@ from ....checkout.fetch import ()from ....checkout.utils import (change_shipping_address_in_checkout,- invalidate_checkout_prices,+ invalidate_checkout,is_shipping_required,)from ....core.tracing import traced_atomic_transaction@@ -196,7 +196,7 @@ class CheckoutShippingAddressUpdate(AddressMetadataMixin, BaseMutation, I18nMiximanager,shipping_channel_listings,)- invalidate_prices_updated_fields = invalidate_checkout_prices(+ invalidate_prices_updated_fields = invalidate_checkout(checkout_info, lines, manager, save=False)checkout.save(diff --git a/saleor/graphql/checkout/mutations/checkout_shipping_method_update.py b/saleor/graphql/checkout/mutations/checkout_shipping_method_update.pyindex 72740fc3f3..965145855c 100644--- a/saleor/graphql/checkout/mutations/checkout_shipping_method_update.py+++ b/saleor/graphql/checkout/mutations/checkout_shipping_method_update.py@@ -8,7 +8,7 @@ from ....checkout.fetch import fetch_checkout_info, fetch_checkout_linesfrom ....checkout.utils import (delete_external_shipping_id,get_checkout_metadata,- invalidate_checkout_prices,+ invalidate_checkout,is_shipping_required,set_external_shipping_id,)@@ -212,7 +212,7 @@ class CheckoutShippingMethodUpdate(BaseMutation):delete_external_shipping_id(checkout=checkout)checkout.shipping_method = shipping_method- invalidate_prices_updated_fields = invalidate_checkout_prices(+ invalidate_prices_updated_fields = invalidate_checkout(checkout_info, lines, manager, save=False)checkout.save(@@ -248,7 +248,7 @@ class CheckoutShippingMethodUpdate(BaseMutation):set_external_shipping_id(checkout=checkout, app_shipping_id=delivery_method.id)checkout.shipping_method = None- invalidate_prices_updated_fields = invalidate_checkout_prices(+ invalidate_prices_updated_fields = invalidate_checkout(checkout_info, lines, manager, save=False)checkout.save(@@ -266,7 +266,7 @@ class CheckoutShippingMethodUpdate(BaseMutation):def remove_shipping_method(cls, checkout, checkout_info, lines, manager):checkout.shipping_method = Nonedelete_external_shipping_id(checkout=checkout)- invalidate_prices_updated_fields = invalidate_checkout_prices(+ invalidate_prices_updated_fields = invalidate_checkout(checkout_info, lines, manager, save=False)checkout.save(diff --git a/saleor/graphql/checkout/mutations/utils.py b/saleor/graphql/checkout/mutations/utils.pyindex 98b4807a6f..f5495b9c88 100644--- a/saleor/graphql/checkout/mutations/utils.py+++ b/saleor/graphql/checkout/mutations/utils.py@@ -15,7 +15,9 @@ from typing import (import grapheneimport pytzfrom django.core.exceptions import ObjectDoesNotExist, ValidationError-from django.db.models import Q, QuerySet+from django.db import transaction+from django.db.models import Exists, OuterRef, Q, QuerySet+from prices import Moneyfrom ....checkout import modelsfrom ....checkout.error_codes import CheckoutErrorCode@@ -26,6 +28,9 @@ from ....checkout.utils import (is_shipping_required,)from ....core.exceptions import InsufficientStock, PermissionDenied+from ....discount import DiscountType, DiscountValueType+from ....discount.models import CheckoutLineDiscount, PromotionRule+from ....discount.utils import create_gift_line, get_best_rule_for_checkoutfrom ....permission.enums import CheckoutPermissionsfrom ....product import models as product_modelsfrom ....product.models import ProductChannelListing, ProductVariant@@ -502,3 +507,68 @@ def find_variant_id_when_line_parameter_used(line_info = list(filter(lambda x: (str(x.line.pk) == line_db_id), lines_info))return str(line_info[0].line.variant_id)+++def apply_gift_reward_if_applicable_on_checkout_creation(checkout: "Checkout") -> None:+ """Apply gift reward if applicable on newly created checkout.++ This method apply the gift reward if any gift promotion exists and+ when it's giving the best discount on the current checkout.+ """+ PromotionRuleChannel = PromotionRule.channels.through+ rule_channels = PromotionRuleChannel.objects.filter(channel_id=checkout.channel_id)+ if not PromotionRule.objects.filter(+ Exists(rule_channels.filter(promotionrule_id=OuterRef("pk"))),+ gifts__isnull=False,+ ).exists():+ return++ _set_checkout_base_subtotal_and_total_on_checkout_creation(checkout)++ best_rule_data = get_best_rule_for_checkout(+ checkout, checkout.channel, checkout.get_country()+ )+ if not best_rule_data:+ return++ best_rule, best_discount_amount, gift_listing = best_rule_data+ if not gift_listing:+ return++ with transaction.atomic():+ line, _line_created = create_gift_line(checkout, gift_listing.variant_id)+ CheckoutLineDiscount.objects.create(+ type=DiscountType.ORDER_PROMOTION,+ line=line,+ amount_value=best_discount_amount,+ value_type=DiscountValueType.FIXED,+ value=best_discount_amount,+ promotion_rule=best_rule,+ currency=checkout.currency,+ )+++def _set_checkout_base_subtotal_and_total_on_checkout_creation(+ checkout: "Checkout",+):+ """Calculate and set base subtotal and total for newly created checkout."""+ variants_id = [line.variant_id for line in checkout.lines.all()]+ variant_id_to_discounted_price = {+ variant_id: discounted_price or price+ for variant_id, discounted_price, price in product_models.ProductVariantChannelListing.objects.filter(+ variant_id__in=variants_id,+ channel_id=checkout.channel_id,+ ).values_list("variant_id", "discounted_price_amount", "price_amount")+ }+ subtotal = Decimal("0")+ for line in checkout.lines.all():+ if price_amount := line.price_override:+ price = price_amount+ else:+ price = variant_id_to_discounted_price.get(line.variant_id) or Decimal("0")+ subtotal += price * line.quantity+ checkout.base_subtotal = Money(subtotal, checkout.currency)+ # base total and subtotal is the same, as there is no option to set the+ # delivery method during checkout creation+ checkout.base_total = checkout.base_subtotal+ checkout.save(update_fields=["base_subtotal_amount", "base_total_amount"])diff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.pyindex 4a43aff158..d112bbcf12 100644--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py@@ -86,6 +86,7 @@ FRAGMENT_CHECKOUT_LINE = (fragment CheckoutLine on CheckoutLine {idquantity+ isGifttotalPrice {...Price}@@ -412,7 +413,7 @@ def test_create_checkout_with_reservations(}}- with django_assert_num_queries(65):+ with django_assert_num_queries(66):response = api_client.post_graphql(query, variables)assert get_graphql_content(response)["data"]["checkoutCreate"]assert Checkout.objects.first().lines.count() == 1@@ -430,12 +431,147 @@ def test_create_checkout_with_reservations(}}- with django_assert_num_queries(65):+ with django_assert_num_queries(66):response = api_client.post_graphql(query, variables)assert get_graphql_content(response)["data"]["checkoutCreate"]assert Checkout.objects.first().lines.count() == 10[email protected]_queries(autouse=False)+def test_create_checkout_with_gift_promotion(+ api_client,+ graphql_address_data,+ stock,+ channel_USD,+ product_with_default_variant,+ product_with_single_variant,+ product_with_two_variants,+ gift_promotion_rule,+ count_queries,+):+ checkout_counts = Checkout.objects.count()+ variables = {+ "checkoutInput": {+ "channel": channel_USD.slug,+ "email": "[email protected]",+ "shippingAddress": graphql_address_data,+ "lines": [+ {+ "quantity": 1,+ "variantId": Node.to_global_id(+ "ProductVariant", stock.product_variant.pk+ ),+ },+ {+ "quantity": 2,+ "variantId": Node.to_global_id(+ "ProductVariant",+ product_with_default_variant.variants.first().pk,+ ),+ },+ {+ "quantity": 10,+ "variantId": Node.to_global_id(+ "ProductVariant",+ product_with_single_variant.variants.first().pk,+ ),+ },+ {+ "quantity": 3,+ "variantId": Node.to_global_id(+ "ProductVariant",+ product_with_two_variants.variants.first().pk,+ ),+ },+ {+ "quantity": 2,+ "variantId": Node.to_global_id(+ "ProductVariant",+ product_with_two_variants.variants.last().pk,+ ),+ },+ ],+ }+ }+ data = get_graphql_content(+ api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)+ )+ assert checkout_counts + 1 == Checkout.objects.count()+ assert data["data"]["checkoutCreate"]["checkout"]++[email protected]_queries(autouse=False)+def test_create_checkout_with_order_promotion(+ user_api_client,+ order_promotion_with_rule,+ channel_USD,+ stock,+ product_with_default_variant,+ product_with_single_variant,+ product_with_two_variants,+ graphql_address_data,+ django_assert_num_queries,+ count_queries,+ variant_with_many_stocks,+):+ # given+ variables = {+ "checkoutInput": {+ "channel": channel_USD.slug,+ "email": "[email protected]",+ "shippingAddress": graphql_address_data,+ "lines": [+ {+ "quantity": 10,+ "variantId": Node.to_global_id(+ "ProductVariant", stock.product_variant.pk+ ),+ },+ {+ "quantity": 2,+ "variantId": Node.to_global_id(+ "ProductVariant",+ product_with_default_variant.variants.first().pk,+ ),+ },+ {+ "quantity": 10,+ "variantId": Node.to_global_id(+ "ProductVariant",+ product_with_single_variant.variants.first().pk,+ ),+ },+ {+ "quantity": 3,+ "variantId": Node.to_global_id(+ "ProductVariant",+ product_with_two_variants.variants.first().pk,+ ),+ },+ {+ "quantity": 2,+ "variantId": Node.to_global_id(+ "ProductVariant",+ product_with_two_variants.variants.last().pk,+ ),+ },+ ],+ }+ }++ # when+ with django_assert_num_queries(88):+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)++ # then+ assert Checkout.objects.get().discounts.exists()+ content = get_graphql_content(response)+ data = content["data"]["checkoutCreate"]+ assert not data["errors"]++@pytest.mark.django_db@pytest.mark.count_queries(autouse=False)def test_add_shipping_to_checkout(@@ -965,6 +1101,74 @@ def test_add_checkout_lines_with_reservations(assert not data["errors"][email protected]_queries(autouse=False)+def test_add_checkout_lines_order_discount_applies(+ user_api_client,+ order_promotion_with_rule,+ checkout,+ channel_USD,+ django_assert_num_queries,+ count_queries,+ variant_with_many_stocks,+):+ # given+ Stock.objects.update(quantity=100)+ variant_id = graphene.Node.to_global_id(+ "ProductVariant", variant_with_many_stocks.id+ )++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [{"variantId": variant_id, "quantity": 10}],+ "channelSlug": checkout.channel.slug,+ }++ # when+ with django_assert_num_queries(75):+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)++ # then+ assert checkout.discounts.exists()+ content = get_graphql_content(response)+ data = content["data"]["checkoutLinesAdd"]+ assert not data["errors"]++[email protected]_queries(autouse=False)+def test_add_checkout_lines_gift_discount_applies(+ user_api_client,+ gift_promotion_rule,+ checkout,+ channel_USD,+ django_assert_num_queries,+ count_queries,+ variant_with_many_stocks,+):+ # given+ Stock.objects.update(quantity=100)+ variant_id = graphene.Node.to_global_id(+ "ProductVariant", variant_with_many_stocks.id+ )++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [{"variantId": variant_id, "quantity": 3}],+ "channelSlug": checkout.channel.slug,+ }++ # when+ with django_assert_num_queries(101):+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)++ # then+ assert checkout.lines.count() == 2+ content = get_graphql_content(response)+ data = content["data"]["checkoutLinesAdd"]+ assert not data["errors"]++@pytest.mark.django_db@pytest.mark.count_queries(autouse=False)def test_checkout_shipping_address_update(diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py b/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.pyindex 0c4ca0a8b3..5499c84f36 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py@@ -31,6 +31,9 @@ MUTATION_CHECKOUT_ADD_PROMO_CODE = """idtokenvoucherCode+ lines {+ id+ }discount {amount}@@ -795,7 +798,7 @@ def test_checkout_add_category_code_checkout_on_promotion(assert checkout.subtotal < subtotal_discounted-def test_checkout_add_voucher_code_checkout_on_checkout_promotion_discount(+def test_checkout_add_voucher_code_checkout_on_order_promotion_discount(api_client, checkout_with_item_and_order_discount, voucher):# given@@ -821,6 +824,38 @@ def test_checkout_add_voucher_code_checkout_on_checkout_promotion_discount(checkout_discount.refresh_from_db()+def test_checkout_add_voucher_code_checkout_with_gift_reward(+ api_client, checkout_with_item_and_gift_promotion, voucher+):+ # given+ checkout = checkout_with_item_and_gift_promotion+ gift_line = checkout.lines.get(is_gift=True)+ line_discount = gift_line.discounts.first()++ lines_count = checkout.lines.count()++ variables = {+ "id": to_global_id_or_none(checkout),+ "promoCode": voucher.code,+ }++ # when+ data = _mutate_checkout_add_promo_code(api_client, variables)++ # then+ assert not data["errors"]+ assert data["checkout"]["token"] == str(checkout.token)+ assert data["checkout"]["voucherCode"] == voucher.code+ checkout.refresh_from_db()+ assert checkout.lines.count() == lines_count - 1 == len(data["checkout"]["lines"])+ assert checkout.discount_amount+ assert checkout.discount_name == voucher.name+ with pytest.raises(line_discount._meta.model.DoesNotExist):+ line_discount.refresh_from_db()+ with pytest.raises(gift_line._meta.model.DoesNotExist):+ gift_line.refresh_from_db()++def test_checkout_add_variant_voucher_code_apply_once_per_order(api_client, checkout_with_items, voucher_specific_product_type):diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_billing_address_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_billing_address_update.pyindex f5745953f6..14f075bbf7 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_billing_address_update.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_billing_address_update.py@@ -2,7 +2,7 @@ from unittest import mockimport pytest-from .....checkout.utils import invalidate_checkout_prices+from .....checkout.utils import invalidate_checkoutfrom ....core.utils import to_global_id_or_nonefrom ....tests.utils import get_graphql_content@@ -143,11 +143,11 @@ def test_checkout_billing_address_update_by_id_without_street_address_2(@mock.patch("saleor.graphql.checkout.mutations.checkout_billing_address_update."- "invalidate_checkout_prices",- wraps=invalidate_checkout_prices,+ "invalidate_checkout",+ wraps=invalidate_checkout,)def test_checkout_billing_address_update(- mocked_invalidate_checkout_prices,+ mocked_invalidate_checkout,user_api_client,checkout_with_item,graphql_address_data,@@ -197,7 +197,7 @@ def test_checkout_billing_address_update(assert checkout.billing_address.country == billing_address["country"]assert checkout.billing_address.city == billing_address["city"].upper()assert checkout.last_change != previous_last_change- assert mocked_invalidate_checkout_prices.call_count == 1+ assert mocked_invalidate_checkout.call_count == 1@pytest.mark.parametrize(diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.pyindex 296b9f693c..a7c39822c0 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py@@ -1910,6 +1910,7 @@ def test_checkout_with_voucher_complete_product_on_sale(amount_value=reward_value,currency=channel.currency_code,promotion_rule=rule,+ reason=f"Sale: {graphene.Node.to_global_id('Sale', old_sale_id)}",)catalogue_promotion_without_rules.name = ""diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_create.py b/saleor/graphql/checkout/tests/mutations/test_checkout_create.pyindex 436c37a50c..3860b61070 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_create.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_create.py@@ -28,6 +28,7 @@ MUTATION_CHECKOUT_CREATE = """quantitylines {quantity+ isGift}}errors {@@ -585,6 +586,44 @@ def test_checkout_create_with_custom_price(assert checkout_line.price_override == price+def test_checkout_create_with_gift_reward(+ api_client, stock, channel_USD, gift_promotion_rule+):+ # given+ variant = stock.product_variant+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)+ test_email = "[email protected]"+ quantity = 5++ variables = {+ "checkoutInput": {+ "channel": channel_USD.slug,+ "lines": [{"quantity": quantity, "variantId": variant_id}],+ "email": test_email,+ }+ }+ assert not Checkout.objects.exists()++ # when+ response = api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)+ content = get_graphql_content(response)["data"]["checkoutCreate"]++ # then+ 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() == len(checkout_data["lines"]) == 2+ checkout_line_data = [+ line for line in checkout_data["lines"] if line["isGift"] is False+ ][0]+ assert checkout_line_data["quantity"] == quantity+ gift_line_data = [+ line for line in checkout_data["lines"] if line["isGift"] is True+ ][0]+ assert gift_line_data["quantity"] == 1++def test_checkout_create_with_metadata_in_line(api_client, stock, graphql_address_data, channel_USD):diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_create_from_order.py b/saleor/graphql/checkout/tests/mutations/test_checkout_create_from_order.pyindex 2e64701fa1..b72aa433c3 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_create_from_order.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_create_from_order.py@@ -5,6 +5,7 @@ import pytzfrom .....checkout.error_codes import CheckoutCreateFromOrderUnavailableVariantErrorCodefrom .....checkout.models import Checkout+from .....product.models import ProductVariantChannelListingfrom .....warehouse.models import Stockfrom ....tests.utils import get_graphql_contentfrom ...enums import CheckoutCreateFromOrderErrorCode@@ -26,6 +27,7 @@ mutation CheckoutCreateFromOrder($id: ID!) {checkout{idlines{+ isGiftquantityvariant{id@@ -185,6 +187,55 @@ def test_checkout_create_from_anonymous_order_and_logged_in_user()+def test_checkout_create_from_order_with_gift_reward(+ user_api_client, order_with_lines, gift_promotion_rule+):+ # given+ order_with_lines.user = user_api_client.user+ order_with_lines.save()++ order_lines_count = order_with_lines.lines.count()++ Stock.objects.update(quantity=10)++ variables = {"id": graphene.Node.to_global_id("Order", order_with_lines.pk)}+ # when+ response = user_api_client.post_graphql(+ MUTATION_CHECKOUT_CREATE_FROM_ORDER, variables+ )++ # then+ variants = gift_promotion_rule.gifts.all()+ variant_listings = ProductVariantChannelListing.objects.filter(variant__in=variants)+ top_price, variant_id = max(+ variant_listings.values_list("discounted_price_amount", "variant")+ )+ order_lines_map = {line.variant.pk: line for line in order_with_lines.lines.all()}++ content = get_graphql_content(response)+ data = content["data"]["checkoutCreateFromOrder"]+ checkout = Checkout.objects.get()+ checkout_lines = checkout.lines.all()+ gift_line = checkout_lines.filter(is_gift=True).first()+ order_lines_map[variant_id] = gift_line+ assert checkout.user == order_with_lines.user+ assert checkout.email == order_with_lines.user_email+ checkout_lines_from_response = data["checkout"]["lines"]+ assert (+ len(checkout_lines_from_response)+ == checkout_lines.count()+ == order_lines_count + 1+ )+ checkout_lines_from_response_map = {+ line["variant"]["id"]: line for line in checkout_lines_from_response+ }+ assert not data["unavailableVariants"]+ assert data["checkout"]["id"] == graphene.Node.to_global_id("Checkout", checkout.pk)+ _assert_checkout_lines(+ order_lines_map, checkout_lines, checkout_lines_from_response_map+ )++def test_checkout_create_from_order_when_order_not_found(user_api_client,order_with_lines,diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_delivery_method_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_delivery_method_update.pyindex f990b25c50..853f12c146 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_delivery_method_update.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_delivery_method_update.py@@ -7,7 +7,7 @@ import pytestfrom .....account.models import Addressfrom .....checkout.error_codes import CheckoutErrorCodefrom .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines-from .....checkout.utils import PRIVATE_META_APP_SHIPPING_ID, invalidate_checkout_prices+from .....checkout.utils import PRIVATE_META_APP_SHIPPING_ID, invalidate_checkoutfrom .....plugins.manager import get_plugins_managerfrom .....shipping import models as shipping_modelsfrom .....shipping.utils import convert_to_shipping_method_data@@ -62,11 +62,11 @@ MUTATION_UPDATE_DELIVERY_METHOD = """)@patch("saleor.graphql.checkout.mutations.checkout_delivery_method_update."- "invalidate_checkout_prices",- wraps=invalidate_checkout_prices,+ "invalidate_checkout",+ wraps=invalidate_checkout,)def test_checkout_delivery_method_update(- mock_invalidate_checkout_prices,+ mock_invalidate_checkout,mock_clean_delivery,api_client,delivery_method,@@ -107,7 +107,7 @@ def test_checkout_delivery_method_update(if is_valid_delivery_method:assert not errorsassert getattr(checkout, attribute_name) == delivery_method- assert mock_invalidate_checkout_prices.call_count == 1+ assert mock_invalidate_checkout.call_count == 1else:assert len(errors) == 1assert errors[0]["field"] == "deliveryMethodId"@@ -133,11 +133,11 @@ def test_checkout_delivery_method_update()@patch("saleor.graphql.checkout.mutations.checkout_delivery_method_update."- "invalidate_checkout_prices",- wraps=invalidate_checkout_prices,+ "invalidate_checkout",+ wraps=invalidate_checkout,)def test_checkout_delivery_method_update_no_checkout_metadata(- mock_invalidate_checkout_prices,+ mock_invalidate_checkout,mock_clean_delivery,api_client,delivery_method,@@ -182,7 +182,7 @@ def test_checkout_delivery_method_update_no_checkout_metadata(if is_valid_delivery_method:assert not errorsassert getattr(checkout, attribute_name) == delivery_method- assert mock_invalidate_checkout_prices.call_count == 1+ assert mock_invalidate_checkout.call_count == 1else:assert len(errors) == 1assert errors[0]["field"] == "deliveryMethodId"diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_line_delete.py b/saleor/graphql/checkout/tests/mutations/test_checkout_line_delete.pyindex 3c4ed09d94..20d742edcd 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_line_delete.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_line_delete.py@@ -3,12 +3,13 @@ from unittest import mockimport graphenefrom .....checkout import base_calculations+from .....checkout.error_codes import CheckoutErrorCodefrom .....checkout.fetch import fetch_checkout_info, fetch_checkout_linesfrom .....checkout.utils import (add_variant_to_checkout,add_voucher_to_checkout,calculate_checkout_quantity,- invalidate_checkout_prices,+ invalidate_checkout,)from .....plugins.manager import get_plugins_managerfrom .....warehouse.models import Reservation@@ -31,6 +32,7 @@ MUTATION_CHECKOUT_LINE_DELETE = """errors {fieldmessage+ code}}}@@ -43,12 +45,11 @@ MUTATION_CHECKOUT_LINE_DELETE = """wraps=update_checkout_shipping_method_if_invalid,)@mock.patch(- "saleor.graphql.checkout.mutations.checkout_line_delete."- "invalidate_checkout_prices",- wraps=invalidate_checkout_prices,+ "saleor.graphql.checkout.mutations.checkout_line_delete.invalidate_checkout",+ wraps=invalidate_checkout,)def test_checkout_line_delete(- mocked_invalidate_checkout_prices,+ mocked_invalidate_checkout,mocked_update_shipping_method,user_api_client,checkout_line_with_reservation_in_many_stocks,@@ -79,7 +80,7 @@ def test_checkout_line_delete(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- assert mocked_invalidate_checkout_prices.call_count == 1+ assert mocked_invalidate_checkout.call_count == 1def test_checkout_lines_delete_with_not_applicable_voucher(@@ -175,3 +176,25 @@ def test_with_active_problems_flow(# thenassert not content["data"]["checkoutLineDelete"]["errors"]+++def test_checkout_line_delete_non_removable_gift(user_api_client, checkout_line):+ # given+ checkout = checkout_line.checkout+ line = checkout_line+ line.is_gift = True+ line.save(update_fields=["is_gift"])+ line_id = to_global_id_or_none(line)+ variables = {"id": to_global_id_or_none(checkout), "lineId": line_id}++ # when+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINE_DELETE, variables)+ content = get_graphql_content(response)++ # then+ data = content["data"]["checkoutLineDelete"]+ assert not data["checkout"]+ errors = data["errors"]+ assert len(errors) == 1+ assert errors[0]["field"] == "lineId"+ assert errors[0]["code"] == CheckoutErrorCode.NON_REMOVABLE_GIFT_LINE.namediff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.pyindex 966ca851bd..061ee23be6 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py@@ -12,12 +12,12 @@ from .....checkout.fetch import fetch_checkout_info, fetch_checkout_linesfrom .....checkout.models import Checkoutfrom .....checkout.utils import (calculate_checkout_quantity,- invalidate_checkout_prices,+ invalidate_checkout,recalculate_checkout_discount,)from .....discount import RewardType, RewardValueTypefrom .....plugins.manager import get_plugins_manager-from .....product.models import ProductChannelListing+from .....product.models import ProductChannelListing, ProductVariantChannelListingfrom .....warehouse import WarehouseClickAndCollectOptionfrom .....warehouse.models import Reservation, Stockfrom .....warehouse.tests.utils import get_available_quantity_for_stock@@ -55,6 +55,7 @@ mutation checkoutLinesAdd($id: ID, $lines: [CheckoutLineInput!]!) {variant {id}+ isGift}}errors {@@ -74,12 +75,11 @@ mutation checkoutLinesAdd($id: ID, $lines: [CheckoutLineInput!]!) {wraps=update_checkout_shipping_method_if_invalid,)@mock.patch(- "saleor.graphql.checkout.mutations.checkout_lines_add."- "invalidate_checkout_prices",- wraps=invalidate_checkout_prices,+ "saleor.graphql.checkout.mutations.checkout_lines_add.invalidate_checkout",+ wraps=invalidate_checkout,)def test_checkout_lines_add(- mocked_invalidate_checkout_prices,+ mocked_invalidate_checkout,mocked_update_shipping_method,user_api_client,checkout_with_item,@@ -121,7 +121,7 @@ def test_checkout_lines_add(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- assert mocked_invalidate_checkout_prices.call_count == 1+ assert mocked_invalidate_checkout.call_count == 1@mock.patch(@@ -130,12 +130,11 @@ def test_checkout_lines_add(wraps=update_checkout_shipping_method_if_invalid,)@mock.patch(- "saleor.graphql.checkout.mutations.checkout_lines_add."- "invalidate_checkout_prices",- wraps=invalidate_checkout_prices,+ "saleor.graphql.checkout.mutations.checkout_lines_add.invalidate_checkout",+ wraps=invalidate_checkout,)def test_add_to_existing_line_with_sale_when_checkout_has_voucher(- mocked_invalidate_checkout_prices,+ mocked_invalidate_checkout,mocked_update_shipping_method,user_api_client,checkout_with_item,@@ -340,7 +339,7 @@ def test_add_to_existing_line_catalogue_and_order_discount_applies(assert checkout.discounts.count() == 1-def test_add_to_existing_line_on_promotion_with_voucher_checkout_promotion_not_applies(+def test_add_to_existing_line_on_promotion_with_voucher_order_promotion_not_applies(user_api_client,checkout_with_item,stock,@@ -448,6 +447,119 @@ def test_add_to_existing_line_on_promotion_with_voucher_checkout_promotion_not_a)+def test_add_to_existing_line_catalogue_and_gift_reward_applies(+ user_api_client,+ checkout_with_item,+ stock,+ channel_USD,+ gift_promotion_rule,+ catalogue_promotion_without_rules,+):+ """Ensure that both catalogue and gift reward are applied."""+ # given+ checkout = checkout_with_item+ variant_unit_price = Decimal(100)+ line = checkout.lines.first()+ variant = line.variant+ lines_count = checkout.lines.count()++ # prepare catalogue promotion with 50% discount+ reward_value = Decimal("50.00")+ rule = catalogue_promotion_without_rules.rules.create(+ catalogue_predicate={+ "productPredicate": {+ "ids": [graphene.Node.to_global_id("Product", variant.product.id)]+ }+ },+ reward_value_type=RewardValueType.PERCENTAGE,+ reward_value=reward_value,+ )+ rule.channels.add(channel_USD)++ variant_channel_listing = variant.channel_listings.get(channel=channel_USD)++ variant_channel_listing.price_amount = variant_unit_price+ discount_amount = variant_unit_price * reward_value / 100+ variant_channel_listing.discounted_price_amount = (+ variant_channel_listing.price_amount - discount_amount+ )+ variant_channel_listing.save(+ update_fields=["discounted_price_amount", "price_amount"]+ )++ variant_channel_listing.variantlistingpromotionrule.create(+ promotion_rule=rule,+ discount_amount=discount_amount,+ currency=channel_USD.currency_code,+ )++ variant_id = graphene.Node.to_global_id("ProductVariant", line.variant_id)++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [{"variantId": variant_id, "quantity": 1}],+ "channelSlug": checkout.channel.slug,+ }++ # when+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)++ # then+ line.refresh_from_db()+ checkout.refresh_from_db()++ variant_listing = variant.channel_listings.get(channel=checkout.channel)+ base_unit_price = variant_listing.price_amount+ discounted_unit_price = base_unit_price * Decimal("0.5")+ # catalogue promotion 50%++ expected_total_price = discounted_unit_price * line.quantity++ content = get_graphql_content(response)+ data = content["data"]["checkoutLinesAdd"]+ assert not data["errors"]++ assert checkout.lines.count() == lines_count + 1+ line_data = [+ line_data+ for line_data in data["checkout"]["lines"]+ if line_data["isGift"] is False+ ][0]+ unit_price = line_data["unitPrice"]["gross"]["amount"]+ assert Decimal(unit_price) == discounted_unit_price+ total_price = line_data["totalPrice"]["gross"]["amount"]+ assert Decimal(total_price) == expected_total_price++ gift_line_data = [+ line_data+ for line_data in data["checkout"]["lines"]+ if line_data["isGift"] is True+ ][0]+ unit_price = gift_line_data["unitPrice"]["gross"]["amount"]+ assert Decimal(unit_price) == Decimal("0")+ total_price = gift_line_data["totalPrice"]["gross"]["amount"]+ assert Decimal(total_price) == Decimal("0")++ variants = gift_promotion_rule.gifts.all()+ variant_listings = ProductVariantChannelListing.objects.filter(variant__in=variants)+ top_price, variant_id = max(+ variant_listings.values_list("discounted_price_amount", "variant")+ )+ undiscounted_unit_price = gift_line_data["undiscountedUnitPrice"]["amount"]+ assert Decimal(undiscounted_unit_price) == top_price+ undiscounted_total_price = gift_line_data["undiscountedTotalPrice"]["amount"]+ assert Decimal(undiscounted_total_price) == top_price+ unit_price = gift_line_data["unitPrice"]["gross"]["amount"]+ assert Decimal(unit_price) == Decimal("0")+ total_price = gift_line_data["totalPrice"]["gross"]["amount"]+ assert Decimal(total_price) == Decimal("0")++ checkout_discount_amount = data["checkout"]["discount"]["amount"]+ # Both catalogue and gift discount are only visible on line level+ assert Decimal(checkout_discount_amount) == Decimal("0")+ assert checkout.discounts.count() == 0++def test_checkout_lines_add_with_existing_variant_and_metadata(user_api_client,checkout_with_item,diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_delete.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_delete.pyindex 5a1c3cbb42..19d94f3097 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_delete.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_delete.py@@ -4,7 +4,8 @@ import graphenefrom .....checkout.error_codes import CheckoutErrorCodefrom .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines-from .....checkout.utils import invalidate_checkout_prices+from .....checkout.models import CheckoutLine+from .....checkout.utils import invalidate_checkoutfrom .....plugins.manager import get_plugins_managerfrom ....core.utils import to_global_id_or_nonefrom ....tests.utils import get_graphql_content@@ -40,12 +41,11 @@ MUTATION_CHECKOUT_LINES_DELETE = """wraps=update_checkout_shipping_method_if_invalid,)@mock.patch(- "saleor.graphql.checkout.mutations.checkout_lines_delete."- "invalidate_checkout_prices",- wraps=invalidate_checkout_prices,+ "saleor.graphql.checkout.mutations.checkout_lines_delete.invalidate_checkout",+ wraps=invalidate_checkout,)def test_checkout_lines_delete(- mocked_invalidate_checkout_prices,+ mocked_invalidate_checkout,mocked_update_shipping_method,user_api_client,checkout_with_items,@@ -76,7 +76,7 @@ def test_checkout_lines_delete(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- assert mocked_invalidate_checkout_prices.call_count == 1+ assert mocked_invalidate_checkout.call_count == 1def test_checkout_lines_delete_invalid_checkout_id(@@ -140,3 +140,58 @@ def test_with_active_problems_flow(api_client, checkout_with_problems):# thenassert not content["data"]["checkoutLinesDelete"]["errors"]+++def test_checkout_lines_delete_non_removable_gift(user_api_client, checkout_with_items):+ # given+ checkout = checkout_with_items+ gift_line = checkout.lines.first()+ gift_line.is_gift = True+ gift_line.save(update_fields=["is_gift"])+ non_gift_line = checkout.lines.last()+ gift_line_id = to_global_id_or_none(gift_line)+ non_gift_line_id = to_global_id_or_none(non_gift_line)+ lines_list = [gift_line_id, non_gift_line_id]++ variables = {"id": to_global_id_or_none(checkout), "linesIds": lines_list}++ # when+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_DELETE, variables)+ content = get_graphql_content(response)++ # then+ data = content["data"]["checkoutLinesDelete"]+ assert not data["checkout"]+ errors = data["errors"]+ assert len(errors) == 1+ assert errors[0]["field"] == "lineIds"+ assert errors[0]["code"] == CheckoutErrorCode.NON_REMOVABLE_GIFT_LINE.name+ assert errors[0]["lines"] == [gift_line_id]+++def test_checkout_lines_delete_not_associated_with_checkout(+ user_api_client, checkout_with_items, checkouts_list, variant+):+ # given+ checkout = checkout_with_items+ wrong_checkout = checkouts_list[0]+ line = CheckoutLine.objects.create(+ checkout=wrong_checkout,+ variant=variant,+ quantity=1,+ )+ line_id = to_global_id_or_none(line)+ variables = {"id": to_global_id_or_none(checkout), "linesIds": [line_id]}++ # when+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_DELETE, variables)+ content = get_graphql_content(response)++ # then+ data = content["data"]["checkoutLinesDelete"]+ assert not data["checkout"]+ errors = data["errors"]+ assert len(errors) == 1+ assert errors[0]["field"] == "lineId"+ assert errors[0]["code"] == CheckoutErrorCode.INVALID.name+ assert errors[0]["lines"] == [line_id]diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.pyindex 141110fc28..64c03d118a 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py@@ -12,7 +12,7 @@ from .....checkout.models import Checkout, CheckoutLinefrom .....checkout.utils import (add_variant_to_checkout,calculate_checkout_quantity,- invalidate_checkout_prices,+ invalidate_checkout,)from .....plugins.manager import get_plugins_managerfrom .....product.models import ProductChannelListing@@ -52,6 +52,7 @@ MUTATION_CHECKOUT_LINES_UPDATE = """codemessagevariants+ lines}}}@@ -64,12 +65,11 @@ MUTATION_CHECKOUT_LINES_UPDATE = """wraps=update_checkout_shipping_method_if_invalid,)@mock.patch(- "saleor.graphql.checkout.mutations.checkout_lines_add."- "invalidate_checkout_prices",- wraps=invalidate_checkout_prices,+ "saleor.graphql.checkout.mutations.checkout_lines_add.invalidate_checkout",+ wraps=invalidate_checkout,)def test_checkout_lines_update(- mocked_invalidate_checkout_prices,+ mocked_invalidate_checkout,mocked_update_shipping_method,user_api_client,checkout_with_item,@@ -107,7 +107,7 @@ def test_checkout_lines_update(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- assert mocked_invalidate_checkout_prices.call_count == 1+ assert mocked_invalidate_checkout.call_count == 1@mock.patch(@@ -1155,3 +1155,29 @@ def test_with_active_problems_flow(# thenassert not content["data"]["checkoutLinesUpdate"]["errors"]+++def test_checkout_lines_update_quantity_gift(user_api_client, checkout_with_item):+ # given+ checkout = checkout_with_item+ line = checkout.lines.first()+ line.is_gift = True+ line.save(update_fields=["is_gift"])+ line_id = to_global_id_or_none(line)+ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [{"lineId": line_id, "quantity": 0}],+ }++ # when+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["checkoutLinesUpdate"]+ assert not data["checkout"]+ errors = data["errors"]+ assert len(errors) == 1+ assert errors[0]["field"] == "lineId"+ assert errors[0]["code"] == CheckoutErrorCode.NON_EDITABLE_GIFT_LINE.name+ assert errors[0]["lines"] == [line_id]diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_remove_promo_code.py b/saleor/graphql/checkout/tests/mutations/test_checkout_remove_promo_code.pyindex bd89f1808a..408e2ca845 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_remove_promo_code.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_remove_promo_code.py@@ -24,6 +24,9 @@ MUTATION_CHECKOUT_REMOVE_PROMO_CODE = """checkout {tokenvoucherCode+ lines {+ id+ }discount {amount}@@ -302,7 +305,7 @@ def test_checkout_remove_voucher_code_invalidates_price(assert data["checkout"]["totalPrice"]["gross"]["amount"] == expected_total-def test_checkout_remove_voucher_code_checkout_promotion_discount_applied(+def test_checkout_remove_voucher_code_order_promotion_discount_applied(api_client, checkout_with_voucher, order_promotion_rule):# given@@ -335,6 +338,40 @@ def test_checkout_remove_voucher_code_checkout_promotion_discount_applied(assert checkout.discounts.count() == 1+def test_checkout_remove_voucher_code_gift_reward_applied(+ api_client, checkout_with_voucher, gift_promotion_rule+):+ # given+ checkout = checkout_with_voucher++ assert checkout.voucher_code is not None+ previous_checkout_last_change = checkout.last_change++ lines_count = checkout.lines.count()++ variables = {+ "id": to_global_id_or_none(checkout),+ "promoCode": checkout.voucher_code,+ }++ # when+ data = _mutate_checkout_remove_promo_code(api_client, variables)++ # then+ checkout.refresh_from_db()+ assert not data["errors"]+ assert data["checkout"]["token"] == str(checkout.token)+ assert data["checkout"]["voucherCode"] is None+ assert data["checkout"]["discount"]["amount"] == 0+ assert checkout.voucher_code is None+ assert not checkout.discount_amount+ assert checkout.last_change != previous_checkout_last_change+ assert not checkout.discounts.all()+ assert checkout.lines.count() == lines_count + 1 == len(data["checkout"]["lines"])+ gift_line = checkout.lines.get(is_gift=True)+ assert gift_line.discounts.count() == 1++def test_with_active_problems_flow(api_client,checkout_with_problems,diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_address_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_address_update.pyindex f1714c40d0..dace332377 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_address_update.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_address_update.py@@ -11,7 +11,7 @@ from .....checkout.models import Checkoutfrom .....checkout.utils import (add_variant_to_checkout,add_voucher_to_checkout,- invalidate_checkout_prices,+ invalidate_checkout,)from .....plugins.base_plugin import ExcludedShippingMethodfrom .....plugins.manager import get_plugins_manager@@ -91,11 +91,11 @@ MUTATION_CHECKOUT_SHIPPING_ADDRESS_WITH_METADATA_UPDATE = """)@mock.patch("saleor.graphql.checkout.mutations.checkout_shipping_address_update."- "invalidate_checkout_prices",- wraps=invalidate_checkout_prices,+ "invalidate_checkout",+ wraps=invalidate_checkout,)def test_checkout_shipping_address_with_metadata_update(- mocked_invalidate_checkout_prices,+ mocked_invalidate_checkout,mocked_update_shipping_method,user_api_client,checkout_with_item,@@ -137,7 +137,7 @@ def test_checkout_shipping_address_with_metadata_update(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- assert mocked_invalidate_checkout_prices.call_count == 1+ assert mocked_invalidate_checkout.call_count == 1@mock.patch(diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.pyindex 456ecf929a..9f950db075 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.py@@ -11,7 +11,7 @@ from .....checkout.fetch import (fetch_checkout_lines,get_delivery_method_info,)-from .....checkout.utils import PRIVATE_META_APP_SHIPPING_ID, invalidate_checkout_prices+from .....checkout.utils import PRIVATE_META_APP_SHIPPING_ID, invalidate_checkoutfrom .....plugins.base_plugin import ExcludedShippingMethodfrom .....plugins.manager import get_plugins_managerfrom .....shipping import models as shipping_models@@ -45,11 +45,11 @@ MUTATION_UPDATE_SHIPPING_METHOD = """)@patch("saleor.graphql.checkout.mutations.checkout_shipping_method_update."- "invalidate_checkout_prices",- wraps=invalidate_checkout_prices,+ "invalidate_checkout",+ wraps=invalidate_checkout,)def test_checkout_shipping_method_update(- mocked_invalidate_checkout_prices,+ mocked_invalidate_checkout,mock_clean_shipping,staff_api_client,shipping_method,@@ -92,7 +92,7 @@ def test_checkout_shipping_method_update(assert data["checkout"]["token"] == str(checkout.token)assert checkout.shipping_method == shipping_methodassert checkout.last_change != previous_last_change- assert mocked_invalidate_checkout_prices.call_count == 1+ assert mocked_invalidate_checkout.call_count == 1else:assert len(errors) == 1assert errors[0]["field"] == "shippingMethod"diff --git a/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py b/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.pyindex 45f95d069e..a74f429ad2 100644--- a/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py+++ b/saleor/graphql/checkout/tests/mutations/test_order_create_from_checkout.py@@ -12,7 +12,7 @@ from prices import Moneyfrom .....checkout import calculationsfrom .....checkout.error_codes import OrderCreateFromCheckoutErrorCodefrom .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines-from .....checkout.models import Checkout+from .....checkout.models import Checkout, CheckoutLinefrom .....core.taxes import TaxError, zero_money, zero_taxed_moneyfrom .....discount import DiscountType, DiscountValueType, RewardValueTypefrom .....discount.models import CheckoutLineDiscount, Promotion@@ -21,6 +21,7 @@ from .....giftcard.models import GiftCard, GiftCardEventfrom .....order import OrderOrigin, OrderStatusfrom .....order.models import Fulfillment, Orderfrom .....plugins.manager import PluginsManager, get_plugins_manager+from .....product.models import ProductVariantChannelListingfrom .....tests.utils import flush_post_commit_hooksfrom .....warehouse.models import Reservation, Stock, WarehouseClickAndCollectOptionfrom .....warehouse.tests.utils import get_available_quantity_for_stock@@ -1059,6 +1060,143 @@ def test_order_from_checkout_on_order_promotion(assert order_discount.type == DiscountType.ORDER_PROMOTION+def test_order_from_checkout_on_gift_promotion(+ app_api_client,+ checkout_with_item_and_gift_promotion,+ gift_promotion_rule,+ permission_handle_checkouts,+ permission_manage_checkouts,+ address,+ shipping_method,+):+ # given+ checkout = checkout_with_item_and_gift_promotion+ checkout.shipping_address = address+ checkout.shipping_method = shipping_method+ checkout.billing_address = address+ checkout.save()+ line_count = checkout.lines.count()++ variables = {+ "id": graphene.Node.to_global_id("Checkout", checkout.pk),+ }++ # when+ response = app_api_client.post_graphql(+ MUTATION_ORDER_CREATE_FROM_CHECKOUT,+ variables,+ permissions=[permission_handle_checkouts, permission_manage_checkouts],+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["orderCreateFromCheckout"]+ assert not data["errors"]++ order = Order.objects.first()+ assert order.status == OrderStatus.UNCONFIRMED+ assert order.origin == OrderOrigin.CHECKOUT+ assert not order.original++ assert not order.discounts.all()+ assert order.lines.count() == line_count+ gift_line = order.lines.get(is_gift=True)+ assert gift_line.discounts.count() == 1+ line_discount = gift_line.discounts.first()+ assert line_discount.promotion_rule == gift_promotion_rule+ assert line_discount.type == DiscountType.ORDER_PROMOTION+++def test_order_from_checkout_on_catalogue_and_gift_promotion(+ app_api_client,+ checkout_with_item_on_promotion,+ gift_promotion_rule,+ permission_handle_checkouts,+ permission_manage_checkouts,+ address,+ shipping_method,+):+ # given+ checkout = checkout_with_item_on_promotion+ checkout.shipping_address = address+ checkout.shipping_method = shipping_method+ checkout.billing_address = address+ checkout.save()++ gift_promotion_rule.order_predicate = {+ "discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": 10}}}+ }+ gift_promotion_rule.save(update_fields=["order_predicate"])++ variants = gift_promotion_rule.gifts.all()+ variant_listings = ProductVariantChannelListing.objects.filter(variant__in=variants)+ top_price, variant_id = max(+ variant_listings.values_list("discounted_price_amount", "variant")+ )++ # add gift reward+ gift_line = CheckoutLine.objects.create(+ checkout=checkout,+ quantity=1,+ variant_id=variant_id,+ is_gift=True,+ currency="USD",+ )+ CheckoutLineDiscount.objects.create(+ line=gift_line,+ promotion_rule=gift_promotion_rule,+ type=DiscountType.ORDER_PROMOTION,+ value_type=RewardValueType.FIXED,+ value=top_price,+ amount_value=top_price,+ currency=checkout.channel.currency_code,+ )++ line_count = checkout.lines.count()++ variables = {+ "id": graphene.Node.to_global_id("Checkout", checkout.pk),+ }++ # when+ response = app_api_client.post_graphql(+ MUTATION_ORDER_CREATE_FROM_CHECKOUT,+ variables,+ permissions=[permission_handle_checkouts, permission_manage_checkouts],+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["orderCreateFromCheckout"]+ assert not data["errors"]++ order = Order.objects.first()+ assert order.status == OrderStatus.UNCONFIRMED+ assert order.origin == OrderOrigin.CHECKOUT+ assert not order.original++ assert not order.discounts.all()+ assert order.lines.count() == line_count+ gift_line = order.lines.get(is_gift=True)++ assert gift_line.discounts.count() == 1+ gift_line_discount = gift_line.discounts.first()+ assert gift_line_discount.promotion_rule == gift_promotion_rule+ assert gift_line_discount.type == DiscountType.ORDER_PROMOTION++ line = order.lines.get(is_gift=False)+ assert line.sale_id+ assert line.unit_discount_reason+ assert line.discounts.count() == 1+ line_discount = line.discounts.first()+ assert line_discount.promotion_rule+ assert line_discount.type == DiscountType.PROMOTION++ assert (+ order.undiscounted_total - order.total+ ).gross.amount == top_price + line_discount.amount_value++def test_order_from_checkout_multiple_rules_applied(app_api_client,checkout_with_item_on_promotion,diff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.pyindex 6c566b35c6..2d44994866 100644--- a/saleor/graphql/checkout/tests/test_checkout.py+++ b/saleor/graphql/checkout/tests/test_checkout.py@@ -31,7 +31,7 @@ from ....payment.interface import ()from ....plugins.manager import get_plugins_managerfrom ....plugins.tests.sample_plugins import ActiveDummyPaymentGateway-from ....product.models import ProductVariant+from ....product.models import ProductVariant, ProductVariantChannelListingfrom ....shipping.models import ShippingMethodTranslationfrom ....shipping.utils import convert_to_shipping_method_datafrom ....tests.utils import dummy_editorjs@@ -1485,6 +1485,10 @@ QUERY_CHECKOUT_PRICES = """}}lines {+ isGift+ variant {+ id+ }unitPrice {gross {amount@@ -1811,6 +1815,68 @@ def test_checkout_prices_with_order_promotion(assert data["lines"][0]["undiscountedTotalPrice"]["amount"] == subtotal_price.amount+def test_checkout_prices_with_gift_promotion(+ user_api_client, checkout_with_item_and_gift_promotion, gift_promotion_rule+):+ # given+ query = QUERY_CHECKOUT_PRICES+ checkout = checkout_with_item_and_gift_promotion+ variants = gift_promotion_rule.gifts.all()+ variant_listings = ProductVariantChannelListing.objects.filter(variant__in=variants)+ top_price, variant_id = max(+ variant_listings.values_list("discounted_price_amount", "variant")+ )++ variables = {"id": to_global_id_or_none(checkout)}++ manager = get_plugins_manager(allow_replica=False)+ lines, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, manager)++ # when+ response = user_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ data = content["data"]["checkout"]++ # then+ assert data["token"] == str(checkout.token)+ assert len(data["lines"]) == checkout.lines.count()++ line = checkout.lines.get(is_gift=False)+ variant = line.variant+ variant_listing = variant.channel_listings.get(channel=checkout.channel)+ unit_price = variant.get_price(variant_listing)+ subtotal_price = unit_price * line.quantity+ shipping_price = base_calculations.base_checkout_delivery_price(+ checkout_info, lines+ )+ total_price = subtotal_price + shipping_price++ assert data["discount"]["amount"] == 0+ assert data["totalPrice"]["gross"]["amount"] == (total_price.amount)+ assert data["subtotalPrice"]["gross"]["amount"] == (subtotal_price.amount)+ line_data = [+ line_data for line_data in data["lines"] if line_data["isGift"] is False+ ][0]+ assert line_data["unitPrice"]["gross"]["amount"] == (+ round((subtotal_price.amount) / line.quantity, 2)+ )+ assert line_data["totalPrice"]["gross"]["amount"] == subtotal_price.amount++ assert line_data["undiscountedUnitPrice"]["amount"] == unit_price.amount+ assert line_data["undiscountedTotalPrice"]["amount"] == subtotal_price.amount+ gift_line = [+ line_data for line_data in data["lines"] if line_data["isGift"] is True+ ][0]+ assert gift_line["unitPrice"]["gross"]["amount"] == 0+ assert gift_line["totalPrice"]["gross"]["amount"] == 0+ assert gift_line["undiscountedUnitPrice"]["amount"] == top_price+ assert gift_line["undiscountedTotalPrice"]["amount"] == top_price+ assert gift_line["variant"]["id"] == graphene.Node.to_global_id(+ "ProductVariant", variant_id+ )++def test_checkout_display_gross_prices_use_default(user_api_client, checkout_with_item):# givenvariables = {"id": to_global_id_or_none(checkout_with_item)}@@ -2112,6 +2178,7 @@ def test_query_checkout_lines(edges {node {id+ isGift}}}@@ -2128,6 +2195,8 @@ def test_query_checkout_lines(graphene.Node.to_global_id("CheckoutLine", item.pk) for item in checkout]assert expected_lines_ids == checkout_lines_ids+ is_gift_flags = [line["node"]["isGift"] for line in lines]+ assert all([item is False for item in is_gift_flags])def test_query_checkout_lines_with_meta(diff --git a/saleor/graphql/checkout/tests/test_checkout_price_expiration.py b/saleor/graphql/checkout/tests/test_checkout_price_expiration.pyindex 0cf9a76f7a..e0e1885174 100644--- a/saleor/graphql/checkout/tests/test_checkout_price_expiration.py+++ b/saleor/graphql/checkout/tests/test_checkout_price_expiration.py@@ -7,7 +7,7 @@ from django.utils import timezonefrom freezegun import freeze_timefrom ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines-from ....checkout.utils import invalidate_checkout_prices+from ....checkout.utils import invalidate_checkoutfrom ....plugins.manager import get_plugins_managerfrom ...tests.utils import get_graphql_content@@ -23,9 +23,7 @@ mutation addCheckoutLines($checkoutId: ID!, $line: CheckoutLineInput!) {"""-@patch(- "saleor.graphql.checkout.mutations.checkout_lines_add.invalidate_checkout_prices"-)+@patch("saleor.graphql.checkout.mutations.checkout_lines_add.invalidate_checkout")def test_checkout_lines_add_invalidate_prices(mocked_function,api_client,@@ -68,9 +66,7 @@ mutation updateCheckoutLines($token: UUID!, $line: CheckoutLineUpdateInput!) {"""-@patch(- "saleor.graphql.checkout.mutations.checkout_lines_add.invalidate_checkout_prices"-)+@patch("saleor.graphql.checkout.mutations.checkout_lines_add.invalidate_checkout")def test_checkout_lines_update_invalidate_prices(mocked_function,api_client,@@ -113,9 +109,7 @@ mutation deleteCheckoutLines($token: UUID!, $lineId: ID!){"""-@patch(- "saleor.graphql.checkout.mutations.checkout_lines_delete.invalidate_checkout_prices"-)+@patch("saleor.graphql.checkout.mutations.checkout_lines_delete.invalidate_checkout")def test_checkout_lines_delete_invalidate_prices(mocked_function,api_client,@@ -154,9 +148,7 @@ mutation deleteCheckoutLine($token: UUID!, $lineId: ID!){"""-@patch(- "saleor.graphql.checkout.mutations.checkout_line_delete.invalidate_checkout_prices"-)+@patch("saleor.graphql.checkout.mutations.checkout_line_delete.invalidate_checkout")def test_checkout_line_delete_invalidate_prices(mocked_function,api_client,@@ -197,7 +189,7 @@ mutation UpdateCheckoutShippingAddress($token: UUID!, $address: AddressInput!) {@patch("saleor.graphql.checkout.mutations.checkout_shipping_address_update"- ".invalidate_checkout_prices"+ ".invalidate_checkout")def test_checkout_shipping_address_update_invalidate_prices(mocked_function,@@ -240,7 +232,7 @@ mutation UpdateCheckoutBillingAddress($token: UUID!, $address: AddressInput!) {@patch("saleor.graphql.checkout.mutations.checkout_billing_address_update"- ".invalidate_checkout_prices"+ ".invalidate_checkout")def test_checkout_billing_address_update_invalidate_prices(mocked_function,@@ -284,11 +276,11 @@ mutation updateCheckoutShippingOptions($token: UUID!, $shippingMethodId: ID) {@mock.patch("saleor.graphql.checkout.mutations.checkout_shipping_method_update."- "invalidate_checkout_prices",- wraps=invalidate_checkout_prices,+ "invalidate_checkout",+ wraps=invalidate_checkout,)def test_checkout_shipping_method_update_invalidate_prices(- mocked_invalidate_checkout_prices,+ mocked_invalidate_checkout,api_client,checkout_with_shipping_address,shipping_method,@@ -311,7 +303,7 @@ def test_checkout_shipping_method_update_invalidate_prices(# thencheckout.refresh_from_db()assert not response["data"]["checkoutShippingMethodUpdate"]["errors"]- assert mocked_invalidate_checkout_prices.call_count == 1+ assert mocked_invalidate_checkout.call_count == 1UPDATE_CHECKOUT_DELIVERY_METHOD = """@@ -328,11 +320,11 @@ mutation updateCheckoutDeliveryOptions($token: UUID!, $deliveryMethodId: ID!) {@mock.patch("saleor.graphql.checkout.mutations.checkout_delivery_method_update."- "invalidate_checkout_prices",- wraps=invalidate_checkout_prices,+ "invalidate_checkout",+ wraps=invalidate_checkout,)def test_checkout_delivery_method_update_invalidate_prices(- mocked_invalidate_checkout_prices,+ mocked_invalidate_checkout,api_client,checkout_with_shipping_address_for_cc,warehouses_for_cc,@@ -354,11 +346,11 @@ def test_checkout_delivery_method_update_invalidate_prices(# thencheckout.refresh_from_db()assert not response["data"]["checkoutDeliveryMethodUpdate"]["errors"]- assert mocked_invalidate_checkout_prices.call_count == 1+ assert mocked_invalidate_checkout.call_count == 1@freeze_time("2020-12-12 12:00:00")-def test_invalidate_checkout_prices_with_save(checkout, plugins_manager):+def test_invalidate_checkout_with_save(checkout, plugins_manager):# givencheckout.price_expiration = timezone.now() + timedelta(minutes=5)checkout.save(update_fields=["price_expiration"])@@ -366,7 +358,7 @@ def test_invalidate_checkout_prices_with_save(checkout, plugins_manager):checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)# when- updated_fields = invalidate_checkout_prices(+ updated_fields = invalidate_checkout(checkout_info, lines, plugins_manager, save=True)@@ -377,7 +369,7 @@ def test_invalidate_checkout_prices_with_save(checkout, plugins_manager):@freeze_time("2020-12-12 12:00:00")-def test_invalidate_checkout_prices_without_save(checkout, plugins_manager):+def test_invalidate_checkout_without_save(checkout, plugins_manager):# givenoriginal_expiration = checkout.price_expiration = timezone.now() + timedelta(minutes=5@@ -387,7 +379,7 @@ def test_invalidate_checkout_prices_without_save(checkout, plugins_manager):checkout_info = fetch_checkout_info(checkout, lines, plugins_manager)# when- updated_fields = invalidate_checkout_prices(+ updated_fields = invalidate_checkout(checkout_info, lines, plugins_manager, save=False)diff --git a/saleor/graphql/checkout/tests/test_utils.py b/saleor/graphql/checkout/tests/test_utils.pynew file mode 100644index 0000000000..a1cd93ec64--- /dev/null+++ b/saleor/graphql/checkout/tests/test_utils.py@@ -0,0 +1,50 @@+from ..mutations.utils import apply_gift_reward_if_applicable_on_checkout_creation+++def test_apply_gift_reward_if_applicable(+ checkout_with_item, gift_promotion_rule, order_promotion_rule, promotion_rule+):+ # given+ checkout = checkout_with_item+ lines_count = checkout.lines.count()++ # when+ apply_gift_reward_if_applicable_on_checkout_creation(checkout)++ # then+ checkout.refresh_from_db()+ assert checkout.lines.count() == lines_count + 1+ gift_line = checkout.lines.filter(is_gift=True).first()+ assert gift_line+ assert gift_line.discounts.count() == 1+++def test_apply_gift_reward_if_applicable_no_gift_promotion_rules(+ checkout_with_item, order_promotion_rule, promotion_rule+):+ # given+ checkout = checkout_with_item+ lines_count = checkout.lines.count()++ # when+ apply_gift_reward_if_applicable_on_checkout_creation(checkout)++ # then+ checkout.refresh_from_db()+ assert checkout.lines.count() == lines_count+++def test_apply_gift_reward_if_applicable_no_gift_promotion_rules_for_checkout_channel(+ checkout_with_item, gift_promotion_rule, order_promotion_rule, promotion_rule+):+ # given+ checkout = checkout_with_item+ lines_count = checkout.lines.count()+ gift_promotion_rule.channels.remove(checkout.channel)++ # when+ apply_gift_reward_if_applicable_on_checkout_creation(checkout)++ # then+ checkout.refresh_from_db()+ assert checkout.lines.count() == lines_countdiff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.pyindex 78049a88af..30a39871f3 100644--- a/saleor/graphql/checkout/types.py+++ b/saleor/graphql/checkout/types.py@@ -47,6 +47,7 @@ from ..core.descriptions import (ADDED_IN_313,ADDED_IN_315,ADDED_IN_318,+ ADDED_IN_319,DEPRECATED_IN_3X_FIELD,PREVIEW_FEATURE,)@@ -255,6 +256,9 @@ class CheckoutLine(ModelObjectType[models.CheckoutLine]):+ ADDED_IN_315+ PREVIEW_FEATURE,)+ is_gift = graphene.Boolean(+ description="Determine if the line is a gift." + ADDED_IN_319 + PREVIEW_FEATURE,+ )class Meta:description = "Represents an item in the checkout."diff --git a/saleor/graphql/discount/dataloaders.py b/saleor/graphql/discount/dataloaders.pyindex 6e5be42d23..b5f927107b 100644--- a/saleor/graphql/discount/dataloaders.py+++ b/saleor/graphql/discount/dataloaders.py@@ -18,6 +18,7 @@ from ...discount.models import (VoucherChannelListing,VoucherCode,)+from ...product.models import ProductVariantfrom ..channel.dataloaders import ChannelBySlugLoaderfrom ..core.dataloaders import DataLoader@@ -449,3 +450,26 @@ class PredicateByPromotionIdLoader(DataLoader):.load_many(keys).then(with_rules))+++class GiftsByPromotionRuleIDLoader(DataLoader):+ context_key = "gifts_by_promotion_rule"++ def batch_load(self, keys):+ PromotionRuleGift = PromotionRule.gifts.through+ rule_gifts = (+ PromotionRuleGift.objects.using(self.database_connection_name)+ .filter(promotionrule_id__in=keys)+ .order_by("pk")+ )+ gifts = (+ ProductVariant.objects.using(self.database_connection_name)+ .filter(Exists(rule_gifts.filter(productvariant_id=OuterRef("id"))))+ .in_bulk()+ )+ rule_to_gifts_map = defaultdict(list)+ for rule_id, variant_id in rule_gifts.values_list(+ "promotionrule_id", "productvariant_id"+ ):+ rule_to_gifts_map[rule_id].append(gifts.get(variant_id))+ return [rule_to_gifts_map.get(rule_id, []) for rule_id in keys]diff --git a/saleor/graphql/discount/mutations/promotion/promotion_create.py b/saleor/graphql/discount/mutations/promotion/promotion_create.pyindex 930377f810..5f96b4f69c 100644--- a/saleor/graphql/discount/mutations/promotion/promotion_create.py+++ b/saleor/graphql/discount/mutations/promotion/promotion_create.py@@ -41,9 +41,15 @@ class PromotionCreateError(Error):rules_limit = graphene.Int(description="Limit of rules with orderPredicate defined.")- exceed_by = graphene.Int(+ rules_limit_exceed_by = graphene.Int(description="Number of rules with orderPredicate defined exceeding the limit.")+ gifts_limit = graphene.Int(description="Limit of gifts assigned to promotion rule.")+ gifts_limit_exceed_by = graphene.Int(+ description=(+ "Number of gifts defined for this promotion rule exceeding the limit."+ )+ )class PromotionRuleInput(PromotionRuleBaseInput):@@ -51,6 +57,12 @@ class PromotionRuleInput(PromotionRuleBaseInput):graphene.ID,description="List of channel ids to which the rule should apply to.",)+ gifts = NonNullList(+ graphene.ID,+ description="Product variant IDs available as a gift to choose."+ + ADDED_IN_319+ + PREVIEW_FEATURE,+ )class Meta:doc_category = DOC_CATEGORY_DISCOUNTS@@ -156,7 +168,7 @@ class PromotionCreate(ModelMutation):code=PromotionCreateErrorCode.RULES_NUMBER_LIMIT.value,params={"rules_limit": rules_limit,- "exceed_by": exceed_by,+ "rules_limit_exceed_by": exceed_by,},)}@@ -166,6 +178,12 @@ class PromotionCreate(ModelMutation):if channel_ids := rule_data.get("channels"):channels = cls.clean_channels(info, channel_ids, index, errors)rule_data["channels"] = channels+ if gift_ids := rule_data.get("gifts"):+ instances = cls.get_nodes_or_error(+ gift_ids, "gifts", schema=info.schema+ )+ rule_data["gifts"] = instances+clean_promotion_rule(rule_data, promotion_type, errors, PromotionCreateErrorCode, index)@@ -218,7 +236,10 @@ class PromotionCreate(ModelMutation):if rules_data := cleaned_data.get("rules"):for rule_data in rules_data:channels = rule_data.pop("channels", None)+ gifts = rule_data.pop("gifts", None)rule = models.PromotionRule(promotion=instance, **rule_data)+ if gifts:+ rule.gifts.set(gifts)if channels:rules_with_channels_to_add.append((rule, channels))rules.append(rule)diff --git a/saleor/graphql/discount/mutations/promotion/promotion_rule_create.py b/saleor/graphql/discount/mutations/promotion/promotion_rule_create.pyindex ef6cb4ab78..e856212db5 100644--- a/saleor/graphql/discount/mutations/promotion/promotion_rule_create.py+++ b/saleor/graphql/discount/mutations/promotion/promotion_rule_create.py@@ -34,9 +34,15 @@ class PromotionRuleCreateError(Error):rules_limit = graphene.Int(description="Limit of rules with orderPredicate defined.")- exceed_by = graphene.Int(+ rules_limit_exceed_by = graphene.Int(description="Number of rules with orderPredicate defined exceeding the limit.")+ gifts_limit = graphene.Int(description="Limit of gifts assigned to promotion rule.")+ gifts_limit_exceed_by = graphene.Int(+ description=(+ "Number of gifts defined for this promotion rule exceeding the limit."+ )+ )class PromotionRuleCreate(ModelMutation):diff --git a/saleor/graphql/discount/mutations/promotion/promotion_rule_update.py b/saleor/graphql/discount/mutations/promotion/promotion_rule_update.pyindex f811bf9f5d..2e0266193f 100644--- a/saleor/graphql/discount/mutations/promotion/promotion_rule_update.py+++ b/saleor/graphql/discount/mutations/promotion/promotion_rule_update.py@@ -11,7 +11,7 @@ from .....product.tasks import update_discounted_prices_taskfrom .....webhook.event_types import WebhookEventAsyncTypefrom ....app.dataloaders import get_app_promisefrom ....core import ResolveInfo-from ....core.descriptions import ADDED_IN_317, PREVIEW_FEATURE+from ....core.descriptions import ADDED_IN_317, ADDED_IN_319, PREVIEW_FEATUREfrom ....core.doc_category import DOC_CATEGORY_DISCOUNTSfrom ....core.mutations import ModelMutationfrom ....core.types import Error, NonNullList@@ -35,6 +35,12 @@ class PromotionRuleUpdateError(Error):description="List of channel IDs which causes the error.",required=False,)+ gifts_limit = graphene.Int(description="Limit of gifts assigned to promotion rule.")+ gifts_limit_exceed_by = graphene.Int(+ description=(+ "Number of gifts defined for this promotion rule exceeding the limit."+ )+ )class PromotionRuleUpdateInput(PromotionRuleBaseInput):@@ -46,6 +52,22 @@ class PromotionRuleUpdateInput(PromotionRuleBaseInput):graphene.ID,description="List of channel ids to remove.",)+ add_gifts = NonNullList(+ graphene.ID,+ description=(+ "List of variant IDs available as a gift to add."+ + ADDED_IN_319+ + PREVIEW_FEATURE+ ),+ )+ remove_gifts = NonNullList(+ graphene.ID,+ description=(+ "List of variant IDs available as a gift to remove."+ + ADDED_IN_319+ + PREVIEW_FEATURE+ ),+ )class PromotionRuleUpdate(ModelMutation):@@ -101,6 +123,13 @@ class PromotionRuleUpdate(ModelMutation):if error:error.code = PromotionRuleUpdateErrorCode.DUPLICATED_INPUT_ITEM.valueraise ValidationError({"addChannels": error, "removeChannels": error})+ error = check_for_duplicates(+ data, "add_gifts", "remove_gifts", error_class_field="gifts"+ )+ if error:+ error.code = PromotionRuleUpdateErrorCode.DUPLICATED_INPUT_ITEM.value+ raise ValidationError({"addGifts": error, "removeGifts": error})+cleaned_input = super().clean_input(info, instance, data, **kwargs)errors: defaultdict[str, list[ValidationError]] = defaultdict(list)cleaned_input = clean_promotion_rule(@@ -122,6 +151,10 @@ class PromotionRuleUpdate(ModelMutation):instance.channels.remove(*remove_channels)if add_channels := cleaned_data.get("add_channels"):instance.channels.add(*add_channels)+ if remove_gifts := cleaned_data.get("remove_gifts"):+ instance.gifts.remove(*remove_gifts)+ if add_gifts := cleaned_data.get("add_gifts"):+ instance.gifts.add(*add_gifts)@classmethoddef post_save_actions(cls, info: ResolveInfo, instance, previous_product_ids):diff --git a/saleor/graphql/discount/mutations/promotion/validators.py b/saleor/graphql/discount/mutations/promotion/validators.pyindex cffe8c686e..78523a4fb6 100644--- a/saleor/graphql/discount/mutations/promotion/validators.py+++ b/saleor/graphql/discount/mutations/promotion/validators.py@@ -2,10 +2,9 @@ from typing import TYPE_CHECKING, Unionfrom django.conf import settingsfrom django.core.exceptions import ValidationError-from django.db.models import Qfrom graphene.utils.str_converters import to_camel_case-from .....discount import PromotionType, RewardValueType+from .....discount import PromotionType, RewardType, RewardValueTypefrom .....discount.models import PromotionRulefrom ....core.validators import validate_price_precision@@ -16,11 +15,14 @@ if TYPE_CHECKING:def clean_promotion_rule(cleaned_input, promotion_type, errors, error_class, index=None, instance=None):- catalogue_predicate = cleaned_input.get("catalogue_predicate")- order_predicate = cleaned_input.get("order_predicate")- if instance:- catalogue_predicate = catalogue_predicate or instance.catalogue_predicate- order_predicate = order_predicate or instance.order_predicate+ catalogue_predicate = get_from_input_or_instance(+ "catalogue_predicate", cleaned_input, instance+ )+ order_predicate = get_from_input_or_instance(+ "order_predicate", cleaned_input, instance+ )+ gift_ids: set[int] = _get_gift_ids(cleaned_input, instance)+ _clean_gifts(gift_ids, errors, error_class, index)invalid_predicates = _clean_predicates(catalogue_predicate,order_predicate,@@ -38,6 +40,7 @@ def clean_promotion_rule(cleaned_input,order_predicate,channel_currencies,+ gift_ids,errors,error_class,index,@@ -57,6 +60,45 @@ def clean_promotion_rule(return cleaned_input+def _get_gift_ids(cleaned_input, instance):+ """Return the set of gift ids for promotion rule valid after performing mutation."""+ if not instance and not any(+ [field in cleaned_input for field in ["gifts", "add_gifts", "remove_gifts"]]+ ):+ return++ if "gifts" in cleaned_input:+ return {gift.id for gift in cleaned_input["gifts"]}+ else:+ # this part is only for PromotionRuleUpdate mutation+ # so the gifts will be fetched once+ current_gift_ids = {gift.id for gift in instance.gifts.all()}+ add_gift_ids = {gift.id for gift in cleaned_input.get("add_gifts", [])}+ remove_gift_ids = {gift.id for gift in cleaned_input.get("remove_gifts", [])}+ return (current_gift_ids | add_gift_ids) - remove_gift_ids+++def _clean_gifts(gift_ids, errors, error_class, index):+ """Check if assigned gifts exceed the gift limit."""+ if not gift_ids:+ return++ gift_limit = int(settings.GIFTS_LIMIT_PER_RULE)+ gifts_count = len(gift_ids)+ if gifts_count > gift_limit:+ errors["gifts"].append(+ ValidationError(+ message="Number of gifts has reached the limit.",+ code=error_class.GIFTS_NUMBER_LIMIT.value,+ params={+ "gifts_limit": settings.GIFTS_LIMIT_PER_RULE,+ "gifts_limit_exceed_by": gifts_count - gift_limit,+ "index": index,+ },+ )+ )++def _clean_predicates(catalogue_predicate,order_predicate,@@ -135,9 +177,7 @@ def _clean_catalogue_predicate(if not catalogue_predicate:return- reward_type = cleaned_input.get("reward_type")- if instance and "reward_type" not in cleaned_input:- reward_type = reward_type or instance.reward_type+ reward_type = get_from_input_or_instance("reward_type", cleaned_input, instance)if reward_type:errors["reward_type"].append(ValidationError(@@ -166,6 +206,7 @@ def _clean_order_predicate(cleaned_input,order_predicate,channel_currencies,+ gift_ids,errors,error_class,index,@@ -180,9 +221,7 @@ def _clean_order_predicate(if not order_predicate:return- reward_type = cleaned_input.get("reward_type")- if "reward_type" not in cleaned_input and instance:- reward_type = reward_type or instance.reward_type+ reward_type = get_from_input_or_instance("reward_type", cleaned_input, instance)if not reward_type:errors["reward_type"].append(ValidationError(@@ -220,10 +259,7 @@ def _clean_order_predicate()return- if "order_predicate" not in cleaned_input:- return-- order_rules_count = PromotionRule.objects.filter(~Q(order_predicate={})).count()+ order_rules_count = PromotionRule.objects.exclude(order_predicate={}).count()rules_limit = settings.ORDER_RULES_LIMITif order_rules_count >= int(rules_limit):errors["order_predicate"].append(@@ -232,7 +268,7 @@ def _clean_order_predicate(code=error_class.RULES_NUMBER_LIMIT.value,params={"rules_limit": rules_limit,- "exceed_by": 1,+ "rules_limit_exceed_by": 1,},))@@ -248,6 +284,65 @@ def _clean_order_predicate(errors["order_predicate"].append(error)return+ if reward_type == RewardType.GIFT:+ _clean_gift_rule(cleaned_input, gift_ids, errors, error_class, index, instance)+++def _clean_gift_rule(cleaned_input, gift_ids, errors, error_class, index, instance):+ reward_value = get_from_input_or_instance("reward_value", cleaned_input, instance)+ if reward_value:+ errors["reward_value"].append(+ ValidationError(+ message=(+ "The rewardValue field must be empty "+ "when rewardType is set to GIFT."+ ),+ code=error_class.INVALID.value,+ params={"index": index} if index is not None else {},+ )+ )++ reward_value_type = get_from_input_or_instance(+ "reward_value_type", cleaned_input, instance+ )+ if reward_value_type:+ errors["reward_value_type"].append(+ ValidationError(+ message=(+ "The rewardValueType field must be empty "+ "when rewardType is set to GIFT."+ ),+ code=error_class.INVALID.value,+ params={"index": index} if index is not None else {},+ )+ )++ if not gift_ids:+ errors["gifts"].append(+ ValidationError(+ message="The gifts field is required when rewardType is set to GIFT.",+ code=error_class.REQUIRED.value,+ params={"index": index} if index is not None else {},+ )+ )+ return++ for field in ["gifts", "add_gifts", "remove_gifts"]:+ for gift in cleaned_input.get(field, []):+ model_name = gift.__class__.__name__+ if model_name != "ProductVariant":+ errors[field].append(+ ValidationError(+ message=(+ f"Gift IDs must resolve to ProductVariant type, "+ f"not to {model_name} type."+ ),+ code=error_class.INVALID_GIFT_TYPE.value,+ params={"index": index} if index is not None else {},+ )+ )+ return+def _clean_reward(cleaned_input,@@ -266,24 +361,18 @@ def _clean_reward(- Validate price precision for fixed reward value.- Check if percentage reward value is not above 100."""+ reward_type = get_from_input_or_instance("reward_type", cleaned_input, instance)if (instanceand "reward_value" not in cleaned_inputand "reward_value_type" not in cleaned_input- ):+ ) or reward_type == RewardType.GIFT:return- reward_value = cleaned_input.get("reward_value")- reward_value_type = cleaned_input.get("reward_value_type")- if instance:- reward_value = (- reward_value if "reward_value" in cleaned_input else instance.reward_value- )- reward_value_type = (- reward_value_type- if "reward_value_type" in cleaned_input- else instance.reward_value_type- )+ reward_value = get_from_input_or_instance("reward_value", cleaned_input, instance)+ reward_value_type = get_from_input_or_instance(+ "reward_value_type", cleaned_input, instance+ )if reward_value_type is None and (catalogue_predicate or order_predicate):errors["reward_value_type"].append(@@ -468,3 +557,10 @@ def clean_percentage_discount_value(code=error_code,params={"index": index} if index is not None else {},)+++def get_from_input_or_instance(field: str, input: dict, instance: PromotionRule):+ if field in input:+ return input[field]+ if instance:+ return getattr(instance, field)diff --git a/saleor/graphql/discount/tests/benchmark/test_promotion_create.py b/saleor/graphql/discount/tests/benchmark/test_promotion_create.pyindex ba17dfd82a..8ecf280276 100644--- a/saleor/graphql/discount/tests/benchmark/test_promotion_create.py+++ b/saleor/graphql/discount/tests/benchmark/test_promotion_create.py@@ -6,8 +6,25 @@ import pytestfrom django.utils import timezonefrom ....tests.utils import get_graphql_content-from ...enums import PromotionTypeEnum, RewardValueTypeEnum-from ..mutations.test_promotion_create import PROMOTION_CREATE_MUTATION+from ...enums import PromotionTypeEnum, RewardTypeEnum, RewardValueTypeEnum++PROMOTION_CREATE_MUTATION = """+ mutation promotionCreate($input: PromotionCreateInput!) {+ promotionCreate(input: $input) {+ promotion {+ id+ rules {+ id+ }+ }+ errors {+ field+ code+ message+ }+ }+ }+"""@pytest.mark.django_db@@ -106,3 +123,83 @@ def test_promotion_create(# thendata = content["data"]["promotionCreate"]assert data["promotion"]++[email protected]_queries(autouse=False)+def test_promotion_create_order_promotion(+ staff_api_client,+ permission_group_manage_discounts,+ channel_USD,+ product_variant_list,+ count_queries,+ django_assert_num_queries,+):+ # given+ permission_group_manage_discounts.user_set.add(staff_api_client.user)+ order_predicate_0 = {+ "discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": "10"}}}+ }+ order_predicate_1 = {+ "discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": "50"}}}+ }+ order_predicate_2 = {+ "discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": "100"}}}+ }+ channel_ids = [graphene.Node.to_global_id("Channel", channel_USD.pk)]+ gift_ids_1 = [+ graphene.Node.to_global_id("ProductVariant", variant.pk)+ for variant in product_variant_list[:2]+ ]+ gift_ids_2 = [+ graphene.Node.to_global_id("ProductVariant", variant.pk)+ for variant in product_variant_list[2:]+ ]++ variables = {+ "input": {+ "name": "test gift promotion",+ "type": PromotionTypeEnum.ORDER.name,+ "rules": [+ {+ "name": "test order promotion rule 1",+ "channels": channel_ids,+ "rewardType": RewardTypeEnum.SUBTOTAL_DISCOUNT.name,+ "rewardValueType": RewardValueTypeEnum.FIXED.name,+ "rewardValue": Decimal("1"),+ "orderPredicate": order_predicate_0,+ },+ {+ "name": "test order promotion rule 2",+ "channels": channel_ids,+ "rewardType": RewardTypeEnum.SUBTOTAL_DISCOUNT.name,+ "rewardValueType": RewardValueTypeEnum.PERCENTAGE.name,+ "rewardValue": Decimal("10"),+ "orderPredicate": order_predicate_0,+ },+ {+ "name": "test gift promotion rule 1",+ "channels": channel_ids,+ "rewardType": RewardTypeEnum.GIFT.name,+ "orderPredicate": order_predicate_1,+ "gifts": gift_ids_1,+ },+ {+ "name": "test gift promotion rule 2",+ "channels": channel_ids,+ "rewardType": RewardTypeEnum.GIFT.name,+ "orderPredicate": order_predicate_2,+ "gifts": gift_ids_2,+ },+ ],+ }+ }++ # when+ with django_assert_num_queries(40):+ response = staff_api_client.post_graphql(PROMOTION_CREATE_MUTATION, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["promotionCreate"]+ assert not data["errors"]diff --git a/saleor/graphql/discount/tests/benchmark/test_promotion_delete.py b/saleor/graphql/discount/tests/benchmark/test_promotion_delete.pyindex 65cd5cb977..bc10dc0604 100644--- a/saleor/graphql/discount/tests/benchmark/test_promotion_delete.py+++ b/saleor/graphql/discount/tests/benchmark/test_promotion_delete.py@@ -31,3 +31,30 @@ def test_promotion_delete(# thendata = content["data"]["promotionDelete"]assert data["promotion"]++[email protected]_queries(autouse=False)+def test_gift_promotion_delete(+ staff_api_client,+ permission_group_manage_discounts,+ gift_promotion_rule,+ count_queries,+ django_assert_num_queries,+):+ # given+ staff_api_client.user.groups.add(permission_group_manage_discounts)++ variables = {+ "id": graphene.Node.to_global_id("Promotion", gift_promotion_rule.promotion_id),+ }++ # when+ with django_assert_num_queries(23):+ content = get_graphql_content(+ staff_api_client.post_graphql(PROMOTION_DELETE_MUTATION, variables)+ )++ # then+ data = content["data"]["promotionDelete"]+ assert data["promotion"]diff --git a/saleor/graphql/discount/tests/benchmark/test_promotion_rule_create.py b/saleor/graphql/discount/tests/benchmark/test_promotion_rule_create.pyindex 619dccbef8..a4e1217291 100644--- a/saleor/graphql/discount/tests/benchmark/test_promotion_rule_create.py+++ b/saleor/graphql/discount/tests/benchmark/test_promotion_rule_create.py@@ -4,8 +4,22 @@ import grapheneimport pytestfrom ....tests.utils import get_graphql_content-from ...enums import RewardValueTypeEnum-from ..mutations.test_promotion_rule_create import PROMOTION_RULE_CREATE_MUTATION+from ...enums import RewardTypeEnum, RewardValueTypeEnum++PROMOTION_RULE_CREATE_MUTATION = """+ mutation promotionRuleCreate($input: PromotionRuleCreateInput!) {+ promotionRuleCreate(input: $input) {+ promotionRule {+ id+ }+ errors {+ field+ code+ message+ }+ }+ }+"""@pytest.mark.django_db@@ -81,3 +95,50 @@ def test_promotion_rule_create(# thendata = content["data"]["promotionRuleCreate"]assert data["promotionRule"]++[email protected]_queries(autouse=False)+def test_promotion_rule_create_gift(+ staff_api_client,+ permission_group_manage_discounts,+ channel_USD,+ count_queries,+ product_variant_list,+ gift_promotion_rule,+ django_assert_num_queries,+):+ # given+ permission_group_manage_discounts.user_set.add(staff_api_client.user)+ order_predicate = {+ "discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": "100"}}}+ }+ channel_ids = [graphene.Node.to_global_id("Channel", channel_USD.pk)]+ gift_ids = [+ graphene.Node.to_global_id("ProductVariant", variant.pk)+ for variant in product_variant_list+ ]++ variables = {+ "input": {+ "promotion": graphene.Node.to_global_id(+ "Promotion", gift_promotion_rule.promotion_id+ ),+ "name": "test gift promotion rule",+ "channels": channel_ids,+ "rewardType": RewardTypeEnum.GIFT.name,+ "orderPredicate": order_predicate,+ "gifts": gift_ids,+ }+ }++ # when+ with django_assert_num_queries(17):+ content = get_graphql_content(+ staff_api_client.post_graphql(PROMOTION_RULE_CREATE_MUTATION, variables)+ )++ # then+ data = content["data"]["promotionRuleCreate"]+ assert data["promotionRule"]+ assert not data["errors"]diff --git a/saleor/graphql/discount/tests/mutations/test_promotion_create.py b/saleor/graphql/discount/tests/mutations/test_promotion_create.pyindex 0ec075a6cb..7a58239657 100644--- a/saleor/graphql/discount/tests/mutations/test_promotion_create.py+++ b/saleor/graphql/discount/tests/mutations/test_promotion_create.py@@ -36,9 +36,11 @@ PROMOTION_CREATE_MUTATION = """}rewardValueTyperewardValue+ rewardTypepredicateTypecataloguePredicateorderPredicate+ giftIds}}errors {@@ -47,7 +49,9 @@ PROMOTION_CREATE_MUTATION = """indexmessagerulesLimit- exceedBy+ rulesLimitExceedBy+ giftsLimit+ giftsLimitExceedBy}}}@@ -164,6 +168,8 @@ def test_promotion_create_by_staff_user(rule_data["channels"] = [{"id": channel_id} for channel_id in rule_data["channels"]]+ rule_data["giftIds"] = []+ rule_data["rewardType"] = Noneassert rule_data in promotion_data["rules"]promotion = Promotion.objects.filter(name=promotion_name).get()@@ -744,6 +750,8 @@ def test_promotion_create_start_date_and_end_date_after_current_date(rule_data["channels"] = [{"id": channel_id} for channel_id in rule_data["channels"]]+ rule_data["giftIds"] = []+ rule_data["rewardType"] = Noneassert rule_data in promotion_data["rules"]promotion = Promotion.objects.filter(name=promotion_name).get()@@ -826,7 +834,9 @@ def test_promotion_create_missing_predicate("index": 1,"message": ANY,"rulesLimit": None,- "exceedBy": None,+ "rulesLimitExceedBy": None,+ "giftsLimit": None,+ "giftsLimitExceedBy": None,} in errors@@ -1111,7 +1121,9 @@ def test_promotion_create_mixed_catalogue_and_order_rules("field": "cataloguePredicate","index": 1,"rulesLimit": None,- "exceedBy": None,+ "rulesLimitExceedBy": None,+ "giftsLimit": None,+ "giftsLimitExceedBy": None,"message": ANY,} in errorsassert {@@ -1119,7 +1131,9 @@ def test_promotion_create_mixed_catalogue_and_order_rules("field": "orderPredicate","index": 1,"rulesLimit": None,- "exceedBy": None,+ "rulesLimitExceedBy": None,+ "giftsLimit": None,+ "giftsLimitExceedBy": None,"message": ANY,} in errors@@ -1243,7 +1257,9 @@ def test_promotion_create_multiple_errors("index": 0,"message": ANY,"rulesLimit": None,- "exceedBy": None,+ "rulesLimitExceedBy": None,+ "giftsLimit": None,+ "giftsLimitExceedBy": None,},{"code": PromotionCreateErrorCode.REQUIRED.name,@@ -1251,7 +1267,9 @@ def test_promotion_create_multiple_errors("index": 0,"message": ANY,"rulesLimit": None,- "exceedBy": None,+ "rulesLimitExceedBy": None,+ "giftsLimit": None,+ "giftsLimitExceedBy": None,},{"code": PromotionCreateErrorCode.GRAPHQL_ERROR.name,@@ -1259,7 +1277,9 @@ def test_promotion_create_multiple_errors("index": 0,"message": ANY,"rulesLimit": None,- "exceedBy": None,+ "rulesLimitExceedBy": None,+ "giftsLimit": None,+ "giftsLimitExceedBy": None,},]for error in expected_errors:@@ -1483,7 +1503,69 @@ def test_promotion_create_exceeds_rules_number_limit(assert errors[0]["code"] == PromotionCreateErrorCode.RULES_NUMBER_LIMIT.nameassert errors[0]["field"] == "rules"assert errors[0]["rulesLimit"] == 1- assert errors[0]["exceedBy"] == 1+ assert errors[0]["rulesLimitExceedBy"] == 1+ assert errors[0]["giftsLimit"] is None+ assert errors[0]["giftsLimitExceedBy"] is None+++@override_settings(GIFTS_LIMIT_PER_RULE=1)+def test_promotion_create_exceeds_gifts_number_limit(+ staff_api_client,+ permission_group_manage_discounts,+ channel_USD,+ product_variant_list,+):+ # given+ gift_limit = 1+ permission_group_manage_discounts.user_set.add(staff_api_client.user)+ start_date = timezone.now() - timedelta(days=30)+ end_date = timezone.now() + timedelta(days=30)++ promotion_name = "test promotion"+ order_predicate = {+ "discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": 100}}}+ }+ rule_name = "test promotion rule 1"+ reward_type = RewardTypeEnum.GIFT.name+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.pk)+ gift_ids = [+ graphene.Node.to_global_id("ProductVariant", variant.pk)+ for variant in product_variant_list+ ]++ variables = {+ "input": {+ "name": promotion_name,+ "startDate": start_date.isoformat(),+ "endDate": end_date.isoformat(),+ "type": PromotionTypeEnum.ORDER.name,+ "rules": [+ {+ "name": rule_name,+ "channels": [channel_id],+ "rewardType": reward_type,+ "orderPredicate": order_predicate,+ "gifts": gift_ids,+ }+ ],+ }+ }++ # when+ response = staff_api_client.post_graphql(PROMOTION_CREATE_MUTATION, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["promotionCreate"]+ errors = data["errors"]++ assert not data["promotion"]+ assert len(errors) == 1+ assert errors[0]["code"] == PromotionCreateErrorCode.GIFTS_NUMBER_LIMIT.name+ assert errors[0]["field"] == "gifts"+ assert errors[0]["index"] == 0+ assert errors[0]["giftsLimit"] == gift_limit+ assert errors[0]["giftsLimitExceedBy"] == len(gift_ids) - gift_limit@patch("saleor.product.tasks.update_products_discounted_prices_of_promotion_task.delay")@@ -1716,6 +1798,273 @@ def test_promotion_create_events_by_app(assert all([rule["id"] in rule_ids for rule in rules])+@patch("saleor.product.tasks.update_products_discounted_prices_of_promotion_task.delay")+def test_promotion_create_gift_promotion(+ _,+ staff_api_client,+ permission_group_manage_discounts,+ channel_USD,+ channel_PLN,+ product_variant_list,+):+ # given+ permission_group_manage_discounts.user_set.add(staff_api_client.user)+ promotion_name = "test gift promotion"+ order_predicate = {+ "discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": "100"}}}+ }+ rule_name = "test gift promotion rule"+ reward_type = RewardTypeEnum.GIFT.name+ channel_ids = [graphene.Node.to_global_id("Channel", channel_USD.pk)]+ gift_ids = [+ graphene.Node.to_global_id("ProductVariant", variant.pk)+ for variant in product_variant_list+ ]++ variables = {+ "input": {+ "name": promotion_name,+ "type": PromotionTypeEnum.ORDER.name,+ "rules": [+ {+ "name": rule_name,+ "channels": channel_ids,+ "rewardType": reward_type,+ "orderPredicate": order_predicate,+ "gifts": gift_ids,+ }+ ],+ }+ }++ # when+ response = staff_api_client.post_graphql(PROMOTION_CREATE_MUTATION, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["promotionCreate"]+ assert not data["errors"]++ assert data["promotion"]["type"] == PromotionTypeEnum.ORDER.name+ rules_data = data["promotion"]["rules"]+ assert len(rules_data) == 1+ assert rules_data[0]["orderPredicate"] == order_predicate+ assert rules_data[0]["predicateType"] == PromotionTypeEnum.ORDER.name+ assert rules_data[0]["rewardType"] == RewardTypeEnum.GIFT.name+ assert sorted(rules_data[0]["giftIds"]) == sorted(gift_ids)++ promotion = Promotion.objects.filter(name=promotion_name).get()+ rules = promotion.rules.all()+ assert len(rules) == 1+ assert all([gift in product_variant_list for gift in rules[0].gifts.all()])+ assert rules[0].reward_type == RewardTypeEnum.GIFT.value+++def test_promotion_create_gift_promotion_wrong_gift_instance(+ staff_api_client,+ permission_group_manage_discounts,+ channel_USD,+ channel_PLN,+ product_list,+):+ # given+ permission_group_manage_discounts.user_set.add(staff_api_client.user)+ promotion_name = "test gift promotion"+ order_predicate = {+ "discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": "100"}}}+ }+ rule_name = "test gift promotion rule"+ reward_type = RewardTypeEnum.GIFT.name+ channel_ids = [graphene.Node.to_global_id("Channel", channel_USD.pk)]+ gift_ids = [+ graphene.Node.to_global_id("Product", product.pk) for product in product_list+ ]++ variables = {+ "input": {+ "name": promotion_name,+ "type": PromotionTypeEnum.ORDER.name,+ "rules": [+ {+ "name": rule_name,+ "channels": channel_ids,+ "rewardType": reward_type,+ "orderPredicate": order_predicate,+ "gifts": gift_ids,+ }+ ],+ }+ }++ # when+ response = staff_api_client.post_graphql(PROMOTION_CREATE_MUTATION, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["promotionCreate"]+ errors = data["errors"]++ assert not data["promotion"]+ assert len(errors) == 1+ assert errors[0]["code"] == PromotionCreateErrorCode.INVALID_GIFT_TYPE.name+ assert errors[0]["field"] == "gifts"+ assert errors[0]["index"] == 0+++def test_promotion_create_gift_promotion_with_reward_value(+ staff_api_client,+ permission_group_manage_discounts,+ channel_USD,+ channel_PLN,+ product_variant_list,+):+ # given+ permission_group_manage_discounts.user_set.add(staff_api_client.user)+ promotion_name = "test gift promotion"+ order_predicate = {+ "discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": "100"}}}+ }+ rule_name = "test gift promotion rule"+ reward_type = RewardTypeEnum.GIFT.name+ reward_value = Decimal("10")+ channel_ids = [graphene.Node.to_global_id("Channel", channel_USD.pk)]+ gift_ids = [+ graphene.Node.to_global_id("ProductVariant", variant.pk)+ for variant in product_variant_list+ ]++ variables = {+ "input": {+ "name": promotion_name,+ "type": PromotionTypeEnum.ORDER.name,+ "rules": [+ {+ "name": rule_name,+ "channels": channel_ids,+ "rewardType": reward_type,+ "rewardValue": reward_value,+ "orderPredicate": order_predicate,+ "gifts": gift_ids,+ }+ ],+ }+ }++ # when+ response = staff_api_client.post_graphql(PROMOTION_CREATE_MUTATION, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["promotionCreate"]+ errors = data["errors"]++ assert not data["promotion"]+ assert len(errors) == 1+ assert errors[0]["code"] == PromotionCreateErrorCode.INVALID.name+ assert errors[0]["field"] == "rewardValue"+ assert errors[0]["index"] == 0+++def test_promotion_create_gift_promotion_with_reward_value_type(+ staff_api_client,+ permission_group_manage_discounts,+ channel_USD,+ channel_PLN,+ product_variant_list,+):+ # given+ permission_group_manage_discounts.user_set.add(staff_api_client.user)+ promotion_name = "test gift promotion"+ order_predicate = {+ "discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": "100"}}}+ }+ rule_name = "test gift promotion rule"+ reward_type = RewardTypeEnum.GIFT.name+ reward_value_type = RewardValueTypeEnum.PERCENTAGE.name+ channel_ids = [graphene.Node.to_global_id("Channel", channel_USD.pk)]+ gift_ids = [+ graphene.Node.to_global_id("ProductVariant", variant.pk)+ for variant in product_variant_list+ ]++ variables = {+ "input": {+ "name": promotion_name,+ "type": PromotionTypeEnum.ORDER.name,+ "rules": [+ {+ "name": rule_name,+ "channels": channel_ids,+ "rewardType": reward_type,+ "rewardValueType": reward_value_type,+ "orderPredicate": order_predicate,+ "gifts": gift_ids,+ }+ ],+ }+ }++ # when+ response = staff_api_client.post_graphql(PROMOTION_CREATE_MUTATION, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["promotionCreate"]+ errors = data["errors"]++ assert not data["promotion"]+ assert len(errors) == 1+ assert errors[0]["code"] == PromotionCreateErrorCode.INVALID.name+ assert errors[0]["field"] == "rewardValueType"+ assert errors[0]["index"] == 0+++def test_promotion_create_gift_promotion_missing_gifts(+ staff_api_client,+ permission_group_manage_discounts,+ channel_USD,+ channel_PLN,+):+ # given+ permission_group_manage_discounts.user_set.add(staff_api_client.user)+ promotion_name = "test gift promotion"+ order_predicate = {+ "discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": "100"}}}+ }+ rule_name = "test gift promotion rule"+ reward_type = RewardTypeEnum.GIFT.name+ channel_ids = [graphene.Node.to_global_id("Channel", channel_USD.pk)]++ variables = {+ "input": {+ "name": promotion_name,+ "type": PromotionTypeEnum.ORDER.name,+ "rules": [+ {+ "name": rule_name,+ "channels": channel_ids,+ "rewardType": reward_type,+ "orderPredicate": order_predicate,+ }+ ],+ }+ }++ # when+ response = staff_api_client.post_graphql(PROMOTION_CREATE_MUTATION, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["promotionCreate"]+ errors = data["errors"]++ assert not data["promotion"]+ assert len(errors) == 1+ assert errors[0]["code"] == PromotionCreateErrorCode.REQUIRED.name+ assert errors[0]["field"] == "gifts"+ assert errors[0]["index"] == 0++def test_promotion_create_without_catalogue_predicate(staff_api_client,permission_manage_discounts,@@ -1767,4 +2116,6 @@ def test_promotion_create_without_catalogue_predicate(assert error["code"] == PromotionCreateErrorCode.REQUIRED.nameassert error["field"] == "cataloguePredicate"assert error["rulesLimit"] is None- assert error["exceedBy"] is None+ assert error["rulesLimitExceedBy"] is None+ assert error["giftsLimit"] is None+ assert error["giftsLimitExceedBy"] is Nonediff --git a/saleor/graphql/discount/tests/mutations/test_promotion_rule_create.py b/saleor/graphql/discount/tests/mutations/test_promotion_rule_create.pyindex 4b8b8a9d04..9115ff76df 100644--- a/saleor/graphql/discount/tests/mutations/test_promotion_rule_create.py+++ b/saleor/graphql/discount/tests/mutations/test_promotion_rule_create.py@@ -33,16 +33,20 @@ PROMOTION_RULE_CREATE_MUTATION = """}rewardValueTyperewardValue+ rewardTypepredicateTypecataloguePredicateorderPredicate+ giftIds}errors {fieldcodemessagerulesLimit- exceedBy+ rulesLimitExceedBy+ giftsLimit+ giftsLimitExceedBy}}}@@ -310,7 +314,9 @@ def test_promotion_rule_create_missing_predicate("field": "orderPredicate","message": ANY,"rulesLimit": None,- "exceedBy": None,+ "rulesLimitExceedBy": None,+ "giftsLimit": None,+ "giftsLimitExceedBy": None,} in errorsassert promotion.rules.count() == rules_count@@ -466,14 +472,18 @@ def test_promotion_rule_create_multiple_errors("field": "rewardValue","message": ANY,"rulesLimit": None,- "exceedBy": None,+ "rulesLimitExceedBy": None,+ "giftsLimit": None,+ "giftsLimitExceedBy": None,},{"code": PromotionRuleCreateErrorCode.REQUIRED.name,"field": "rewardValueType","message": ANY,"rulesLimit": None,- "exceedBy": None,+ "rulesLimitExceedBy": None,+ "giftsLimit": None,+ "giftsLimitExceedBy": None,},]for error in expected_errors:@@ -1079,7 +1089,9 @@ def test_promotion_rule_create_multiple_predicates("field": "orderPredicate","message": ANY,"rulesLimit": None,- "exceedBy": None,+ "rulesLimitExceedBy": None,+ "giftsLimit": None,+ "giftsLimitExceedBy": None,} in errorsassert promotion.rules.count() == rules_count@@ -1345,6 +1357,7 @@ def test_promotion_rule_create_order_predicate(assert rule_data["predicateType"] == promotion.type.upper()assert rule_data["rewardValueType"] == reward_value_typeassert rule_data["rewardValue"] == reward_value+ assert rule_data["rewardType"] == reward_type.upper()assert rule_data["promotion"]["id"] == promotion_idassert promotion.rules.count() == rules_count + 1rule = promotion.rules.last()@@ -1408,6 +1421,56 @@ def test_promotion_rule_create_mixed_currencies_for_price_based_predicate(assert promotion.rules.count() == rules_count+def test_promotion_rule_create_with_metadata(+ staff_api_client,+ permission_group_manage_discounts,+ description_json,+ channel_USD,+ channel_PLN,+ variant,+ product,+ collection,+ category,+ catalogue_promotion,+):+ # given+ permission_group_manage_discounts.user_set.add(staff_api_client.user)++ channel_ids = [+ graphene.Node.to_global_id("Channel", channel.pk)+ for channel in [channel_USD, channel_PLN]+ ]+ catalogue_predicate = {+ "OR": [{"variantPredicate": {"metadata": [{"key": "test", "value": "test"}]}}]+ }+ name = "test promotion rule"+ reward_value = Decimal("10")+ reward_value_type = RewardValueTypeEnum.PERCENTAGE.name+ promotion_id = graphene.Node.to_global_id("Promotion", catalogue_promotion.id)++ variables = {+ "input": {+ "name": name,+ "promotion": promotion_id,+ "description": description_json,+ "channels": channel_ids,+ "rewardValueType": reward_value_type,+ "rewardValue": reward_value,+ "cataloguePredicate": catalogue_predicate,+ }+ }++ # when+ response = staff_api_client.post_graphql(PROMOTION_RULE_CREATE_MUTATION, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["promotionRuleCreate"]++ assert not data["errors"]+ assert data["promotionRule"]++@override_settings(ORDER_RULES_LIMIT=1)def test_promotion_rule_create_exceeds_rules_number_limit(staff_api_client,@@ -1464,46 +1527,256 @@ def test_promotion_rule_create_exceeds_rules_number_limit(assert errors[0]["code"] == PromotionRuleCreateErrorCode.RULES_NUMBER_LIMIT.nameassert errors[0]["field"] == "orderPredicate"assert errors[0]["rulesLimit"] == 1- assert errors[0]["exceedBy"] == 1+ assert errors[0]["rulesLimitExceedBy"] == 1assert promotion.rules.count() == rules_count-def test_promotion_rule_create_with_metadata(+@override_settings(GIFTS_LIMIT_PER_RULE=1)+def test_promotion_rule_create_exceeds_gifts_number_limit(staff_api_client,permission_group_manage_discounts,- description_json,channel_USD,- channel_PLN,- variant,- product,- collection,- category,- catalogue_promotion,+ order_promotion_without_rules,+ product_variant_list,):# given+ gift_limit = 1+ promotion = order_promotion_without_rulespermission_group_manage_discounts.user_set.add(staff_api_client.user)- channel_ids = [- graphene.Node.to_global_id("Channel", channel.pk)- for channel in [channel_USD, channel_PLN]+ reward_type = RewardTypeEnum.GIFT.name+ promotion_id = graphene.Node.to_global_id("Promotion", promotion.id)+ order_predicate = {+ "discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": "100"}}}+ }+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.pk)+ gift_ids = [+ graphene.Node.to_global_id("ProductVariant", variant.pk)+ for variant in product_variant_list]- catalogue_predicate = {- "OR": [{"variantPredicate": {"metadata": [{"key": "test", "value": "test"}]}}]++ rules_count = promotion.rules.count()++ variables = {+ "input": {+ "promotion": promotion_id,+ "channels": [channel_id],+ "rewardType": reward_type,+ "orderPredicate": order_predicate,+ "gifts": gift_ids,+ }+ }++ # when+ response = staff_api_client.post_graphql(PROMOTION_RULE_CREATE_MUTATION, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["promotionRuleCreate"]+ errors = data["errors"]++ assert not data["promotionRule"]+ assert len(errors) == 1+ assert errors[0]["code"] == PromotionRuleCreateErrorCode.GIFTS_NUMBER_LIMIT.name+ assert errors[0]["field"] == "gifts"+ assert errors[0]["giftsLimit"] == gift_limit+ assert errors[0]["giftsLimitExceedBy"] == len(gift_ids) - gift_limit+ assert errors[0]["rulesLimit"] is None+ assert errors[0]["rulesLimitExceedBy"] is None+ assert promotion.rules.count() == rules_count+++@patch("saleor.plugins.manager.PluginsManager.promotion_rule_created")+def test_promotion_rule_create_gift_promotion(+ promotion_rule_created_mock,+ staff_api_client,+ permission_group_manage_discounts,+ channel_USD,+ order_promotion_without_rules,+ product_variant_list,+):+ # given+ promotion = order_promotion_without_rules+ permission_group_manage_discounts.user_set.add(staff_api_client.user)+ rules_count = promotion.rules.count()+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.pk)+ name = "test promotion rule"+ reward_type = RewardTypeEnum.GIFT.name+ promotion_id = graphene.Node.to_global_id("Promotion", promotion.id)+ order_predicate = {+ "discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": "100"}}}+ }+ gift_ids = [+ graphene.Node.to_global_id("ProductVariant", variant.pk)+ for variant in product_variant_list+ ]++ variables = {+ "input": {+ "name": name,+ "promotion": promotion_id,+ "channels": [channel_id],+ "rewardType": reward_type,+ "orderPredicate": order_predicate,+ "gifts": gift_ids,+ }+ }++ # when+ response = staff_api_client.post_graphql(PROMOTION_RULE_CREATE_MUTATION, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["promotionRuleCreate"]+ rule_data = data["promotionRule"]++ assert not data["errors"]+ assert rule_data["name"] == name+ assert rule_data["channels"][0]["id"] == channel_id+ assert rule_data["orderPredicate"] == order_predicate+ assert rule_data["predicateType"] == promotion.type.upper()+ assert rule_data["promotion"]["id"] == promotion_id+ assert rule_data["rewardType"] == reward_type+ assert sorted(rule_data["giftIds"]) == sorted(gift_ids)+ assert promotion.rules.count() == rules_count + 1+ rule = promotion.rules.last()+ assert all([gift in product_variant_list for gift in rule.gifts.all()])+ assert rule.reward_type == RewardTypeEnum.GIFT.value+ promotion_rule_created_mock.assert_called_once_with(rule)+++def test_promotion_rule_create_gift_promotion_wrong_gift_instance(+ staff_api_client,+ permission_group_manage_discounts,+ channel_USD,+ order_promotion_without_rules,+ product_list,+):+ # given+ promotion = order_promotion_without_rules+ permission_group_manage_discounts.user_set.add(staff_api_client.user)+ rules_count = promotion.rules.count()+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.pk)+ name = "test promotion rule"+ reward_type = RewardTypeEnum.GIFT.name+ promotion_id = graphene.Node.to_global_id("Promotion", promotion.id)+ order_predicate = {+ "discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": "100"}}}}+ gift_ids = [+ graphene.Node.to_global_id("Product", product.pk) for product in product_list+ ]++ variables = {+ "input": {+ "name": name,+ "promotion": promotion_id,+ "channels": [channel_id],+ "rewardType": reward_type,+ "orderPredicate": order_predicate,+ "gifts": gift_ids,+ }+ }++ # when+ response = staff_api_client.post_graphql(PROMOTION_RULE_CREATE_MUTATION, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["promotionRuleCreate"]+ errors = data["errors"]++ assert not data["promotionRule"]+ assert len(errors) == 1+ assert errors[0]["code"] == PromotionRuleCreateErrorCode.INVALID_GIFT_TYPE.name+ assert errors[0]["field"] == "gifts"+ assert promotion.rules.count() == rules_count+++def test_promotion_rule_create_gift_promotion_with_reward_value(+ staff_api_client,+ permission_group_manage_discounts,+ channel_USD,+ order_promotion_without_rules,+ product_variant_list,+):+ # given+ promotion = order_promotion_without_rules+ permission_group_manage_discounts.user_set.add(staff_api_client.user)+ rules_count = promotion.rules.count()+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.pk)name = "test promotion rule"+ reward_type = RewardTypeEnum.GIFT.namereward_value = Decimal("10")+ promotion_id = graphene.Node.to_global_id("Promotion", promotion.id)+ order_predicate = {+ "discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": "100"}}}+ }+ gift_ids = [+ graphene.Node.to_global_id("ProductVariant", variant.pk)+ for variant in product_variant_list+ ]++ variables = {+ "input": {+ "name": name,+ "promotion": promotion_id,+ "channels": [channel_id],+ "rewardType": reward_type,+ "rewardValue": reward_value,+ "orderPredicate": order_predicate,+ "gifts": gift_ids,+ }+ }++ # when+ response = staff_api_client.post_graphql(PROMOTION_RULE_CREATE_MUTATION, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["promotionRuleCreate"]+ errors = data["errors"]++ assert not data["promotionRule"]+ assert len(errors) == 1+ assert errors[0]["code"] == PromotionRuleCreateErrorCode.INVALID.name+ assert errors[0]["field"] == "rewardValue"+ assert promotion.rules.count() == rules_count+++def test_promotion_rule_create_gift_promotion_with_reward_value_type(+ staff_api_client,+ permission_group_manage_discounts,+ channel_USD,+ order_promotion_without_rules,+ product_variant_list,+):+ # given+ promotion = order_promotion_without_rules+ permission_group_manage_discounts.user_set.add(staff_api_client.user)+ rules_count = promotion.rules.count()+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.pk)+ name = "test promotion rule"+ reward_type = RewardTypeEnum.GIFT.namereward_value_type = RewardValueTypeEnum.PERCENTAGE.name- promotion_id = graphene.Node.to_global_id("Promotion", catalogue_promotion.id)+ promotion_id = graphene.Node.to_global_id("Promotion", promotion.id)+ order_predicate = {+ "discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": "100"}}}+ }+ gift_ids = [+ graphene.Node.to_global_id("ProductVariant", variant.pk)+ for variant in product_variant_list+ ]variables = {"input": {"name": name,"promotion": promotion_id,- "description": description_json,- "channels": channel_ids,+ "channels": [channel_id],+ "rewardType": reward_type,"rewardValueType": reward_value_type,- "rewardValue": reward_value,- "cataloguePredicate": catalogue_predicate,+ "orderPredicate": order_predicate,+ "gifts": gift_ids,}}@@ -1513,6 +1786,54 @@ def test_promotion_rule_create_with_metadata(# thencontent = get_graphql_content(response)data = content["data"]["promotionRuleCreate"]+ errors = data["errors"]- assert not data["errors"]- assert data["promotionRule"]+ assert not data["promotionRule"]+ assert len(errors) == 1+ assert errors[0]["code"] == PromotionRuleCreateErrorCode.INVALID.name+ assert errors[0]["field"] == "rewardValueType"+ assert promotion.rules.count() == rules_count+++def test_promotion_rule_create_gift_promotion_missing_gifts(+ staff_api_client,+ permission_group_manage_discounts,+ channel_USD,+ order_promotion_without_rules,+ product_variant_list,+):+ # given+ promotion = order_promotion_without_rules+ permission_group_manage_discounts.user_set.add(staff_api_client.user)+ rules_count = promotion.rules.count()+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.pk)+ name = "test promotion rule"+ reward_type = RewardTypeEnum.GIFT.name+ promotion_id = graphene.Node.to_global_id("Promotion", promotion.id)+ order_predicate = {+ "discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": "100"}}}+ }++ variables = {+ "input": {+ "name": name,+ "promotion": promotion_id,+ "channels": [channel_id],+ "rewardType": reward_type,+ "orderPredicate": order_predicate,+ }+ }++ # when+ response = staff_api_client.post_graphql(PROMOTION_RULE_CREATE_MUTATION, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["promotionRuleCreate"]+ errors = data["errors"]++ assert not data["promotionRule"]+ assert len(errors) == 1+ assert errors[0]["code"] == PromotionRuleCreateErrorCode.REQUIRED.name+ assert errors[0]["field"] == "gifts"+ assert promotion.rules.count() == rules_countdiff --git a/saleor/graphql/discount/tests/mutations/test_promotion_rule_update.py b/saleor/graphql/discount/tests/mutations/test_promotion_rule_update.pyindex dbbf0d4a70..e962b0a7da 100644--- a/saleor/graphql/discount/tests/mutations/test_promotion_rule_update.py+++ b/saleor/graphql/discount/tests/mutations/test_promotion_rule_update.py@@ -2,6 +2,7 @@ from decimal import Decimalfrom unittest.mock import ANY, patchimport graphene+from django.test import override_settingsfrom .....discount import PromotionEvents, RewardValueTypefrom .....discount.error_codes import PromotionRuleUpdateErrorCode@@ -33,12 +34,16 @@ PROMOTION_RULE_UPDATE_MUTATION = """rewardValuerewardTypecataloguePredicate+ orderPredicate+ giftIds}errors {fieldcodemessagechannels+ giftsLimit+ giftsLimitExceedBy}}}@@ -294,12 +299,16 @@ def test_promotion_rule_update_duplicates_channels_in_add_and_remove_field("field": "addChannels","message": ANY,"channels": [graphene.Node.to_global_id("Channel", channel_PLN.pk)],+ "giftsLimit": None,+ "giftsLimitExceedBy": None,},{"code": PromotionRuleUpdateErrorCode.DUPLICATED_INPUT_ITEM.name,"field": "removeChannels","message": ANY,"channels": [graphene.Node.to_global_id("Channel", channel_PLN.pk)],+ "giftsLimit": None,+ "giftsLimitExceedBy": None,},]for error in expected_errors:@@ -924,6 +933,8 @@ def test_promotion_rule_update_mix_predicates_both_predicate_types_given("field": "orderPredicate","message": ANY,"channels": None,+ "giftsLimit": None,+ "giftsLimitExceedBy": None,} in errors@@ -1028,3 +1039,235 @@ def test_promotion_rule_update_add_invalid_channels_for_order_rule(== PromotionRuleUpdateErrorCode.MULTIPLE_CURRENCIES_NOT_ALLOWED.name)assert errors[0]["field"] == "addChannels"+++def test_promotion_rule_update_gift_promotion(+ app_api_client,+ permission_manage_discounts,+ gift_promotion_rule,+ product_variant_list,+):+ # given+ rule = gift_promotion_rule+ rule_id = graphene.Node.to_global_id("PromotionRule", rule.id)+ order_predicate = {+ "discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": "100"}}}+ }+ gift_ids = [+ graphene.Node.to_global_id("ProductVariant", variant.pk)+ for variant in product_variant_list+ ]+ current_gift_ids = [+ graphene.Node.to_global_id("ProductVariant", variant.pk)+ for variant in rule.gifts.all()+ ]+ variables = {+ "id": rule_id,+ "input": {+ "orderPredicate": order_predicate,+ "addGifts": gift_ids,+ },+ }++ # when+ response = app_api_client.post_graphql(+ PROMOTION_RULE_UPDATE_MUTATION,+ variables,+ permissions=(permission_manage_discounts,),+ )++ # then+ gift_ids = set(gift_ids) | set(current_gift_ids)+ content = get_graphql_content(response)+ data = content["data"]["promotionRuleUpdate"]+ assert not data["errors"]+ rule_data = data["promotionRule"]+ assert sorted(rule_data["giftIds"]) == sorted(gift_ids)+ assert rule_data["orderPredicate"] == order_predicate+ rule.refresh_from_db()+ assert rule.reward_type == RewardTypeEnum.GIFT.value+ assert rule.order_predicate == order_predicate+++def test_promotion_rule_update_gift_promotion_wrong_gift_instance(+ app_api_client,+ permission_manage_discounts,+ gift_promotion_rule,+ product_list,+):+ # given+ rule = gift_promotion_rule+ rule_id = graphene.Node.to_global_id("PromotionRule", rule.id)+ gift_ids = [+ graphene.Node.to_global_id("Product", product.pk) for product in product_list+ ]+ variables = {+ "id": rule_id,+ "input": {+ "addGifts": gift_ids,+ },+ }++ # when+ response = app_api_client.post_graphql(+ PROMOTION_RULE_UPDATE_MUTATION,+ variables,+ permissions=(permission_manage_discounts,),+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["promotionRuleUpdate"]+ errors = data["errors"]++ assert not data["promotionRule"]+ assert len(errors) == 1+ assert errors[0]["code"] == PromotionRuleUpdateErrorCode.INVALID_GIFT_TYPE.name+ assert errors[0]["field"] == "addGifts"+++def test_promotion_rule_update_gift_promotion_with_reward_value(+ app_api_client,+ permission_manage_discounts,+ gift_promotion_rule,+):+ # given+ rule = gift_promotion_rule+ rule_id = graphene.Node.to_global_id("PromotionRule", rule.id)+ variables = {+ "id": rule_id,+ "input": {"rewardValue": Decimal(100)},+ }++ # when+ response = app_api_client.post_graphql(+ PROMOTION_RULE_UPDATE_MUTATION,+ variables,+ permissions=(permission_manage_discounts,),+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["promotionRuleUpdate"]+ errors = data["errors"]++ assert not data["promotionRule"]+ assert len(errors) == 1+ assert errors[0]["code"] == PromotionRuleUpdateErrorCode.INVALID.name+ assert errors[0]["field"] == "rewardValue"+++def test_promotion_rule_update_gift_promotion_with_reward_value_type(+ app_api_client,+ permission_manage_discounts,+ gift_promotion_rule,+):+ # given+ rule = gift_promotion_rule+ rule_id = graphene.Node.to_global_id("PromotionRule", rule.id)+ variables = {+ "id": rule_id,+ "input": {"rewardValueType": RewardValueTypeEnum.PERCENTAGE.name},+ }++ # when+ response = app_api_client.post_graphql(+ PROMOTION_RULE_UPDATE_MUTATION,+ variables,+ permissions=(permission_manage_discounts,),+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["promotionRuleUpdate"]+ errors = data["errors"]++ assert not data["promotionRule"]+ assert len(errors) == 1+ assert errors[0]["code"] == PromotionRuleUpdateErrorCode.INVALID.name+ assert errors[0]["field"] == "rewardValueType"+++def test_promotion_rule_update_gift_promotion_remove_gifts(+ app_api_client,+ permission_manage_discounts,+ gift_promotion_rule,+ product_list,+):+ # given+ rule = gift_promotion_rule+ rule_id = graphene.Node.to_global_id("PromotionRule", rule.id)+ gift_ids = [+ graphene.Node.to_global_id("ProductVariant", gift.id)+ for gift in gift_promotion_rule.gifts.all()+ ]+ variables = {+ "id": rule_id,+ "input": {+ "removeGifts": gift_ids,+ },+ }++ # when+ response = app_api_client.post_graphql(+ PROMOTION_RULE_UPDATE_MUTATION,+ variables,+ permissions=(permission_manage_discounts,),+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["promotionRuleUpdate"]+ errors = data["errors"]++ assert not data["promotionRule"]+ assert len(errors) == 1+ assert errors[0]["code"] == PromotionRuleUpdateErrorCode.REQUIRED.name+ assert errors[0]["field"] == "gifts"+++@override_settings(GIFTS_LIMIT_PER_RULE=1)+def test_promotion_rule_update_exceeds_gifts_number_limit(+ app_api_client,+ permission_manage_discounts,+ gift_promotion_rule,+ product_variant_list,+):+ # given+ gift_limit = 1+ rule = gift_promotion_rule+ rule_id = graphene.Node.to_global_id("PromotionRule", rule.id)+ gift_ids = [+ graphene.Node.to_global_id("ProductVariant", variant.pk)+ for variant in product_variant_list+ ]+ current_gift_ids = [+ graphene.Node.to_global_id("ProductVariant", variant.pk)+ for variant in rule.gifts.all()+ ]+ variables = {+ "id": rule_id,+ "input": {+ "addGifts": gift_ids,+ },+ }++ # when+ response = app_api_client.post_graphql(+ PROMOTION_RULE_UPDATE_MUTATION,+ variables,+ permissions=(permission_manage_discounts,),+ )++ # then+ gift_ids = set(gift_ids) | set(current_gift_ids)+ content = get_graphql_content(response)+ data = content["data"]["promotionRuleUpdate"]+ errors = data["errors"]++ assert not data["promotionRule"]+ assert len(errors) == 1+ assert errors[0]["code"] == PromotionRuleUpdateErrorCode.GIFTS_NUMBER_LIMIT.name+ assert errors[0]["field"] == "gifts"+ assert errors[0]["giftsLimit"] == gift_limit+ assert errors[0]["giftsLimitExceedBy"] == len(gift_ids) - gift_limitdiff --git a/saleor/graphql/discount/tests/queries/test_promotion.py b/saleor/graphql/discount/tests/queries/test_promotion.pyindex d58c897b3f..9e5268821c 100644--- a/saleor/graphql/discount/tests/queries/test_promotion.py+++ b/saleor/graphql/discount/tests/queries/test_promotion.py@@ -3,7 +3,7 @@ from decimal import Decimalimport graphene-from .....discount import PromotionEvents, RewardValueType+from .....discount import PromotionEvents, RewardType, RewardValueTypefrom .....tests.utils import dummy_editorjsfrom ....tests.utils import assert_no_permission, get_graphql_content@@ -29,6 +29,7 @@ QUERY_PROMOTION_BY_ID = """rewardValueTyperewardValuecataloguePredicate+ orderPredicaterewardType}}@@ -50,11 +51,17 @@ def _assert_promotion_data(promotion, content_data):"name": rule.name,"description": rule.description,"promotion": {"id": graphene.Node.to_global_id("Promotion", promotion.id)},- "channels": [{"slug": channel.slug} for channel in rule.channels.all()],- "rewardValueType": rule.reward_value_type.upper(),+ "channels": [+ {"slug": channel.slug}+ for channel in rule.channels.all().order_by("slug")+ ],+ "rewardValueType": rule.reward_value_type.upper()+ if rule.reward_value_type+ else None,"rewardValue": rule.reward_value,"cataloguePredicate": rule.catalogue_predicate,- "rewardType": rule.reward_type,+ "orderPredicate": rule.order_predicate,+ "rewardType": rule.reward_type.upper() if rule.reward_type else None,}assert rule_data in promotion_data["rules"]@@ -166,6 +173,49 @@ def test_query_promotion_with_complex_rule_2(_assert_promotion_data(promotion, content)+def test_query_order_promotion_with_gift_rule(+ order_promotion_without_rules,+ gift_promotion_rule,+ staff_api_client,+ permission_group_manage_discounts,+):+ # given+ query = """+ query Promotion($id: ID!) {+ promotion(id: $id) {+ id+ rules {+ rewardType+ giftIds+ giftsLimit+ }+ }+ }+ """+ promotion = order_promotion_without_rules+ permission_group_manage_discounts.user_set.add(staff_api_client.user)+ promotion_id = graphene.Node.to_global_id("Promotion", promotion.id)+ promotion.rules.add(gift_promotion_rule)++ variables = {"id": promotion_id}++ # when+ response = staff_api_client.post_graphql(query, variables)++ # then+ content = get_graphql_content(response)+ rule = content["data"]["promotion"]["rules"][0]+ rule_db = promotion.rules.first()+ assert set(rule["giftIds"]) == set(+ [+ graphene.Node.to_global_id("ProductVariant", gift.pk)+ for gift in rule_db.gifts.all()+ ]+ )+ assert rule["giftsLimit"] == 1+ assert rule["rewardType"] == RewardType.GIFT.upper()++def test_query_promotion_translation(staff_api_client,catalogue_promotion,diff --git a/saleor/graphql/discount/tests/test_validators.py b/saleor/graphql/discount/tests/test_validators.pyindex 6e47c3b60e..cf78342b64 100644--- a/saleor/graphql/discount/tests/test_validators.py+++ b/saleor/graphql/discount/tests/test_validators.py@@ -8,6 +8,7 @@ from ....discount import PromotionType, RewardType, RewardValueTypefrom ..enums import PromotionCreateErrorCodefrom ..mutations.promotion.validators import (_clean_catalogue_predicate,+ _clean_gift_rule,_clean_order_predicate,_clean_predicates,_clean_reward,@@ -262,6 +263,7 @@ def test_clean_order_predicate_missing_reward_type():cleaned_input,order_predicate,{},+ set(),errors,PromotionCreateErrorCode,None,@@ -292,6 +294,7 @@ def test_clean_order_predicate_reward_type_in_instance(cleaned_input,order_predicate,{},+ set(),errors,PromotionCreateErrorCode,None,@@ -319,6 +322,7 @@ def test_clean_order_predicate_price_based_predicate_mixed_currencies():cleaned_input,order_predicate,currencies,+ set(),errors,PromotionCreateErrorCode,None,@@ -353,6 +357,7 @@ def test_clean_order_mixed_currencies_instance_given_invalid_predicate(cleaned_input,order_predicate,currencies,+ set(),errors,PromotionCreateErrorCode,None,@@ -387,6 +392,7 @@ def test_clean_order_mixed_currencies_instance_given_invalid_channels(cleaned_input,order_predicate,currencies,+ set(),errors,PromotionCreateErrorCode,None,@@ -586,3 +592,78 @@ def test_clean_reward_value_multiple_currencies_error_not_raised_for_percentage_# thenassert not errors+++def test_clean_gift_rule(product_variant_list):+ # given+ cleaned_input = {+ "reward_type": RewardType.GIFT,+ "reward_value": None,+ "reward_value_type": None,+ }+ gift_ids = [+ graphene.Node.to_global_id("ProductVariant", variant.id)+ for variant in product_variant_list+ ]+ errors = defaultdict(list)++ # when+ _clean_gift_rule(+ cleaned_input, gift_ids, errors, PromotionCreateErrorCode, None, None+ )++ # then+ assert not errors++[email protected]("index", [None, 1, 0])+def test_clean_gift_rule_no_gifts(index):+ # given+ cleaned_input = {+ "reward_type": RewardType.GIFT,+ "reward_value": None,+ "reward_value_type": None,+ }+ gift_ids = []+ errors = defaultdict(list)+ index = 1++ # when+ _clean_gift_rule(+ cleaned_input, gift_ids, errors, PromotionCreateErrorCode, index, None+ )++ # then+ assert len(errors) == 1+ assert len(errors["gifts"]) == 1+ assert errors["gifts"][0].code == PromotionCreateErrorCode.REQUIRED.value+ assert errors["gifts"][0].params["index"] == index++[email protected]("field", ["gifts", "add_gifts", "remove_gifts"])+def test_clean_gift_rule_invalid_gift_type(field, product_variant_list):+ # given+ gift_ids = [+ graphene.Node.to_global_id("Product", variant.id)+ for variant in product_variant_list+ ]+ cleaned_input = {+ "reward_type": RewardType.GIFT,+ "reward_value": None,+ "reward_value_type": None,+ field: gift_ids,+ }++ errors = defaultdict(list)+ index = 1++ # when+ _clean_gift_rule(+ cleaned_input, gift_ids, errors, PromotionCreateErrorCode, index, None+ )++ # then+ assert len(errors) == 1+ assert len(errors[field]) == 1+ assert errors[field][0].code == PromotionCreateErrorCode.INVALID_GIFT_TYPE.value+ assert errors[field][0].params["index"] == indexdiff --git a/saleor/graphql/discount/types/promotions.py b/saleor/graphql/discount/types/promotions.pyindex 5a8187d64a..b760f85201 100644--- a/saleor/graphql/discount/types/promotions.py+++ b/saleor/graphql/discount/types/promotions.py@@ -16,6 +16,7 @@ from ...translations.fields import TranslationFieldfrom ...translations.types import PromotionRuleTranslation, PromotionTranslationfrom ..dataloaders import (ChannelsByPromotionRuleIdLoader,+ GiftsByPromotionRuleIDLoader,PromotionByIdLoader,PromotionEventsByPromotionIdLoader,PromotionRulesByPromotionIdLoader,@@ -122,6 +123,18 @@ class PromotionRule(ModelObjectType[models.PromotionRule]):+ PREVIEW_FEATURE)translation = TranslationField(PromotionRuleTranslation, type_name="promotion rule")+ gift_ids = NonNullList(+ graphene.ID,+ description="Product variant IDs available as a gift to choose."+ + ADDED_IN_319+ + PREVIEW_FEATURE,+ )+ gifts_limit = graphene.Int(+ default_value=1,+ description="Defines the maximum number of gifts to choose from the gifts list."+ + ADDED_IN_319+ + PREVIEW_FEATURE,+ )class Meta:description = (@@ -151,6 +164,15 @@ class PromotionRule(ModelObjectType[models.PromotionRule]):def resolve_channels(root: models.PromotionRule, info: ResolveInfo):return ChannelsByPromotionRuleIdLoader(info.context).load(root.id)+ @staticmethod+ def resolve_gift_ids(root: models.PromotionRule, info: ResolveInfo):+ def with_gifts(gifts):+ return [+ graphene.Node.to_global_id("ProductVariant", gift.pk) for gift in gifts+ ]++ return GiftsByPromotionRuleIDLoader(info.context).load(root.id).then(with_gifts)+class PromotionCountableConnection(CountableConnection):class Meta:diff --git a/saleor/graphql/order/mutations/order_line_delete.py b/saleor/graphql/order/mutations/order_line_delete.pyindex 0a978ec616..ba045a9197 100644--- a/saleor/graphql/order/mutations/order_line_delete.py+++ b/saleor/graphql/order/mutations/order_line_delete.py@@ -3,6 +3,7 @@ import graphenefrom ....core.taxes import zero_taxed_moneyfrom ....core.tracing import traced_atomic_transactionfrom ....order import events+from ....order.error_codes import OrderErrorCodefrom ....order.fetch import OrderLineInfofrom ....order.search import update_order_search_vectorfrom ....order.utils import (@@ -16,6 +17,7 @@ from ...core import ResolveInfofrom ...core.doc_category import DOC_CATEGORY_ORDERSfrom ...core.mutations import BaseMutationfrom ...core.types import OrderError+from ...core.utils import raise_validation_errorfrom ...plugins.dataloaders import get_plugin_manager_promisefrom ..types import Order, OrderLinefrom .utils import EditableOrderValidationMixin, get_webhook_handler_by_order_status@@ -48,8 +50,7 @@ class OrderLineDelete(EditableOrderValidationMixin, BaseMutation):only_type=OrderLine,)order = line.order- cls.check_channel_permissions(info, [order.channel_id])- cls.validate_order(line.order)+ cls.validate(info, order, line)db_id = line.idwarehouse_pk = (@@ -99,3 +100,14 @@ class OrderLineDelete(EditableOrderValidationMixin, BaseMutation):func = get_webhook_handler_by_order_status(order.status, manager)cls.call_event(func, order)return OrderLineDelete(order=order, order_line=line)++ @classmethod+ def validate(cls, info, order, line):+ cls.check_channel_permissions(info, [order.channel_id])+ cls.validate_order(line.order)+ if line.is_gift:+ raise_validation_error(+ message="Order line marked as gift can't be deleted.",+ field="id",+ code=OrderErrorCode.NON_REMOVABLE_GIFT_LINE.value,+ )diff --git a/saleor/graphql/order/mutations/order_line_update.py b/saleor/graphql/order/mutations/order_line_update.pyindex 54136c9fc7..572b561485 100644--- a/saleor/graphql/order/mutations/order_line_update.py+++ b/saleor/graphql/order/mutations/order_line_update.py@@ -57,6 +57,16 @@ class OrderLineUpdate()})+ if instance.is_gift:+ raise ValidationError(+ {+ "id": ValidationError(+ "Order line marked as gift can't be edited.",+ code=OrderErrorCode.NON_EDITABLE_GIFT_LINE.value,+ )+ }+ )+return cleaned_input@classmethoddiff --git a/saleor/graphql/order/tests/mutations/test_order_line_delete.py b/saleor/graphql/order/tests/mutations/test_order_line_delete.pyindex bbe8da92f3..d48d142ff7 100644--- a/saleor/graphql/order/tests/mutations/test_order_line_delete.py+++ b/saleor/graphql/order/tests/mutations/test_order_line_delete.py@@ -6,6 +6,7 @@ from django.db.models import Sumfrom .....order import OrderStatusfrom .....order import events as order_events+from .....order.error_codes import OrderErrorCodefrom .....order.models import OrderEventfrom .....warehouse.models import Stockfrom ....tests.utils import assert_no_permission, get_graphql_content@@ -17,6 +18,7 @@ ORDER_LINE_DELETE_MUTATION = """errors {fieldmessage+ code}orderLine {id@@ -232,3 +234,31 @@ def test_draft_order_properly_recalculate_total_after_shipping_product_removed(assert data["order"]["total"]["net"]["amount"] == float(line.total_price_net_amount) + float(order.shipping_price_net_amount)+++def test_order_line_delete_non_removable_gift(+ draft_order,+ permission_group_manage_orders,+ staff_api_client,+):+ # given+ query = ORDER_LINE_DELETE_MUTATION+ permission_group_manage_orders.user_set.add(staff_api_client.user)+ order = draft_order+ line = order.lines.first()+ line.is_gift = True+ line.save(update_fields=["is_gift"])+ line_id = graphene.Node.to_global_id("OrderLine", line.id)+ variables = {"id": line_id}++ # when+ response = staff_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)++ # then+ data = content["data"]["orderLineDelete"]+ assert not data["orderLine"]+ errors = data["errors"]+ assert len(errors) == 1+ assert errors[0]["field"] == "id"+ assert errors[0]["code"] == OrderErrorCode.NON_REMOVABLE_GIFT_LINE.namediff --git a/saleor/graphql/order/tests/mutations/test_order_line_update.py b/saleor/graphql/order/tests/mutations/test_order_line_update.pyindex 18e235640f..9a9e09697c 100644--- a/saleor/graphql/order/tests/mutations/test_order_line_update.py+++ b/saleor/graphql/order/tests/mutations/test_order_line_update.py@@ -5,6 +5,7 @@ import pytestfrom .....order import OrderStatusfrom .....order import events as order_events+from .....order.error_codes import OrderErrorCodefrom .....order.models import OrderEventfrom .....product.models import ProductVariantfrom .....tests.utils import flush_post_commit_hooks@@ -18,6 +19,7 @@ ORDER_LINE_UPDATE_MUTATION = """errors {fieldmessage+ code}orderLine {id@@ -368,15 +370,50 @@ def test_invalid_order_when_updating_lines(staff_api_client,permission_group_manage_orders,):+ # givenquery = ORDER_LINE_UPDATE_MUTATIONpermission_group_manage_orders.user_set.add(staff_api_client.user)order = order_with_linesline = order.lines.first()line_id = graphene.Node.to_global_id("OrderLine", line.id)variables = {"lineId": line_id, "quantity": 1}++ # whenresponse = staff_api_client.post_graphql(query, variables)++ # thencontent = get_graphql_content(response)data = content["data"]["orderLineUpdate"]assert data["errors"]order_update_webhook_mock.assert_not_called()draft_order_update_webhook_mock.assert_not_called()+++def test_order_line_update_quantity_gift(+ order_with_lines,+ staff_api_client,+ permission_group_manage_orders,+):+ # given+ query = ORDER_LINE_UPDATE_MUTATION+ permission_group_manage_orders.user_set.add(staff_api_client.user)+ order = order_with_lines+ order.status = OrderStatus.UNCONFIRMED+ order.save(update_fields=["status"])+ line = order.lines.first()+ line.is_gift = True+ line.save(update_fields=["is_gift"])+ line_id = graphene.Node.to_global_id("OrderLine", line.id)+ variables = {"lineId": line_id, "quantity": 1}++ # when+ response = staff_api_client.post_graphql(query, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["orderLineUpdate"]+ assert not data["orderLine"]+ errors = data["errors"]+ assert len(errors) == 1+ assert errors[0]["field"] == "id"+ assert errors[0]["code"] == OrderErrorCode.NON_EDITABLE_GIFT_LINE.namediff --git a/saleor/graphql/order/tests/queries/test_order_line.py b/saleor/graphql/order/tests/queries/test_order_line.pyindex cb09c6b6b2..0d19fb0322 100644--- a/saleor/graphql/order/tests/queries/test_order_line.py+++ b/saleor/graphql/order/tests/queries/test_order_line.py@@ -77,6 +77,7 @@ def test_order_line_query(value}taxRate+ isGift}}}@@ -161,6 +162,7 @@ def test_order_line_query(first_order_data_line["taxClassPrivateMetadata"][0]["value"]== list(line_tax_class.private_metadata.values())[0])+ assert first_order_data_line["isGift"] is Falsedef test_denormalized_tax_class_in_orderline_query(diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.pyindex 0b4e09795d..ea099f4007 100644--- a/saleor/graphql/order/types.py+++ b/saleor/graphql/order/types.py@@ -76,6 +76,7 @@ from ..core.descriptions import (ADDED_IN_314,ADDED_IN_315,ADDED_IN_318,+ ADDED_IN_319,DEPRECATED_IN_3X_FIELD,PREVIEW_FEATURE,)@@ -859,6 +860,9 @@ class OrderLine(ModelObjectType[models.OrderLine]):required=False,description="Voucher code that was used for this order line." + ADDED_IN_314,)+ is_gift = graphene.Boolean(+ description="Determine if the line is a gift." + ADDED_IN_319 + PREVIEW_FEATURE,+ )class Meta:description = "Represents order line of particular order."diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex eb3738ade8..a8cea7b795 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -11170,6 +11170,15 @@ type CheckoutLine implements Node & ObjectWithMetadata @doc(category: "Checkout"Note: this API is currently in Feature Preview and can be subject to changes at later point."""problems: [CheckoutLineProblem!]++ """+ Determine if the line is a gift.++ Added in Saleor 3.19.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ isGift: Boolean}"""@@ -12106,6 +12115,15 @@ type OrderLine implements Node & ObjectWithMetadata @doc(category: "Orders") {Added in Saleor 3.14."""voucherCode: String++ """+ Determine if the line is a gift.++ Added in Saleor 3.19.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ isGift: Boolean}"""@@ -12794,6 +12812,8 @@ enum OrderErrorCode @doc(category: "Orders") {CHANNEL_INACTIVEINVALID_VOUCHERINVALID_VOUCHER_CODE+ NON_EDITABLE_GIFT_LINE+ NON_REMOVABLE_GIFT_LINE}"""An enumeration."""@@ -14344,6 +14364,24 @@ type PromotionRule implements Node @doc(category: "Discounts") {"""A language code to return the translation for promotion rule."""languageCode: LanguageCodeEnum!): PromotionRuleTranslation++ """+ Product variant IDs available as a gift to choose.++ Added in Saleor 3.19.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ giftIds: [ID!]++ """+ Defines the maximum number of gifts to choose from the gifts list.++ Added in Saleor 3.19.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ giftsLimit: Int}"""An enumeration."""@@ -14355,6 +14393,7 @@ enum RewardValueTypeEnum @doc(category: "Discounts") {"""An enumeration."""enum RewardTypeEnum @doc(category: "Discounts") {SUBTOTAL_DISCOUNT+ GIFT}union PromotionEvent = PromotionCreatedEvent | PromotionUpdatedEvent | PromotionStartedEvent | PromotionEndedEvent | PromotionRuleCreatedEvent | PromotionRuleUpdatedEvent | PromotionRuleDeletedEvent@@ -27514,7 +27553,13 @@ type PromotionCreateError {rulesLimit: Int"""Number of rules with orderPredicate defined exceeding the limit."""- exceedBy: Int+ rulesLimitExceedBy: Int++ """Limit of gifts assigned to promotion rule."""+ giftsLimit: Int++ """Number of gifts defined for this promotion rule exceeding the limit."""+ giftsLimitExceedBy: Int}"""An enumeration."""@@ -27527,6 +27572,8 @@ enum PromotionCreateErrorCode {INVALID_PRECISIONMISSING_CHANNELSRULES_NUMBER_LIMIT+ GIFTS_NUMBER_LIMIT+ INVALID_GIFT_TYPE}input PromotionCreateInput @doc(category: "Discounts") {@@ -27599,6 +27646,15 @@ input PromotionRuleInput @doc(category: "Discounts") {"""List of channel ids to which the rule should apply to."""channels: [ID!]++ """+ Product variant IDs available as a gift to choose.++ Added in Saleor 3.19.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ gifts: [ID!]}input CataloguePredicateInput @doc(category: "Discounts") {@@ -27769,7 +27825,13 @@ type PromotionRuleCreateError {rulesLimit: Int"""Number of rules with orderPredicate defined exceeding the limit."""- exceedBy: Int+ rulesLimitExceedBy: Int++ """Limit of gifts assigned to promotion rule."""+ giftsLimit: Int++ """Number of gifts defined for this promotion rule exceeding the limit."""+ giftsLimitExceedBy: Int}"""An enumeration."""@@ -27782,6 +27844,8 @@ enum PromotionRuleCreateErrorCode {INVALID_PRECISIONMISSING_CHANNELSRULES_NUMBER_LIMIT+ GIFTS_NUMBER_LIMIT+ INVALID_GIFT_TYPE}input PromotionRuleCreateInput {@@ -27827,6 +27891,15 @@ input PromotionRuleCreateInput {"""List of channel ids to which the rule should apply to."""channels: [ID!]+ """+ Product variant IDs available as a gift to choose.++ Added in Saleor 3.19.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ gifts: [ID!]+"""The ID of the promotion that rule belongs to."""promotion: ID!}@@ -27862,6 +27935,12 @@ type PromotionRuleUpdateError {"""List of channel IDs which causes the error."""channels: [ID!]++ """Limit of gifts assigned to promotion rule."""+ giftsLimit: Int++ """Number of gifts defined for this promotion rule exceeding the limit."""+ giftsLimitExceedBy: Int}"""An enumeration."""@@ -27874,6 +27953,8 @@ enum PromotionRuleUpdateErrorCode {MISSING_CHANNELSMULTIPLE_CURRENCIES_NOT_ALLOWEDINVALID_PRECISION+ INVALID_GIFT_TYPE+ GIFTS_NUMBER_LIMIT}input PromotionRuleUpdateInput {@@ -27921,6 +28002,24 @@ input PromotionRuleUpdateInput {"""List of channel ids to remove."""removeChannels: [ID!]++ """+ List of variant IDs available as a gift to add.++ Added in Saleor 3.19.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ addGifts: [ID!]++ """+ List of variant IDs available as a gift to remove.++ Added in Saleor 3.19.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ removeGifts: [ID!]}"""@@ -28759,6 +28858,8 @@ enum CheckoutErrorCode @doc(category: "Checkout") {EMAIL_NOT_SETNO_LINESINACTIVE_PAYMENT+ NON_EDITABLE_GIFT_LINE+ NON_REMOVABLE_GIFT_LINE}"""diff --git a/saleor/graphql/tax/mutations/tax_exemption_manage.py b/saleor/graphql/tax/mutations/tax_exemption_manage.pyindex c352c7d5a7..dcc7bed2e4 100644--- a/saleor/graphql/tax/mutations/tax_exemption_manage.py+++ b/saleor/graphql/tax/mutations/tax_exemption_manage.py@@ -3,7 +3,7 @@ from django.core.exceptions import ValidationErrorfrom ....checkout.fetch import fetch_checkout_info, fetch_checkout_linesfrom ....checkout.models import Checkout-from ....checkout.utils import invalidate_checkout_prices+from ....checkout.utils import invalidate_checkoutfrom ....graphql.core.mutations import BaseMutationfrom ....order import ORDER_EDITABLE_STATUSfrom ....order.models import Order@@ -75,12 +75,12 @@ class TaxExemptionManage(BaseMutation):return obj@classmethod- def _invalidate_checkout_prices(cls, info: ResolveInfo, checkout):+ def _invalidate_checkout(cls, info: ResolveInfo, checkout):manager = get_plugin_manager_promise(info.context).get()checkout_info = fetch_checkout_info(checkout, [], manager)lines_info, _ = fetch_checkout_lines(checkout)- invalidate_checkout_prices(+ invalidate_checkout(checkout_info,lines_info,manager,@@ -94,7 +94,7 @@ class TaxExemptionManage(BaseMutation):obj.tax_exemption = data["tax_exemption"]if isinstance(obj, Checkout):- cls._invalidate_checkout_prices(info, obj)+ cls._invalidate_checkout(info, obj)obj.save(update_fields=["tax_exemption", "price_expiration", "last_change"])if isinstance(obj, Order):diff --git a/saleor/order/error_codes.py b/saleor/order/error_codes.pyindex 46e91a4d4c..0fd975a4b7 100644--- a/saleor/order/error_codes.py+++ b/saleor/order/error_codes.py@@ -36,6 +36,8 @@ class OrderErrorCode(Enum):CHANNEL_INACTIVE = "channel_inactive"INVALID_VOUCHER = "invalid_voucher"INVALID_VOUCHER_CODE = "invalid_voucher_code"+ NON_EDITABLE_GIFT_LINE = "non_editable_gift_line"+ NON_REMOVABLE_GIFT_LINE = "non_removable_gift_line"class OrderGrantRefundCreateErrorCode(Enum):diff --git a/saleor/order/migrations/0182_orderline_is_gift.py b/saleor/order/migrations/0182_orderline_is_gift.pynew file mode 100644index 0000000000..bd59d56e90--- /dev/null+++ b/saleor/order/migrations/0182_orderline_is_gift.py@@ -0,0 +1,25 @@+# Generated by Django 3.2.23 on 2024-01-19 14:03++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("order", "0181_order_subtotal_as_a_field"),+ ]++ operations = [+ migrations.AddField(+ model_name="orderline",+ name="is_gift",+ field=models.BooleanField(default=False),+ ),+ migrations.RunSQL(+ sql="""+ ALTER TABLE order_orderline+ ALTER COLUMN is_gift+ SET DEFAULT false;+ """,+ reverse_sql=migrations.RunSQL.noop,+ ),+ ]diff --git a/saleor/order/models.py b/saleor/order/models.pyindex 8ca1a8cb6f..21831264b3 100644--- a/saleor/order/models.py+++ b/saleor/order/models.py@@ -549,6 +549,7 @@ class OrderLine(ModelWithMetadata):quantity_fulfilled = models.IntegerField(validators=[MinValueValidator(0)], default=0)+ is_gift = models.BooleanField(default=False)currency = models.CharField(max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH,diff --git a/saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_checkout_line_total_gift_promotion_line.yaml b/saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_checkout_line_total_gift_promotion_line.yamlnew file mode 100644index 0000000000..f84ce185aa--- /dev/null+++ b/saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_checkout_line_total_gift_promotion_line.yaml@@ -0,0 +1,78 @@+interactions:+- request:+ body: '{"createTransactionModel": {"companyCode": "DEFAULT", "type": "SalesOrder",+ "lines": [{"quantity": 3, "amount": "30.00", "taxCode": "O9999999", "taxIncluded":+ true, "itemCode": "123", "discounted": false, "description": "Test product",+ "ref1": "123"}, {"quantity": 1, "amount": "0.00", "taxCode": "O9999999", "taxIncluded":+ true, "itemCode": "3d71bfdd15484e538e77fbff1c34ba85", "discounted": false, "description":+ "Test product 2", "ref1": "3d71bfdd15484e538e77fbff1c34ba85"}, {"quantity":+ 1, "amount": "10.000", "taxCode": "FR000000", "taxIncluded": true, "itemCode":+ "Shipping", "discounted": false, "description": null}], "code": "be91dcaf-f569-4087-91f4-045464848da9",+ "date": "2024-01-26", "customerCode": 0, "discount": null, "addresses": {"shipFrom":+ {"line1": "Teczowa 7", "line2": "", "city": "Wroclaw", "region": "", "country":+ "PL", "postalCode": "53-601"}, "shipTo": {"line1": "O\u0142awska 10", "line2":+ "", "city": "WROC\u0141AW", "region": "", "country": "PL", "postalCode": "53-105"}},+ "commit": false, "currencyCode": "USD", "email": "[email protected]"}}'+ headers:+ Accept:+ - '*/*'+ Accept-Encoding:+ - gzip, deflate, br+ Authorization:+ - Basic Og==+ Connection:+ - keep-alive+ Content-Length:+ - '1069'+ User-Agent:+ - Saleor/3.19+ method: POST+ uri: https://sandbox-rest.avatax.com/api/v2/transactions/createoradjust+ response:+ body:+ string: '{"id":0,"code":"be91dcaf-f569-4087-91f4-045464848da9","companyId":7799660,"date":"2024-01-26","paymentDate":"2024-01-26","status":"Temporary","type":"SalesOrder","batchCode":"","currencyCode":"USD","exchangeRateCurrencyCode":"USD","customerUsageType":"","entityUseCode":"","customerVendorCode":"0","customerCode":"0","exemptNo":"","reconciled":false,"locationCode":"","reportingLocationCode":"","purchaseOrderNo":"","referenceCode":"","salespersonCode":"","totalAmount":32.52,"totalExempt":0.0,"totalDiscount":0.0,"totalTax":7.48,"totalTaxable":32.52,"totalTaxCalculated":7.48,"adjustmentReason":"NotAdjusted","locked":false,"version":1,"exchangeRateEffectiveDate":"2024-01-26","exchangeRate":1.0,"email":"[email protected]","modifiedDate":"2024-01-26T09:21:44.6188868Z","modifiedUserId":6479978,"taxDate":"2024-01-26","lines":[{"id":0,"transactionId":0,"lineNumber":"1","customerUsageType":"","entityUseCode":"","description":"Test+ product","discountAmount":0.0,"exemptAmount":0.0,"exemptCertId":0,"exemptNo":"","isItemTaxable":true,"itemCode":"123","lineAmount":24.3900,"quantity":3.0,"ref1":"123","ref2":"","reportingDate":"2024-01-26","tax":5.61,"taxableAmount":24.39,"taxCalculated":5.61,"taxCode":"O9999999","taxCodeId":9111,"taxDate":"2024-01-26","taxIncluded":true,"details":[{"id":0,"transactionLineId":0,"transactionId":0,"country":"PL","region":"PL","exemptAmount":0.0,"jurisCode":"PL","jurisName":"POLAND","stateAssignedNo":"","jurisType":"CNT","jurisdictionType":"Country","nonTaxableAmount":0.0,"rate":0.230000,"tax":5.61,"taxableAmount":24.39,"taxType":"Output","taxSubTypeId":"O","taxName":"Standard+ Rate","taxAuthorityTypeId":45,"taxCalculated":5.61,"rateType":"Standard","rateTypeCode":"S","taxableUnits":24.3900,"nonTaxableUnits":0.0000,"exemptUnits":0.0000,"unitOfBasis":"PerCurrencyUnit","isNonPassThru":false,"isFee":false,"reportingTaxableUnits":24.39,"reportingNonTaxableUnits":0.0,"reportingExemptUnits":0.0,"reportingTax":5.61,"reportingTaxCalculated":5.61,"liabilityType":"Seller","chargedTo":"Buyer"}],"nonPassthroughDetails":[],"hsCode":"","costInsuranceFreight":0.0,"vatCode":"PLS-230C","vatNumberTypeId":0},{"id":0,"transactionId":0,"lineNumber":"2","customerUsageType":"","entityUseCode":"","description":"Test+ product 2","discountAmount":0.0,"exemptAmount":0.0,"exemptCertId":0,"exemptNo":"","isItemTaxable":false,"itemCode":"3d71bfdd15484e538e77fbff1c34ba85","lineAmount":0.0,"quantity":1.0,"ref1":"3d71bfdd15484e538e77fbff1c34ba85","ref2":"","reportingDate":"2024-01-26","tax":0.0,"taxableAmount":0.0,"taxCalculated":0.0,"taxCode":"O9999999","taxCodeId":9111,"taxDate":"2024-01-26","taxIncluded":true,"details":[{"id":0,"transactionLineId":0,"transactionId":0,"country":"PL","region":"PL","exemptAmount":0.0,"jurisCode":"PL","jurisName":"POLAND","stateAssignedNo":"","jurisType":"CNT","jurisdictionType":"Country","nonTaxableAmount":0.0,"rate":0.230000,"tax":0.0,"taxableAmount":0.0,"taxType":"Output","taxSubTypeId":"O","taxName":"Standard+ Rate","taxAuthorityTypeId":45,"taxCalculated":0.0,"rateType":"Standard","rateTypeCode":"S","taxableUnits":0.0000,"nonTaxableUnits":0.0000,"exemptUnits":0.0000,"unitOfBasis":"PerCurrencyUnit","isNonPassThru":false,"isFee":false,"reportingTaxableUnits":0.0,"reportingNonTaxableUnits":0.0,"reportingExemptUnits":0.0,"reportingTax":0.0,"reportingTaxCalculated":0.0,"liabilityType":"Seller","chargedTo":"Buyer"}],"nonPassthroughDetails":[],"hsCode":"","costInsuranceFreight":0.0,"vatCode":"PLS-230C","vatNumberTypeId":0},{"id":0,"transactionId":0,"lineNumber":"3","customerUsageType":"","entityUseCode":"","discountAmount":0.0,"exemptAmount":0.0,"exemptCertId":0,"exemptNo":"","isItemTaxable":true,"itemCode":"Shipping","lineAmount":8.1300,"quantity":1.0,"ref1":"","ref2":"","reportingDate":"2024-01-26","tax":1.87,"taxableAmount":8.13,"taxCalculated":1.87,"taxCode":"FR000000","taxCodeId":8550,"taxDate":"2024-01-26","taxIncluded":true,"details":[{"id":0,"transactionLineId":0,"transactionId":0,"country":"PL","region":"PL","exemptAmount":0.0,"jurisCode":"PL","jurisName":"POLAND","stateAssignedNo":"","jurisType":"CNT","jurisdictionType":"Country","nonTaxableAmount":0.0,"rate":0.230000,"tax":1.87,"taxableAmount":8.13,"taxType":"Output","taxSubTypeId":"O","taxName":"Standard+ Rate","taxAuthorityTypeId":45,"taxCalculated":1.87,"rateType":"Standard","rateTypeCode":"S","taxableUnits":8.1300,"nonTaxableUnits":0.0000,"exemptUnits":0.0000,"unitOfBasis":"PerCurrencyUnit","isNonPassThru":false,"isFee":false,"reportingTaxableUnits":8.13,"reportingNonTaxableUnits":0.0,"reportingExemptUnits":0.0,"reportingTax":1.87,"reportingTaxCalculated":1.87,"liabilityType":"Seller","chargedTo":"Buyer"}],"nonPassthroughDetails":[],"hsCode":"","costInsuranceFreight":0.0,"vatCode":"PLS-230D","vatNumberTypeId":0}],"addresses":[{"id":0,"transactionId":0,"boundaryLevel":"Zip5","line1":"Olawska+ 10","line2":"","line3":"","city":"WROCLAW","region":"","postalCode":"53-105","country":"PL","taxRegionId":205102,"latitude":"","longitude":""},{"id":0,"transactionId":0,"boundaryLevel":"Zip5","line1":"Teczowa+ 7","line2":"","line3":"","city":"Wroclaw","region":"","postalCode":"53-601","country":"PL","taxRegionId":205102,"latitude":"","longitude":""}],"summary":[{"country":"PL","region":"PL","jurisType":"Country","jurisCode":"PL","jurisName":"POLAND","taxAuthorityType":45,"stateAssignedNo":"","taxType":"Output","taxSubType":"O","taxName":"Standard+ Rate","rateType":"Standard","taxable":32.52,"rate":0.230000,"tax":7.48,"taxCalculated":7.48,"nonTaxable":0.0,"exemption":0.0}]}'+ headers:+ Connection:+ - keep-alive+ Content-Type:+ - application/json; charset=utf-8+ Date:+ - Fri, 26 Jan 2024 09:21:44 GMT+ Location:+ - /api/v2/companies/7799660/transactions/0+ ServerDuration:+ - '00:00:00.0220891'+ Transfer-Encoding:+ - chunked+ X-Content-Type-Options:+ - nosniff+ api-supported-versions:+ - '2.0'+ cache-control:+ - private, no-cache, no-store+ referrer-policy:+ - same-origin+ strict-transport-security:+ - max-age=31536000; includeSubdomains+ x-avalara-uid:+ - b4f6a642-69e7-427a-be0c-76afdfc2137a+ x-correlation-id:+ - b4f6a642-69e7-427a-be0c-76afdfc2137a+ x-frame-options:+ - sameorigin+ x-permitted-cross-domain-policies:+ - none+ x-xss-protection:+ - 1; mode=block+ status:+ code: 201+ message: Created+version: 1diff --git a/saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_checkout_line_unit_price_gift_promotion_line.yaml b/saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_checkout_line_unit_price_gift_promotion_line.yamlnew file mode 100644index 0000000000..6ccc02e687--- /dev/null+++ b/saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_checkout_line_unit_price_gift_promotion_line.yaml@@ -0,0 +1,78 @@+interactions:+- request:+ body: '{"createTransactionModel": {"companyCode": "DEFAULT", "type": "SalesOrder",+ "lines": [{"quantity": 3, "amount": "30.00", "taxCode": "O9999999", "taxIncluded":+ true, "itemCode": "123", "discounted": false, "description": "Test product",+ "ref1": "123"}, {"quantity": 1, "amount": "0.00", "taxCode": "O9999999", "taxIncluded":+ true, "itemCode": "1623bf453d5f4404a5d5d34ec593e289", "discounted": false, "description":+ "Test product 2", "ref1": "1623bf453d5f4404a5d5d34ec593e289"}, {"quantity":+ 1, "amount": "10.000", "taxCode": "FR000000", "taxIncluded": true, "itemCode":+ "Shipping", "discounted": false, "description": null}], "code": "a1a100de-ef60-4b2b-9e15-c1ef5b709dfe",+ "date": "2024-01-26", "customerCode": 0, "discount": null, "addresses": {"shipFrom":+ {"line1": "Teczowa 7", "line2": "", "city": "Wroclaw", "region": "", "country":+ "PL", "postalCode": "53-601"}, "shipTo": {"line1": "T\u0119czowa 7", "line2":+ "", "city": "WROC\u0141AW", "region": "", "country": "PL", "postalCode": "53-601"}},+ "commit": false, "currencyCode": "USD", "email": "[email protected]"}}'+ headers:+ Accept:+ - '*/*'+ Accept-Encoding:+ - gzip, deflate, br+ Authorization:+ - Basic Og==+ Connection:+ - keep-alive+ Content-Length:+ - '1068'+ User-Agent:+ - Saleor/3.19+ method: POST+ uri: https://sandbox-rest.avatax.com/api/v2/transactions/createoradjust+ response:+ body:+ string: '{"id":0,"code":"a1a100de-ef60-4b2b-9e15-c1ef5b709dfe","companyId":7799660,"date":"2024-01-26","paymentDate":"2024-01-26","status":"Temporary","type":"SalesOrder","batchCode":"","currencyCode":"USD","exchangeRateCurrencyCode":"USD","customerUsageType":"","entityUseCode":"","customerVendorCode":"0","customerCode":"0","exemptNo":"","reconciled":false,"locationCode":"","reportingLocationCode":"","purchaseOrderNo":"","referenceCode":"","salespersonCode":"","totalAmount":32.52,"totalExempt":0.0,"totalDiscount":0.0,"totalTax":7.48,"totalTaxable":32.52,"totalTaxCalculated":7.48,"adjustmentReason":"NotAdjusted","locked":false,"version":1,"exchangeRateEffectiveDate":"2024-01-26","exchangeRate":1.0,"email":"[email protected]","modifiedDate":"2024-01-26T09:07:19.3028869Z","modifiedUserId":6479978,"taxDate":"2024-01-26","lines":[{"id":0,"transactionId":0,"lineNumber":"1","customerUsageType":"","entityUseCode":"","description":"Test+ product","discountAmount":0.0,"exemptAmount":0.0,"exemptCertId":0,"exemptNo":"","isItemTaxable":true,"itemCode":"123","lineAmount":24.3900,"quantity":3.0,"ref1":"123","ref2":"","reportingDate":"2024-01-26","tax":5.61,"taxableAmount":24.39,"taxCalculated":5.61,"taxCode":"O9999999","taxCodeId":9111,"taxDate":"2024-01-26","taxIncluded":true,"details":[{"id":0,"transactionLineId":0,"transactionId":0,"country":"PL","region":"PL","exemptAmount":0.0,"jurisCode":"PL","jurisName":"POLAND","stateAssignedNo":"","jurisType":"CNT","jurisdictionType":"Country","nonTaxableAmount":0.0,"rate":0.230000,"tax":5.61,"taxableAmount":24.39,"taxType":"Output","taxSubTypeId":"O","taxName":"Standard+ Rate","taxAuthorityTypeId":45,"taxCalculated":5.61,"rateType":"Standard","rateTypeCode":"S","taxableUnits":24.3900,"nonTaxableUnits":0.0000,"exemptUnits":0.0000,"unitOfBasis":"PerCurrencyUnit","isNonPassThru":false,"isFee":false,"reportingTaxableUnits":24.39,"reportingNonTaxableUnits":0.0,"reportingExemptUnits":0.0,"reportingTax":5.61,"reportingTaxCalculated":5.61,"liabilityType":"Seller","chargedTo":"Buyer"}],"nonPassthroughDetails":[],"hsCode":"","costInsuranceFreight":0.0,"vatCode":"PLS-230C","vatNumberTypeId":0},{"id":0,"transactionId":0,"lineNumber":"2","customerUsageType":"","entityUseCode":"","description":"Test+ product 2","discountAmount":0.0,"exemptAmount":0.0,"exemptCertId":0,"exemptNo":"","isItemTaxable":false,"itemCode":"1623bf453d5f4404a5d5d34ec593e289","lineAmount":0.0,"quantity":1.0,"ref1":"1623bf453d5f4404a5d5d34ec593e289","ref2":"","reportingDate":"2024-01-26","tax":0.0,"taxableAmount":0.0,"taxCalculated":0.0,"taxCode":"O9999999","taxCodeId":9111,"taxDate":"2024-01-26","taxIncluded":true,"details":[{"id":0,"transactionLineId":0,"transactionId":0,"country":"PL","region":"PL","exemptAmount":0.0,"jurisCode":"PL","jurisName":"POLAND","stateAssignedNo":"","jurisType":"CNT","jurisdictionType":"Country","nonTaxableAmount":0.0,"rate":0.230000,"tax":0.0,"taxableAmount":0.0,"taxType":"Output","taxSubTypeId":"O","taxName":"Standard+ Rate","taxAuthorityTypeId":45,"taxCalculated":0.0,"rateType":"Standard","rateTypeCode":"S","taxableUnits":0.0000,"nonTaxableUnits":0.0000,"exemptUnits":0.0000,"unitOfBasis":"PerCurrencyUnit","isNonPassThru":false,"isFee":false,"reportingTaxableUnits":0.0,"reportingNonTaxableUnits":0.0,"reportingExemptUnits":0.0,"reportingTax":0.0,"reportingTaxCalculated":0.0,"liabilityType":"Seller","chargedTo":"Buyer"}],"nonPassthroughDetails":[],"hsCode":"","costInsuranceFreight":0.0,"vatCode":"PLS-230C","vatNumberTypeId":0},{"id":0,"transactionId":0,"lineNumber":"3","customerUsageType":"","entityUseCode":"","discountAmount":0.0,"exemptAmount":0.0,"exemptCertId":0,"exemptNo":"","isItemTaxable":true,"itemCode":"Shipping","lineAmount":8.1300,"quantity":1.0,"ref1":"","ref2":"","reportingDate":"2024-01-26","tax":1.87,"taxableAmount":8.13,"taxCalculated":1.87,"taxCode":"FR000000","taxCodeId":8550,"taxDate":"2024-01-26","taxIncluded":true,"details":[{"id":0,"transactionLineId":0,"transactionId":0,"country":"PL","region":"PL","exemptAmount":0.0,"jurisCode":"PL","jurisName":"POLAND","stateAssignedNo":"","jurisType":"CNT","jurisdictionType":"Country","nonTaxableAmount":0.0,"rate":0.230000,"tax":1.87,"taxableAmount":8.13,"taxType":"Output","taxSubTypeId":"O","taxName":"Standard+ Rate","taxAuthorityTypeId":45,"taxCalculated":1.87,"rateType":"Standard","rateTypeCode":"S","taxableUnits":8.1300,"nonTaxableUnits":0.0000,"exemptUnits":0.0000,"unitOfBasis":"PerCurrencyUnit","isNonPassThru":false,"isFee":false,"reportingTaxableUnits":8.13,"reportingNonTaxableUnits":0.0,"reportingExemptUnits":0.0,"reportingTax":1.87,"reportingTaxCalculated":1.87,"liabilityType":"Seller","chargedTo":"Buyer"}],"nonPassthroughDetails":[],"hsCode":"","costInsuranceFreight":0.0,"vatCode":"PLS-230D","vatNumberTypeId":0}],"addresses":[{"id":0,"transactionId":0,"boundaryLevel":"Zip5","line1":"Teczowa+ 7","line2":"","line3":"","city":"WROCLAW","region":"","postalCode":"53-601","country":"PL","taxRegionId":205102,"latitude":"","longitude":""},{"id":0,"transactionId":0,"boundaryLevel":"Zip5","line1":"Teczowa+ 7","line2":"","line3":"","city":"Wroclaw","region":"","postalCode":"53-601","country":"PL","taxRegionId":205102,"latitude":"","longitude":""}],"summary":[{"country":"PL","region":"PL","jurisType":"Country","jurisCode":"PL","jurisName":"POLAND","taxAuthorityType":45,"stateAssignedNo":"","taxType":"Output","taxSubType":"O","taxName":"Standard+ Rate","rateType":"Standard","taxable":32.52,"rate":0.230000,"tax":7.48,"taxCalculated":7.48,"nonTaxable":0.0,"exemption":0.0}]}'+ headers:+ Connection:+ - keep-alive+ Content-Type:+ - application/json; charset=utf-8+ Date:+ - Fri, 26 Jan 2024 09:07:19 GMT+ Location:+ - /api/v2/companies/7799660/transactions/0+ ServerDuration:+ - '00:00:00.0263520'+ Transfer-Encoding:+ - chunked+ X-Content-Type-Options:+ - nosniff+ api-supported-versions:+ - '2.0'+ cache-control:+ - private, no-cache, no-store+ referrer-policy:+ - same-origin+ strict-transport-security:+ - max-age=31536000; includeSubdomains+ x-avalara-uid:+ - 4d40efcd-df0e-4408-9ba4-cf8dfe9dfaf7+ x-correlation-id:+ - 4d40efcd-df0e-4408-9ba4-cf8dfe9dfaf7+ x-frame-options:+ - sameorigin+ x-permitted-cross-domain-policies:+ - none+ x-xss-protection:+ - 1; mode=block+ status:+ code: 201+ message: Created+version: 1diff --git a/saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_checkout_total_with_gift_promotion.yaml b/saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_checkout_total_with_gift_promotion.yamlnew file mode 100644index 0000000000..16fec520fd--- /dev/null+++ b/saleor/plugins/avatax/tests/cassettes/test_avatax/test_calculate_checkout_total_with_gift_promotion.yaml@@ -0,0 +1,78 @@+interactions:+- request:+ body: '{"createTransactionModel": {"companyCode": "DEFAULT", "type": "SalesOrder",+ "lines": [{"quantity": 3, "amount": "30.00", "taxCode": "PS081282", "taxIncluded":+ true, "itemCode": "123", "discounted": false, "description": "Test product",+ "ref1": "123"}, {"quantity": 1, "amount": "0.00", "taxCode": "O9999999", "taxIncluded":+ true, "itemCode": "0a57114cb7e44ee3ab76daa971a58d59", "discounted": false, "description":+ "Test product 2", "ref1": "0a57114cb7e44ee3ab76daa971a58d59"}, {"quantity":+ 1, "amount": "10.000", "taxCode": "FR000000", "taxIncluded": true, "itemCode":+ "Shipping", "discounted": false, "description": null}], "code": "39c9f72a-a495-49b4-9916-52af67b6e370",+ "date": "2024-01-26", "customerCode": 0, "discount": null, "addresses": {"shipFrom":+ {"line1": "Teczowa 7", "line2": "", "city": "Wroclaw", "region": "", "country":+ "PL", "postalCode": "53-601"}, "shipTo": {"line1": "O\u0142awska 10", "line2":+ "", "city": "WROC\u0141AW", "region": "", "country": "PL", "postalCode": "53-105"}},+ "commit": false, "currencyCode": "USD", "email": "[email protected]"}}'+ headers:+ Accept:+ - '*/*'+ Accept-Encoding:+ - gzip, deflate, br+ Authorization:+ - Basic Og==+ Connection:+ - keep-alive+ Content-Length:+ - '1069'+ User-Agent:+ - Saleor/3.19+ method: POST+ uri: https://sandbox-rest.avatax.com/api/v2/transactions/createoradjust+ response:+ body:+ string: '{"id":0,"code":"39c9f72a-a495-49b4-9916-52af67b6e370","companyId":7799660,"date":"2024-01-26","paymentDate":"2024-01-26","status":"Temporary","type":"SalesOrder","batchCode":"","currencyCode":"USD","exchangeRateCurrencyCode":"USD","customerUsageType":"","entityUseCode":"","customerVendorCode":"0","customerCode":"0","exemptNo":"","reconciled":false,"locationCode":"","reportingLocationCode":"","purchaseOrderNo":"","referenceCode":"","salespersonCode":"","totalAmount":32.52,"totalExempt":0.0,"totalDiscount":0.0,"totalTax":7.48,"totalTaxable":32.52,"totalTaxCalculated":7.48,"adjustmentReason":"NotAdjusted","locked":false,"version":1,"exchangeRateEffectiveDate":"2024-01-26","exchangeRate":1.0,"email":"[email protected]","modifiedDate":"2024-01-26T09:01:33.5547355Z","modifiedUserId":6479978,"taxDate":"2024-01-26","lines":[{"id":0,"transactionId":0,"lineNumber":"1","customerUsageType":"","entityUseCode":"","description":"Test+ product","discountAmount":0.0,"exemptAmount":0.0,"exemptCertId":0,"exemptNo":"","isItemTaxable":true,"itemCode":"123","lineAmount":24.3900,"quantity":3.0,"ref1":"123","ref2":"","reportingDate":"2024-01-26","tax":5.61,"taxableAmount":24.39,"taxCalculated":5.61,"taxCode":"PS081282","taxCodeId":38007,"taxDate":"2024-01-26","taxIncluded":true,"details":[{"id":0,"transactionLineId":0,"transactionId":0,"country":"PL","region":"PL","exemptAmount":0.0,"jurisCode":"PL","jurisName":"POLAND","stateAssignedNo":"","jurisType":"CNT","jurisdictionType":"Country","nonTaxableAmount":0.0,"rate":0.230000,"tax":5.61,"taxableAmount":24.39,"taxType":"Output","taxSubTypeId":"O","taxName":"Standard+ Rate","taxAuthorityTypeId":45,"taxCalculated":5.61,"rateType":"Standard","rateTypeCode":"S","taxableUnits":24.3900,"nonTaxableUnits":0.0000,"exemptUnits":0.0000,"unitOfBasis":"PerCurrencyUnit","isNonPassThru":false,"isFee":false,"reportingTaxableUnits":24.39,"reportingNonTaxableUnits":0.0,"reportingExemptUnits":0.0,"reportingTax":5.61,"reportingTaxCalculated":5.61,"avtUserBIN":"","liabilityType":"Seller","chargedTo":"Buyer"}],"nonPassthroughDetails":[],"hsCode":"","costInsuranceFreight":0.0,"vatCode":"PLSL230C","vatNumberTypeId":0},{"id":0,"transactionId":0,"lineNumber":"2","customerUsageType":"","entityUseCode":"","description":"Test+ product 2","discountAmount":0.0,"exemptAmount":0.0,"exemptCertId":0,"exemptNo":"","isItemTaxable":false,"itemCode":"0a57114cb7e44ee3ab76daa971a58d59","lineAmount":0.0,"quantity":1.0,"ref1":"0a57114cb7e44ee3ab76daa971a58d59","ref2":"","reportingDate":"2024-01-26","tax":0.0,"taxableAmount":0.0,"taxCalculated":0.0,"taxCode":"O9999999","taxCodeId":9111,"taxDate":"2024-01-26","taxIncluded":true,"details":[{"id":0,"transactionLineId":0,"transactionId":0,"country":"PL","region":"PL","exemptAmount":0.0,"jurisCode":"PL","jurisName":"POLAND","stateAssignedNo":"","jurisType":"CNT","jurisdictionType":"Country","nonTaxableAmount":0.0,"rate":0.230000,"tax":0.0,"taxableAmount":0.0,"taxType":"Output","taxSubTypeId":"O","taxName":"Standard+ Rate","taxAuthorityTypeId":45,"taxCalculated":0.0,"rateType":"Standard","rateTypeCode":"S","taxableUnits":0.0000,"nonTaxableUnits":0.0000,"exemptUnits":0.0000,"unitOfBasis":"PerCurrencyUnit","isNonPassThru":false,"isFee":false,"reportingTaxableUnits":0.0,"reportingNonTaxableUnits":0.0,"reportingExemptUnits":0.0,"reportingTax":0.0,"reportingTaxCalculated":0.0,"liabilityType":"Seller","chargedTo":"Buyer"}],"nonPassthroughDetails":[],"hsCode":"","costInsuranceFreight":0.0,"vatCode":"PLS-230C","vatNumberTypeId":0},{"id":0,"transactionId":0,"lineNumber":"3","customerUsageType":"","entityUseCode":"","discountAmount":0.0,"exemptAmount":0.0,"exemptCertId":0,"exemptNo":"","isItemTaxable":true,"itemCode":"Shipping","lineAmount":8.1300,"quantity":1.0,"ref1":"","ref2":"","reportingDate":"2024-01-26","tax":1.87,"taxableAmount":8.13,"taxCalculated":1.87,"taxCode":"FR000000","taxCodeId":8550,"taxDate":"2024-01-26","taxIncluded":true,"details":[{"id":0,"transactionLineId":0,"transactionId":0,"country":"PL","region":"PL","exemptAmount":0.0,"jurisCode":"PL","jurisName":"POLAND","stateAssignedNo":"","jurisType":"CNT","jurisdictionType":"Country","nonTaxableAmount":0.0,"rate":0.230000,"tax":1.87,"taxableAmount":8.13,"taxType":"Output","taxSubTypeId":"O","taxName":"Standard+ Rate","taxAuthorityTypeId":45,"taxCalculated":1.87,"rateType":"Standard","rateTypeCode":"S","taxableUnits":8.1300,"nonTaxableUnits":0.0000,"exemptUnits":0.0000,"unitOfBasis":"PerCurrencyUnit","isNonPassThru":false,"isFee":false,"reportingTaxableUnits":8.13,"reportingNonTaxableUnits":0.0,"reportingExemptUnits":0.0,"reportingTax":1.87,"reportingTaxCalculated":1.87,"liabilityType":"Seller","chargedTo":"Buyer"}],"nonPassthroughDetails":[],"hsCode":"","costInsuranceFreight":0.0,"vatCode":"PLS-230D","vatNumberTypeId":0}],"addresses":[{"id":0,"transactionId":0,"boundaryLevel":"Zip5","line1":"Olawska+ 10","line2":"","line3":"","city":"WROCLAW","region":"","postalCode":"53-105","country":"PL","taxRegionId":205102,"latitude":"","longitude":""},{"id":0,"transactionId":0,"boundaryLevel":"Zip5","line1":"Teczowa+ 7","line2":"","line3":"","city":"Wroclaw","region":"","postalCode":"53-601","country":"PL","taxRegionId":205102,"latitude":"","longitude":""}],"summary":[{"country":"PL","region":"PL","jurisType":"Country","jurisCode":"PL","jurisName":"POLAND","taxAuthorityType":45,"stateAssignedNo":"","taxType":"Output","taxSubType":"O","taxName":"Standard+ Rate","rateType":"Standard","taxable":32.52,"rate":0.230000,"tax":7.48,"taxCalculated":7.48,"nonTaxable":0.0,"exemption":0.0}]}'+ headers:+ Connection:+ - keep-alive+ Content-Type:+ - application/json; charset=utf-8+ Date:+ - Fri, 26 Jan 2024 09:01:33 GMT+ Location:+ - /api/v2/companies/7799660/transactions/0+ ServerDuration:+ - '00:00:00.0233063'+ Transfer-Encoding:+ - chunked+ X-Content-Type-Options:+ - nosniff+ api-supported-versions:+ - '2.0'+ cache-control:+ - private, no-cache, no-store+ referrer-policy:+ - same-origin+ strict-transport-security:+ - max-age=31536000; includeSubdomains+ x-avalara-uid:+ - 79160d1e-cff4-489e-bc9c-66be27d23c54+ x-correlation-id:+ - 79160d1e-cff4-489e-bc9c-66be27d23c54+ x-frame-options:+ - sameorigin+ x-permitted-cross-domain-policies:+ - none+ x-xss-protection:+ - 1; mode=block+ status:+ code: 201+ message: Created+version: 1diff --git a/saleor/plugins/avatax/tests/test_avatax.py b/saleor/plugins/avatax/tests/test_avatax.pyindex 42de040035..7a3292f407 100644--- a/saleor/plugins/avatax/tests/test_avatax.py+++ b/saleor/plugins/avatax/tests/test_avatax.py@@ -294,6 +294,52 @@ def test_calculate_checkout_line_total_with_order_promotion()+@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])+def test_calculate_checkout_line_total_gift_promotion_line(+ checkout_with_item_and_gift_promotion,+ ship_to_pl_address,+ shipping_zone,+ plugin_configuration,+):+ # given+ checkout = checkout_with_item_and_gift_promotion+ plugin_configuration()+ manager = get_plugins_manager(allow_replica=False)++ checkout.shipping_address = ship_to_pl_address+ checkout.shipping_method = shipping_zone.shipping_methods.get()+ checkout.save()++ tax_configuration = checkout.channel.tax_configuration+ tax_configuration.charge_taxes = True+ tax_configuration.prices_entered_with_tax = True+ tax_configuration.save(update_fields=["charge_taxes", "prices_entered_with_tax"])+ tax_configuration.country_exceptions.all().delete()++ line = checkout.lines.get(is_gift=True)+ product = line.variant.product+ product.metadata = {}+ product.save()+ product.product_type.save()++ lines, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, manager)+ gift_line_info = [line_info for line_info in lines if line_info.line.is_gift][0]++ # when+ total = manager.calculate_checkout_line_total(+ checkout_info,+ lines,+ gift_line_info,+ checkout.shipping_address,+ )++ # then+ total = quantize_price(total, total.currency)+ assert total == zero_taxed_money(total.currency)++@pytest.mark.vcr@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])def test_calculate_checkout_line_total_with_voucher(@@ -1415,6 +1461,68 @@ def test_calculate_checkout_total_with_order_promotion()+@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])+def test_calculate_checkout_total_with_gift_promotion(+ checkout_with_item_and_gift_promotion,+ shipping_zone,+ ship_to_pl_address,+ monkeypatch,+ plugin_configuration,+):+ # given+ checkout = checkout_with_item_and_gift_promotion++ plugin_configuration()+ monkeypatch.setattr(+ "saleor.plugins.avatax.plugin.get_cached_tax_codes_or_fetch",+ lambda _: {"PS081282": "desc", TAX_CODE_NON_TAXABLE_PRODUCT: "desc"},+ )+ monkeypatch.setattr(+ "saleor.plugins.avatax.plugin.AvataxPlugin._skip_plugin", lambda *_: False+ )+ manager = get_plugins_manager(allow_replica=False)+ checkout.shipping_address = ship_to_pl_address+ checkout.save()++ tax_configuration = checkout.channel.tax_configuration+ tax_configuration.prices_entered_with_tax = True+ tax_configuration.charge_taxes = True+ tax_configuration.save(update_fields=["charge_taxes", "prices_entered_with_tax"])+ tax_configuration.country_exceptions.all().delete()++ shipping_method = shipping_zone.shipping_methods.get()+ checkout.shipping_method = shipping_method+ checkout.save(update_fields=["shipping_method"])++ line = checkout.lines.get(is_gift=False)+ product = line.variant.product++ manager.assign_tax_code_to_object_meta(product.tax_class, "PS081282")+ product.save()+ product.tax_class.save()++ checkout_info = fetch_checkout_info(checkout, [], manager)+ lines, _ = fetch_checkout_lines(checkout)++ # when+ total = manager.calculate_checkout_total(checkout_info, lines, ship_to_pl_address)++ # then+ total = quantize_price(total, total.currency)+ line_info = [line_info for line_info in lines if not line_info.line.is_gift][0]+ unit_price = line_info.variant.get_price(line_info.channel_listing)+ subtotal_price_amount = (unit_price * line.quantity).amount+ shipping_price = shipping_method.channel_listings.get(+ channel=checkout.channel+ ).price+ total_price_amount = subtotal_price_amount + shipping_price.amount+ assert total == TaxedMoney(+ net=Money(round(total_price_amount / Decimal("1.23"), 2), checkout.currency),+ gross=Money(total_price_amount, "USD"),+ )++@pytest.mark.vcr@pytest.mark.parametrize(("expected_net", "expected_gross", "voucher_amount", "prices_entered_with_tax"),@@ -2931,7 +3039,7 @@ def test_calculate_checkout_line_unit_price_order_promotion_charge_taxes(@pytest.mark.vcr@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])-def test_calculate_checkout_line_unit_price_checkout_promotion_do_not_charge_taxes(+def test_calculate_checkout_line_unit_price_order_promotion_do_not_charge_taxes(checkout_with_item_and_order_discount,shipping_zone,address,@@ -2981,6 +3089,49 @@ def test_calculate_checkout_line_unit_price_checkout_promotion_do_not_charge_taxassert line_price == expected_line_price+@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])+def test_calculate_checkout_line_unit_price_gift_promotion_line(+ checkout_with_item_and_gift_promotion,+ shipping_zone,+ address,+ plugin_configuration,+):+ # given+ plugin_configuration()+ checkout = checkout_with_item_and_gift_promotion++ lines, _ = fetch_checkout_lines(checkout)+ gift_line_info = [line_info for line_info in lines if line_info.line.is_gift][0]++ manager = get_plugins_manager(allow_replica=False)++ method = shipping_zone.shipping_methods.get()+ checkout.shipping_address = address+ checkout.shipping_method_name = method.name+ checkout.shipping_method = method+ checkout.save()++ tax_configuration = checkout.channel.tax_configuration+ tax_configuration.prices_entered_with_tax = True+ tax_configuration.charge_taxes = True+ tax_configuration.save(update_fields=["charge_taxes", "prices_entered_with_tax"])+ tax_configuration.country_exceptions.all().delete()++ checkout_info = fetch_checkout_info(checkout, lines, manager)++ # when+ line_price = manager.calculate_checkout_line_unit_price(+ checkout_info,+ lines,+ gift_line_info,+ checkout.shipping_address,+ )++ # then+ assert line_price == zero_taxed_money(checkout.currency)++@pytest.mark.vcr@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])def test_calculate_checkout_line_unit_price_with_voucher(diff --git a/saleor/settings.py b/saleor/settings.pyindex 5024f3f2d0..f11abd02e3 100644--- a/saleor/settings.py+++ b/saleor/settings.py@@ -892,3 +892,6 @@ WEBHOOK_SYNC_TIMEOUT = (REQUESTS_CONN_EST_TIMEOUT, 18)# The max number of rules with order_predicate definedORDER_RULES_LIMIT = os.environ.get("ORDER_RULES_LIMIT", 100)++# The max number of gits assigned to promotion rule+GIFTS_LIMIT_PER_RULE = os.environ.get("GIFTS_LIMIT_PER_RULE", 500)diff --git a/saleor/tax/tests/test_checkout_calculations.py b/saleor/tax/tests/test_checkout_calculations.pyindex 8d479c3295..9b9d07239a 100644--- a/saleor/tax/tests/test_checkout_calculations.py+++ b/saleor/tax/tests/test_checkout_calculations.py@@ -472,6 +472,48 @@ def test_calculate_checkout_subtotal_with_order_promotion()+def test_calculate_checkout_subtotal_with_gift_promotion(+ checkout_with_item_and_gift_promotion,+ address,+ shipping_zone,+ stock,+):+ # given+ checkout = checkout_with_item_and_gift_promotion+ prices_entered_with_tax = True+ _enable_flat_rates(checkout, prices_entered_with_tax)++ checkout.shipping_address = address+ checkout.shipping_method = shipping_zone.shipping_methods.get()+ checkout.save()++ manager = get_plugins_manager(allow_replica=False)+ checkout_info = fetch_checkout_info(checkout, [], manager)+ lines, _ = fetch_checkout_lines(checkout)++ # when+ update_checkout_prices_with_flat_rates(+ checkout,+ checkout_info,+ lines,+ prices_entered_with_tax,+ address,+ )++ # then+ subtotal = Decimal("0.00")+ for line_info in lines:+ if line_info.line.is_gift:+ continue+ subtotal += (+ line_info.channel_listing.discounted_price_amount * line_info.line.quantity+ )+ assert checkout.subtotal == TaxedMoney(+ net=Money(round(subtotal / Decimal("1.23"), 2), "USD"),+ gross=Money(subtotal, "USD"),+ )++def test_calculate_checkout_line_total(checkout_with_item, shipping_zone, address):manager = get_plugins_manager(allow_replica=False)checkout = checkout_with_item@@ -859,6 +901,44 @@ def test_calculate_checkout_line_total_discount_from_order_promotion()+def test_calculate_checkout_line_total_discount_for_gift_line(+ checkout_with_item_and_gift_promotion, shipping_zone, address+):+ # given+ manager = get_plugins_manager(allow_replica=False)+ checkout = checkout_with_item_and_gift_promotion++ rate = Decimal(23)+ prices_entered_with_tax = True+ _enable_flat_rates(checkout, prices_entered_with_tax)++ line = checkout.lines.get(is_gift=True)+ assert line.quantity == 1++ method = shipping_zone.shipping_methods.get()+ checkout.shipping_address = address+ checkout.shipping_method_name = method.name+ checkout.shipping_method = method+ checkout.save()++ variant = line.variant+ product = variant.product+ product.tax_class.country_rates.update_or_create(country=address.country, rate=rate)++ lines, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, manager)+ checkout_line_info = [line_info for line_info in lines if line_info.line.is_gift][0]+ create_discount_objects_for_order_promotions(checkout_info, lines)++ # when+ line_price = calculate_checkout_line_total(+ checkout_info, lines, checkout_line_info, rate, prices_entered_with_tax+ )++ # then+ assert line_price == zero_taxed_money(checkout.currency)++def test_calculate_checkout_shipping(checkout_with_item,shipping_zone,diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex acdcc7515b..a9fd83bed5 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -440,6 +440,36 @@ def checkout_with_item_and_order_discount(return checkout_with_item+def checkout_with_item_and_gift_promotion(checkout_with_item, gift_promotion_rule):+ channel = checkout_with_item.channel+ variants = gift_promotion_rule.gifts.all()+ variant_listings = ProductVariantChannelListing.objects.filter(variant__in=variants)+ top_price, variant_id = max(+ variant_listings.values_list("discounted_price_amount", "variant")+ )++ line = CheckoutLine.objects.create(+ checkout=checkout_with_item,+ quantity=1,+ variant_id=variant_id,+ is_gift=True,+ currency="USD",+ )++ CheckoutLineDiscount.objects.create(+ line=line,+ promotion_rule=gift_promotion_rule,+ type=DiscountType.ORDER_PROMOTION,+ value_type=RewardValueType.FIXED,+ value=top_price,+ amount_value=top_price,+ currency=channel.currency_code,+ )++ return checkout_with_item++@pytest.fixturedef checkout_with_item_and_transaction_item(checkout_with_item):TransactionItem.objects.create(@@ -5809,6 +5839,21 @@ def order_promotion_rule(channel_USD, order_promotion_without_rules):return rule+def gift_promotion_rule(channel_USD, order_promotion_without_rules, product_list):+ rule = PromotionRule.objects.create(+ name="Order promotion rule",+ promotion=order_promotion_without_rules,+ order_predicate={+ "discountedObjectPredicate": {"baseSubtotalPrice": {"range": {"gte": 20}}}+ },+ reward_type=RewardType.GIFT,+ )+ rule.channels.add(channel_USD)+ rule.gifts.set([product.variants.first() for product in product_list[:2]])+ return rule++@pytest.fixturedef rule_info(promotion_rule,diff --git a/saleor/webhook/tests/test_webhook_payloads.py b/saleor/webhook/tests/test_webhook_payloads.pyindex c9747df0ff..e45613eacf 100644--- a/saleor/webhook/tests/test_webhook_payloads.py+++ b/saleor/webhook/tests/test_webhook_payloads.py@@ -18,10 +18,11 @@ from prices import Moneyfrom ... import __version__from ...checkout import base_calculationsfrom ...checkout.fetch import fetch_checkout_info, fetch_checkout_lines+from ...checkout.models import CheckoutLinefrom ...core.prices import quantize_pricefrom ...core.utils.json_serializer import CustomJsonEncoder-from ...discount import DiscountType, DiscountValueType-from ...discount.models import CheckoutDiscount+from ...discount import DiscountType, DiscountValueType, RewardValueType+from ...discount.models import CheckoutDiscount, CheckoutLineDiscountfrom ...graphql.utils import get_user_or_app_from_contextfrom ...order import FulfillmentLineData, OrderOriginfrom ...order.actions import fulfill_order_lines@@ -31,7 +32,7 @@ from ...payment import TransactionAction, TransactionEventTypefrom ...payment.interface import RefundData, TransactionActionData, TransactionDatafrom ...payment.models import TransactionItemfrom ...plugins.manager import get_plugins_manager-from ...product.models import ProductVariant+from ...product.models import ProductVariant, ProductVariantChannelListingfrom ...shipping.interface import ShippingMethodDatafrom ...warehouse import WarehouseClickAndCollectOptionfrom ..payloads import (@@ -1948,6 +1949,91 @@ def test_generate_checkout_payload_for_tax_calculation_order_discount()+@patch("saleor.webhook.payloads.serialize_checkout_lines_for_tax_calculation")[email protected]("prices_entered_with_tax", [True, False])+def test_generate_checkout_payload_for_tax_calculation_gift_promotion(+ mocked_serialize_checkout_lines_for_tax_calculation,+ mocked_fetch_checkout,+ checkout_with_prices,+ prices_entered_with_tax,+ gift_promotion_rule,+):+ checkout = checkout_with_prices+ currency = checkout.currency++ variants = gift_promotion_rule.gifts.all()+ variant_listings = ProductVariantChannelListing.objects.filter(variant__in=variants)+ top_price, variant_id = max(+ variant_listings.values_list("discounted_price_amount", "variant")+ )++ line = CheckoutLine.objects.create(+ checkout=checkout,+ quantity=1,+ variant_id=variant_id,+ is_gift=True,+ currency="USD",+ )++ CheckoutLineDiscount.objects.create(+ line=line,+ promotion_rule=gift_promotion_rule,+ type=DiscountType.ORDER_PROMOTION,+ value_type=RewardValueType.FIXED,+ value=top_price,+ amount_value=top_price,+ currency=checkout.channel.currency_code,+ )++ tax_configuration = checkout.channel.tax_configuration+ tax_configuration.prices_entered_with_tax = prices_entered_with_tax+ tax_configuration.save(update_fields=["prices_entered_with_tax"])+ tax_configuration.country_exceptions.all().delete()++ mocked_serialized_checkout_lines = {"data": "checkout_lines_data"}+ mocked_serialize_checkout_lines_for_tax_calculation.return_value = (+ mocked_serialized_checkout_lines+ )++ # when+ lines, _ = fetch_checkout_lines(checkout_with_prices)+ manager = get_plugins_manager(allow_replica=False)+ checkout_info = fetch_checkout_info(checkout_with_prices, lines, manager)+ payload = json.loads(+ generate_checkout_payload_for_tax_calculation(checkout_info, lines)+ )[0]++ # then+ subtotal_price = Money(0, currency)+ for line_info in lines:+ if line_info.line.is_gift:+ continue+ variant = line_info.variant+ variant_listing = line_info.channel_listing+ unit_price = variant.get_price(variant_listing)+ subtotal_price += unit_price * line_info.line.quantity+ shipping_price = quantize_price(+ checkout.shipping_method.channel_listings.get(+ channel_id=checkout.channel_id+ ).price.amount,+ currency,+ )+ total_price_amount = subtotal_price.amount + shipping_price+ assert payload["discounts"] == []+ assert payload["total_amount"] == str(+ quantize_price(+ total_price_amount,+ currency,+ )+ )++ mocked_fetch_checkout.assert_not_called()+ mocked_serialize_checkout_lines_for_tax_calculation.assert_called_once_with(+ checkout_info,+ lines,+ )++@patch("saleor.webhook.payloads.serialize_checkout_lines_for_tax_calculation")def test_generate_checkout_payload_for_tax_calculation_digital_checkout(mocked_serialize_checkout_lines_for_tax_calculation,diff --git a/saleor/webhook/tests/test_webhook_serializers.py b/saleor/webhook/tests/test_webhook_serializers.pyindex a6661308a3..372ca739d2 100644--- a/saleor/webhook/tests/test_webhook_serializers.py+++ b/saleor/webhook/tests/test_webhook_serializers.py@@ -1,3 +1,4 @@+from decimal import Decimalfrom unittest.mock import ANY, sentinelimport graphene@@ -435,7 +436,7 @@ def test_serialize_checkout_lines_for_tax_calculation_with_order_discount(total_price_amount = (unit_price * line.quantity).amountline_data = checkout_lines_data[0]- # the line data shouldn't include order promotin discount+ # the line data shouldn't include order promotion discountassert line_data == {"id": graphene.Node.to_global_id("CheckoutLine", line.pk),"sku": variant.sku,@@ -450,3 +451,76 @@ def test_serialize_checkout_lines_for_tax_calculation_with_order_discount("unit_amount": unit_price.amount,"total_amount": total_price_amount,}+++def test_serialize_checkout_lines_for_tax_calculation_with_gift_promotion(+ checkout_with_item_and_gift_promotion, product+):+ # given+ checkout = checkout_with_item_and_gift_promotion++ lines, _ = fetch_checkout_lines(checkout)+ manager = get_plugins_manager(allow_replica=False)+ checkout_info = fetch_checkout_info(checkout, lines, manager)++ tax_configuration = checkout_info.tax_configuration+ tax_configuration.country_exceptions.all().delete()++ # when+ checkout_lines_data = serialize_checkout_lines_for_tax_calculation(+ checkout_info, lines+ )++ # then+ line_info = [line_info for line_info in lines if not line_info.line.is_gift][0]+ line = line_info.line+ line_id = graphene.Node.to_global_id("CheckoutLine", line.pk)+ variant = line.variant+ product = variant.product++ unit_price = variant.get_price(+ channel_listing=line_info.channel_listing,+ )+ total_price_amount = (unit_price * line.quantity).amount++ line_data = [+ line_data for line_data in checkout_lines_data if line_data["id"] == line_id+ ][0]+ assert line_data == {+ "id": line_id,+ "sku": variant.sku,+ "quantity": line.quantity,+ "charge_taxes": tax_configuration.charge_taxes,+ "full_name": variant.display_product(),+ "product_name": product.name,+ "variant_name": variant.name,+ "variant_id": graphene.Node.to_global_id("ProductVariant", variant.pk),+ "product_metadata": product.metadata,+ "product_type_metadata": product.product_type.metadata,+ "unit_amount": unit_price.amount,+ "total_amount": total_price_amount,+ }+ gift_info = [line_info for line_info in lines if line_info.line.is_gift][0]+ gift_line = gift_info.line+ gift_line_id = graphene.Node.to_global_id("CheckoutLine", gift_info.line.pk)+ gift_line_data = [+ line_data+ for line_data in checkout_lines_data+ if line_data["id"] == gift_line_id+ ][0]+ assert gift_line_data == {+ "id": gift_line_id,+ "sku": gift_line.variant.sku,+ "quantity": 1,+ "charge_taxes": tax_configuration.charge_taxes,+ "full_name": gift_line.variant.display_product(),+ "product_name": gift_line.variant.product.name,+ "variant_name": gift_line.variant.name,+ "variant_id": graphene.Node.to_global_id(+ "ProductVariant", gift_line.variant.pk+ ),+ "product_metadata": gift_line.variant.product.metadata,+ "product_type_metadata": gift_line.variant.product.product_type.metadata,+ "unit_amount": Decimal("0.00"),+ "total_amount": Decimal("0.00"),+ }