Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Feature/gift cards post mvp (#7977)
Iga Karbowiakf5a45de4a22f
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.pyindex d86f5863ab..c89386e373 100644--- a/saleor/checkout/complete_checkout.py+++ b/saleor/checkout/complete_checkout.py@@ -526,11 +526,6 @@ def _create_order(order.search_document = prepare_order_search_document_value(order)order.save()- if site_settings.automatically_fulfill_non_shippable_gift_card:- fulfill_non_shippable_gift_cards(- order, order_lines, site_settings, user, app, manager- )-order_info = OrderInfo(order=order,customer_email=order_data["user_email"],@@ -550,6 +545,11 @@ def _create_order(lambda: send_order_confirmation(order_info, checkout.redirect_url, manager))+ if site_settings.automatically_fulfill_non_shippable_gift_card:+ fulfill_non_shippable_gift_cards(+ order, order_lines, site_settings, user, app, manager+ )+return orderdiff --git a/saleor/checkout/tests/test_checkout_complete.py b/saleor/checkout/tests/test_checkout_complete.pyindex 5f25c584de..34e388d0ec 100644--- a/saleor/checkout/tests/test_checkout_complete.py+++ b/saleor/checkout/tests/test_checkout_complete.py@@ -841,6 +841,7 @@ def test_create_order_gift_card_bought(manager=manager,)+ flush_post_commit_hooks()assert order.total.gross == total_grossflush_post_commit_hooks()gift_card = GiftCard.objects.get()diff --git a/saleor/core/management/commands/populatedb.py b/saleor/core/management/commands/populatedb.pyindex 5abcc39393..de28de50ad 100644--- a/saleor/core/management/commands/populatedb.py+++ b/saleor/core/management/commands/populatedb.py@@ -11,7 +11,7 @@ from ...utils.random_data import (add_address_to_admin,create_channels,create_checkout_with_preorders,- create_gift_card,+ create_gift_cards,create_menus,create_orders,create_page_type,@@ -102,14 +102,14 @@ class Command(BaseCommand):self.stdout.write(msg)for msg in create_vouchers():self.stdout.write(msg)- for msg in create_gift_card():- self.stdout.write(msg)for msg in create_users(user_password, 20):self.stdout.write(msg)for msg in create_orders(20):self.stdout.write(msg)for msg in create_preorder_orders(1):self.stdout.write(msg)+ for msg in create_gift_cards():+ self.stdout.write(msg)for msg in create_menus():self.stdout.write(msg)for msg in create_checkout_with_preorders():diff --git a/saleor/core/notify_events.py b/saleor/core/notify_events.pyindex a075327016..2abfc00047 100644--- a/saleor/core/notify_events.py+++ b/saleor/core/notify_events.py@@ -37,13 +37,13 @@ class UserNotifyEvent:class AdminNotifyEvent:ACCOUNT_SET_STAFF_PASSWORD = "account_set_staff_password"ACCOUNT_STAFF_RESET_PASSWORD = "account_staff_reset_password"- CSV_PRODUCT_EXPORT_SUCCESS = "csv_export_products_success"+ CSV_EXPORT_SUCCESS = "csv_export_success"CSV_EXPORT_FAILED = "csv_export_failed"STAFF_ORDER_CONFIRMATION = "staff_order_confirmation"CHOICES = [ACCOUNT_SET_STAFF_PASSWORD,- CSV_PRODUCT_EXPORT_SUCCESS,+ CSV_EXPORT_SUCCESS,CSV_EXPORT_FAILED,STAFF_ORDER_CONFIRMATION,ACCOUNT_STAFF_RESET_PASSWORD,diff --git a/saleor/core/tests/test_core.py b/saleor/core/tests/test_core.pyindex af7dde0274..7f145d9c4b 100644--- a/saleor/core/tests/test_core.py+++ b/saleor/core/tests/test_core.py@@ -15,7 +15,7 @@ from ...account.models import Address, Userfrom ...account.utils import create_superuserfrom ...channel.models import Channelfrom ...discount.models import Sale, SaleChannelListing, Voucher, VoucherChannelListing-from ...giftcard.models import GiftCard+from ...giftcard.models import GiftCard, GiftCardEventfrom ...order.models import Order, OrderLinefrom ...product import ProductTypeKindfrom ...product.models import ProductMedia, ProductType@@ -186,11 +186,20 @@ def test_create_vouchers(db):assert VoucherChannelListing.objects.all().count() == voucher_count * channel_count-def test_create_gift_card(db):+def test_create_gift_card(+ db, product, shippable_gift_card_product, customer_user, staff_user, order+):+ product = shippable_gift_card_product+ product.name = "Gift card"+ product.save(update_fields=["name"])++ amount = 5assert GiftCard.objects.count() == 0- for _ in random_data.create_gift_card():+ assert GiftCardEvent.objects.count() == 0+ for _ in random_data.create_gift_cards(amount):pass- assert GiftCard.objects.count() == 1+ assert GiftCard.objects.count() == amount * 2+ assert GiftCardEvent.objects.count() == amount * 2@override_settings(VERSATILEIMAGEFIELD_SETTINGS={"create_images_on_demand": False})diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.pyindex 1772ca21e1..a78434b370 100644--- a/saleor/core/utils/random_data.py+++ b/saleor/core/utils/random_data.py@@ -56,7 +56,8 @@ from ...core.weight import zero_weightfrom ...discount import DiscountValueType, VoucherTypefrom ...discount.models import Sale, SaleChannelListing, Voucher, VoucherChannelListingfrom ...discount.utils import fetch_discounts-from ...giftcard.models import GiftCard+from ...giftcard import events as gift_card_events+from ...giftcard.models import GiftCard, GiftCardTagfrom ...menu.models import Menufrom ...order import OrderStatusfrom ...order.models import Fulfillment, Order, OrderLine@@ -164,10 +165,15 @@ IMAGES_MAPPING = {122: ["saleor-digital-03_4.png"],123: ["saleor-digital-03_5.png"],124: ["saleor-digital-03_6.png"],+ 125: ["saleordemoproduct_giftcard_01.png", "saleordemoproduct_giftcard_02.png"],}-CATEGORY_IMAGES = {7: "accessories.jpg", 8: "groceries.jpg", 9: "apparel.jpg"}+CATEGORY_IMAGES = {+ 7: "accessories.jpg",+ 8: "groceries.jpg",+ 9: "apparel.jpg",+}COLLECTION_IMAGES = {1: "summer.jpg", 2: "clothing.jpg", 3: "clothing.jpg"}@@ -263,6 +269,8 @@ def create_products(products_data, placeholder_dir, create_images):defaults["weight"] = get_weight(defaults["weight"])defaults["category_id"] = defaults.pop("category")defaults["product_type_id"] = defaults.pop("product_type")+ if default_variant := defaults.pop("default_variant", None):+ defaults["default_variant_id"] = default_variantproduct, _ = Product.objects.update_or_create(pk=pk, defaults=defaults)@@ -1424,22 +1432,42 @@ def create_vouchers():yield "Value voucher already exists"-def create_gift_card():- user = random.choice(- [User.objects.filter(is_superuser=False).order_by("?").first()]- )- gift_card, created = GiftCard.objects.get_or_create(- code="Gift_card_10",- defaults={- "created_by": user,- "initial_balance": Money(10, DEFAULT_CURRENCY),- "current_balance": Money(10, DEFAULT_CURRENCY),- },- )- if created:- yield "Gift card #%d" % gift_card.id- else:- yield "Gift card already exists"+def create_gift_cards(how_many=5):+ product_pk = Product.objects.get(name="Gift card").pk+ tag, _ = GiftCardTag.objects.get_or_create(name="issued-gift-cards")+ for i in range(how_many):+ staff_user = User.objects.filter(is_staff=True).order_by("?").first()+ gift_card, created = GiftCard.objects.get_or_create(+ code=f"Gift_card_{i+1}",+ defaults={+ "created_by": staff_user,+ "initial_balance": Money(50, DEFAULT_CURRENCY),+ "current_balance": Money(50, DEFAULT_CURRENCY),+ },+ )+ gift_card.tags.add(tag)+ gift_card_events.gift_card_issued_event(gift_card, staff_user, None)+ if created:+ yield "Gift card #%d" % gift_card.id+ else:+ yield "Gift card already exists"++ user = User.objects.filter(is_superuser=False).order_by("?").first()+ gift_card, created = GiftCard.objects.get_or_create(+ code=f"Gift_card_1{i+1}",+ defaults={+ "created_by": user,+ "product_id": product_pk,+ "initial_balance": Money(20, DEFAULT_CURRENCY),+ "current_balance": Money(20, DEFAULT_CURRENCY),+ },+ )+ order_id = Order.objects.order_by("?").first().id+ gift_card_events.gift_cards_bought_event([gift_card], order_id, user, None)+ if created:+ yield "Gift card #%d" % gift_card.id+ else:+ yield "Gift card already exists"def add_address_to_admin(email):diff --git a/saleor/csv/notifications.py b/saleor/csv/notifications.pyindex 304638fa9c..2b5c6eebb9 100644--- a/saleor/csv/notifications.py+++ b/saleor/csv/notifications.py@@ -25,24 +25,26 @@ def get_default_export_payload(export_file: "ExportFile") -> dict:}-def send_export_download_link_notification(export_file: "ExportFile"):+def send_export_download_link_notification(export_file: "ExportFile", data_type: str):"""Call PluginManager.notify to trigger the notification for success export."""payload = {"export": get_default_export_payload(export_file),"csv_link": build_absolute_uri(export_file.content_file.url),"recipient_email": export_file.user.email if export_file.user else None,+ "data_type": data_type,**get_site_context(),}manager = get_plugins_manager()- manager.notify(NotifyEventType.CSV_PRODUCT_EXPORT_SUCCESS, payload)+ manager.notify(NotifyEventType.CSV_EXPORT_SUCCESS, payload)-def send_export_failed_info(export_file: "ExportFile"):+def send_export_failed_info(export_file: "ExportFile", data_type: str):"""Call PluginManager.notify to trigger the notification for failed export."""payload = {"export": get_default_export_payload(export_file),"recipient_email": export_file.user.email if export_file.user else None,+ "data_type": data_type,**get_site_context(),}manager = get_plugins_manager()diff --git a/saleor/csv/tasks.py b/saleor/csv/tasks.pyindex 0597ec9745..117d4d6a13 100644--- a/saleor/csv/tasks.py+++ b/saleor/csv/tasks.py@@ -5,7 +5,7 @@ from ..core import JobStatusfrom . import eventsfrom .models import ExportFilefrom .notifications import send_export_failed_info-from .utils.export import export_products+from .utils.export import export_gift_cards, export_productsdef on_task_failure(self, exc, task_id, args, kwargs, einfo):@@ -44,7 +44,18 @@ def export_products_task(scope: Dict[str, Union[str, dict]],export_info: Dict[str, list],file_type: str,- delimiter: str = ";",+ delimiter: str = ",",):export_file = ExportFile.objects.get(pk=export_file_id)export_products(export_file, scope, export_info, file_type, delimiter)++[email protected](on_success=on_task_success, on_failure=on_task_failure)+def export_gift_cards_task(+ export_file_id: int,+ scope: Dict[str, Union[str, dict]],+ file_type: str,+ delimiter: str = ",",+):+ export_file = ExportFile.objects.get(pk=export_file_id)+ export_gift_cards(export_file, scope, file_type, delimiter)diff --git a/saleor/csv/tests/export/products_data/test_prepare_headers.py b/saleor/csv/tests/export/products_data/test_prepare_headers.pyindex 9750ad8f1d..72f391e0ab 100644--- a/saleor/csv/tests/export/products_data/test_prepare_headers.py+++ b/saleor/csv/tests/export/products_data/test_prepare_headers.py@@ -4,8 +4,8 @@ from .....graphql.csv.enums import ProductFieldEnumfrom ....utils.product_headers import (get_attributes_headers,get_channels_headers,- get_export_fields_and_headers_info,get_product_export_fields_and_headers,+ get_product_export_fields_and_headers_info,get_warehouses_headers,)@@ -144,7 +144,7 @@ def test_get_channels_headers_lack_of_channel_ids():assert channel_headers == []-def test_get_export_fields_and_headers_info(+def test_get_product_export_fields_and_headers_info(warehouses, product_with_multiple_values_attributes, channel_PLN, channel_USD):# given@@ -168,9 +168,11 @@ def test_get_export_fields_and_headers_info(]# when- export_fields, file_headers, data_headers = get_export_fields_and_headers_info(- export_info- )+ (+ export_fields,+ file_headers,+ data_headers,+ ) = get_product_export_fields_and_headers_info(export_info)# thenexpected_fields = [diff --git a/saleor/csv/tests/export/test_export.py b/saleor/csv/tests/export/test_export.pyindex b53fb75af2..d9424bc6a0 100644--- a/saleor/csv/tests/export/test_export.py+++ b/saleor/csv/tests/export/test_export.py@@ -12,16 +12,20 @@ from django.core.files import Filefrom freezegun import freeze_timefrom ....core import JobStatus+from ....giftcard.models import GiftCardfrom ....graphql.csv.enums import ProductFieldEnum+from ....graphql.product.filters import ProductFilterfrom ....product.models import Product, ProductChannelListingfrom ... import FileTypesfrom ...utils.export import (append_to_file,create_file_with_headers,+ export_gift_cards,+ export_gift_cards_in_batches,export_products,export_products_in_batches,get_filename,- get_product_queryset,+ get_queryset,parse_input,save_csv_file_in_export_file,)@@ -66,7 +70,7 @@ def test_export_products(# thencreate_file_with_headers_mock.assert_called_once_with(- ["id", "name", "variant id", "variant sku"], ";", file_type+ ["id", "name", "variant id", "variant sku"], ",", file_type)assert export_products_in_batches_mock.call_count == 1args, kwargs = export_products_in_batches_mock.call_args@@ -77,11 +81,11 @@ def test_export_products(export_info,{"id", "name", "variants__id", "variants__sku"},["id", "name", "variants__id", "variants__sku"],- ";",+ ",",mock_file,file_type,)- send_email_mock.assert_called_once_with(user_export_file)+ send_email_mock.assert_called_once_with(user_export_file, "products")save_file_mock.assert_called_once_with(user_export_file, mock_file, ANY)@@ -112,7 +116,7 @@ def test_export_products_ids(export_products(user_export_file, {"ids": pks}, export_info, file_type)# then- create_file_with_headers_mock.assert_called_once_with(["id"], ";", file_type)+ create_file_with_headers_mock.assert_called_once_with(["id"], ",", file_type)assert export_products_in_batches_mock.call_count == 1args, kwargs = export_products_in_batches_mock.call_args@@ -124,11 +128,11 @@ def test_export_products_ids(export_info,{"id"},["id"],- ";",+ ",",mock_file,file_type,)- send_email_mock.assert_called_once_with(user_export_file)+ send_email_mock.assert_called_once_with(user_export_file, "products")save_file_mock.assert_called_once_with(user_export_file, mock_file, ANY)@@ -168,7 +172,7 @@ def test_export_products_filter_is_published()# then- create_file_with_headers_mock.assert_called_once_with(["id"], ";", file_type)+ create_file_with_headers_mock.assert_called_once_with(["id"], ",", file_type)assert export_products_in_batches_mock.call_count == 1args, _ = export_products_in_batches_mock.call_args@@ -181,11 +185,11 @@ def test_export_products_filter_is_published(export_info,{"id"},["id"],- ";",+ ",",mock_file,file_type,)- send_email_mock.assert_called_once_with(user_export_file)+ send_email_mock.assert_called_once_with(user_export_file, "products")save_file_mock.assert_called_once_with(user_export_file, mock_file, ANY)@@ -228,13 +232,13 @@ def test_export_products_filter_collections()# then- create_file_with_headers_mock.assert_called_once_with(["id"], ";", file_type)+ create_file_with_headers_mock.assert_called_once_with(["id"], ",", file_type)assert export_products_in_batches_mock.call_count == 1batch_args, _ = export_products_in_batches_mock.call_argsassert set(batch_args[0].values_list("pk", flat=True)) == {product_list[-1].pk}- assert batch_args[1:] == (export_info, {"id"}, ["id"], ";", mock_file, file_type)- send_email_mock.assert_called_once_with(user_export_file)+ assert batch_args[1:] == (export_info, {"id"}, ["id"], ",", mock_file, file_type)+ send_email_mock.assert_called_once_with(user_export_file, "products")save_file_mock.assert_called_once_with(user_export_file, mock_file, ANY)@@ -267,7 +271,7 @@ def test_export_products_by_app(# thencreate_file_with_headers_mock.assert_called_once_with(- ["id", "name"], ";", file_type+ ["id", "name"], ",", file_type)assert export_products_in_batches_mock.call_count == 1@@ -279,16 +283,198 @@ def test_export_products_by_app(export_info,{"id", "name"},["id", "name"],- ";",+ ",",mock_file,file_type,)- send_email_mock.assert_called_once_with(app_export_file)+ send_email_mock.assert_called_once_with(app_export_file, "products")save_file_mock.assert_called_once_with(app_export_file, mock_file, ANY)+@patch("saleor.csv.utils.export.create_file_with_headers")+@patch("saleor.csv.utils.export.export_gift_cards_in_batches")+@patch("saleor.csv.utils.export.send_export_download_link_notification")+@patch("saleor.csv.utils.export.save_csv_file_in_export_file")+def test_export_gift_cards(+ save_file_mock,+ send_email_mock,+ export_in_batches_mock,+ create_file_with_headers_mock,+ user_export_file,+ gift_card,+ gift_card_expiry_date,+ gift_card_used,+):+ file_type = FileTypes.CSV++ mock_file = MagicMock(spec=File)+ create_file_with_headers_mock.return_value = mock_file++ # when+ export_gift_cards(user_export_file, {"all": ""}, file_type)++ # then+ create_file_with_headers_mock.assert_called_once_with(["code"], ",", file_type)++ assert export_in_batches_mock.call_count == 1+ args, kwargs = export_in_batches_mock.call_args+ assert set(args[0].values_list("pk", flat=True)) == set(+ GiftCard.objects.exclude(id=gift_card_used.id).values_list("pk", flat=True)+ )+ assert args[1:] == (+ ["code"],+ ",",+ mock_file,+ file_type,+ )++ send_email_mock.assert_called_once_with(user_export_file, "gift cards")++ save_file_mock.assert_called_once_with(user_export_file, mock_file, ANY)+++@patch("saleor.csv.utils.export.create_file_with_headers")+@patch("saleor.csv.utils.export.export_gift_cards_in_batches")+@patch("saleor.csv.utils.export.send_export_download_link_notification")+@patch("saleor.csv.utils.export.save_csv_file_in_export_file")+def test_export_gift_cards_by_app(+ save_file_mock,+ send_email_mock,+ export_in_batches_mock,+ create_file_with_headers_mock,+ app_export_file,+ gift_card,+ gift_card_expiry_date,+ gift_card_used,+):+ file_type = FileTypes.CSV++ mock_file = MagicMock(spec=File)+ create_file_with_headers_mock.return_value = mock_file++ # when+ export_gift_cards(app_export_file, {"all": ""}, file_type)++ # then+ create_file_with_headers_mock.assert_called_once_with(["code"], ",", file_type)++ assert export_in_batches_mock.call_count == 1+ args, kwargs = export_in_batches_mock.call_args+ assert set(args[0].values_list("pk", flat=True)) == set(+ GiftCard.objects.exclude(id=gift_card_used.id).values_list("pk", flat=True)+ )+ assert args[1:] == (+ ["code"],+ ",",+ mock_file,+ file_type,+ )++ send_email_mock.assert_called_once_with(app_export_file, "gift cards")++ save_file_mock.assert_called_once_with(app_export_file, mock_file, ANY)+++@patch("saleor.csv.utils.export.create_file_with_headers")+@patch("saleor.csv.utils.export.export_gift_cards_in_batches")+@patch("saleor.csv.utils.export.send_export_download_link_notification")+@patch("saleor.csv.utils.export.save_csv_file_in_export_file")+def test_export_gift_cards_ids(+ save_file_mock,+ send_email_mock,+ export_in_batches_mock,+ create_file_with_headers_mock,+ user_export_file,+ gift_card,+ gift_card_expiry_date,+ gift_card_used,+):+ file_type = FileTypes.CSV++ mock_file = MagicMock(spec=File)+ create_file_with_headers_mock.return_value = mock_file+ pks = [gift_card.pk]++ # when+ export_gift_cards(user_export_file, {"ids": pks}, file_type)++ # then+ create_file_with_headers_mock.assert_called_once_with(["code"], ",", file_type)++ assert export_in_batches_mock.call_count == 1+ args, kwargs = export_in_batches_mock.call_args+ assert set(args[0].values_list("pk", flat=True)) == set(pks)+ assert args[1:] == (+ ["code"],+ ",",+ mock_file,+ file_type,+ )++ send_email_mock.assert_called_once_with(user_export_file, "gift cards")++ save_file_mock.assert_called_once_with(user_export_file, mock_file, ANY)+++@patch("saleor.csv.utils.export.create_file_with_headers")+@patch("saleor.csv.utils.export.export_gift_cards_in_batches")+@patch("saleor.csv.utils.export.send_export_download_link_notification")+@patch("saleor.csv.utils.export.save_csv_file_in_export_file")+def test_export_gift_cards_with_filter(+ save_file_mock,+ send_email_mock,+ export_in_batches_mock,+ create_file_with_headers_mock,+ user_export_file,+ gift_card,+ gift_card_expiry_date,+ gift_card_used,+ shippable_gift_card_product,+):+ file_type = FileTypes.CSV++ mock_file = MagicMock(spec=File)+ create_file_with_headers_mock.return_value = mock_file++ gift_card_expiry_date.product = shippable_gift_card_product+ gift_card_used.product = shippable_gift_card_product+ GiftCard.objects.bulk_update([gift_card_expiry_date, gift_card_used], ["product"])++ # when+ export_gift_cards(+ user_export_file,+ {+ "filter": {+ "products": [+ graphene.Node.to_global_id(+ "Product", shippable_gift_card_product.pk+ )+ ]+ }+ },+ file_type,+ )++ # then+ create_file_with_headers_mock.assert_called_once_with(["code"], ",", file_type)++ assert export_in_batches_mock.call_count == 1+ args, kwargs = export_in_batches_mock.call_args+ assert set(args[0].values_list("pk", flat=True)) == {gift_card_expiry_date.pk}+ assert args[1:] == (+ ["code"],+ ",",+ mock_file,+ file_type,+ )++ send_email_mock.assert_called_once_with(user_export_file, "gift cards")++ save_file_mock.assert_called_once_with(user_export_file, mock_file, ANY)++def test_get_filename_csv():with freeze_time("2000-02-09 03:21:34"):file_name = get_filename("test", FileTypes.CSV)@@ -306,14 +492,14 @@ def test_get_filename_xlsx():def test_get_product_queryset_all(product_list):- queryset = get_product_queryset({"all": ""})+ queryset = get_queryset(Product, ProductFilter, {"all": ""})assert queryset.count() == len(product_list)def test_get_product_queryset_ids(product_list):pks = [product.pk for product in product_list[:2]]- queryset = get_product_queryset({"ids": pks})+ queryset = get_queryset(Product, ProductFilter, {"ids": pks})assert queryset.count() == len(pks)@@ -323,7 +509,7 @@ def get_product_queryset_filter(product_list):product_not_published.is_published = Falseproduct_not_published.save()- queryset = get_product_queryset({"ids": {"is_published": True}})+ queryset = get_queryset(Product, ProductFilter, {"ids": {"is_published": True}})assert queryset.count() == len(product_list) - 1@@ -335,14 +521,14 @@ def test_create_file_with_headers_csv(user_export_file, tmpdir, media_root):assert not user_export_file.content_file# when- csv_file = create_file_with_headers(file_headers, ";", FileTypes.CSV)+ csv_file = create_file_with_headers(file_headers, ",", FileTypes.CSV)# thenassert csv_filefile_content = csv_file.read().decode().split("\r\n")- assert ";".join(file_headers) in file_content+ assert ",".join(file_headers) in file_contentshutil.rmtree(tmpdir)@@ -354,7 +540,7 @@ def test_create_file_with_headers_xlsx(user_export_file, tmpdir, media_root):assert not user_export_file.content_file# when- xlsx_file = create_file_with_headers(file_headers, ";", FileTypes.XLSX)+ xlsx_file = create_file_with_headers(file_headers, ",", FileTypes.XLSX)# thenassert xlsx_file@@ -392,7 +578,7 @@ def test_append_to_file_for_csv(user_export_file, tmpdir, media_root):{"id": "345", "name": "test2"},]headers = ["id", "name", "collections"]- delimiter = ";"+ delimiter = ","table = etl.fromdicts([{"id": "1", "name": "A"}], header=headers, missing=" ")@@ -406,9 +592,9 @@ def test_append_to_file_for_csv(user_export_file, tmpdir, media_root):user_export_file.refresh_from_db()file_content = temp_file.read().decode().split("\r\n")- assert ";".join(headers) in file_content- assert ";".join(export_data[0].values()) in file_content- assert (";".join(export_data[1].values()) + "; ") in file_content+ assert ",".join(headers) in file_content+ assert ",".join(export_data[0].values()) in file_content+ assert (",".join(export_data[1].values()) + ", ") in file_contenttemp_file.close()shutil.rmtree(tmpdir)@@ -421,7 +607,7 @@ def test_append_to_file_for_xlsx(user_export_file, tmpdir, media_root):{"id": "345", "name": "test2"},]expected_headers = ["id", "name", "collections"]- delimiter = ";"+ delimiter = ","table = etl.fromdicts([{"id": "1", "name": "A"}], header=expected_headers, missing=" "@@ -469,7 +655,7 @@ def test_export_products_in_batches_for_csv(media_root,):# given- qs = Product.objects.all()+ qs = Product.objects.all().order_by("pk")export_info = {"fields": [ProductFieldEnum.NAME.value,@@ -486,7 +672,7 @@ def test_export_products_in_batches_for_csv(table = etl.wrap([expected_headers])temp_file = NamedTemporaryFile()- etl.tocsv(table, temp_file.name, delimiter=";")+ etl.tocsv(table, temp_file.name, delimiter=",")# whenexport_products_in_batches(@@ -494,7 +680,7 @@ def test_export_products_in_batches_for_csv(export_info,set(export_fields),export_fields,- ";",+ ",",temp_file,FileTypes.CSV,)@@ -515,10 +701,10 @@ def test_export_products_in_batches_for_csv(file_content = temp_file.read().decode().split("\r\n")# ensure headers are in file- assert ";".join(expected_headers) in file_content+ assert ",".join(expected_headers) in file_contentfor row in expected_data:- assert ";".join(row) in file_content+ assert ",".join(row) in file_contentshutil.rmtree(tmpdir)@@ -539,7 +725,7 @@ def test_export_products_in_batches_for_xlsx(}product.save(update_fields=["description"])- qs = Product.objects.all()+ qs = Product.objects.all().order_by("pk")export_info = {"fields": [ProductFieldEnum.NAME.value,@@ -564,14 +750,14 @@ def test_export_products_in_batches_for_xlsx(export_info,set(export_fields),export_fields,- ";",+ ",",temp_file,FileTypes.XLSX,)# thenexpected_data = []- for product in qs.order_by("pk"):+ for product in qs:product_data = []id = graphene.Node.to_global_id("Product", product.pk)product_data.append(id)@@ -602,6 +788,85 @@ def test_export_products_in_batches_for_xlsx(shutil.rmtree(tmpdir)+@patch("saleor.csv.utils.export.BATCH_SIZE", 1)+def test_export_gift_cards_in_batches_to_csv(+ gift_card,+ gift_card_expiry_date,+ gift_card_used,+ tmpdir,+):+ # given+ gift_cards = GiftCard.objects.exclude(id=gift_card_used.id).order_by("pk")++ table = etl.wrap([["code"]])+ temp_file = NamedTemporaryFile()+ etl.tocsv(table, temp_file.name, delimiter=",")++ # when+ export_gift_cards_in_batches(+ gift_cards,+ ["code"],+ ",",+ temp_file,+ "csv",+ )++ # then+ file_content = temp_file.read().decode().split("\r\n")++ # ensure headers are in the file+ assert "code" in file_content++ for card in gift_cards:+ assert card.code in file_content++ shutil.rmtree(tmpdir)+++@patch("saleor.csv.utils.export.BATCH_SIZE", 1)+def test_export_gift_cards_in_batches_to_xlsx(+ gift_card,+ gift_card_expiry_date,+ gift_card_used,+ tmpdir,+):+ # given+ gift_cards = GiftCard.objects.exclude(id=gift_card_used.id).order_by("pk")++ table = etl.wrap([["code"]])+ temp_file = NamedTemporaryFile(suffix=".xlsx")+ etl.io.xlsx.toxlsx(table, temp_file.name)++ # when+ export_gift_cards_in_batches(+ gift_cards,+ ["code"],+ ",",+ temp_file,+ "xlsx",+ )++ # then+ wb_obj = openpyxl.load_workbook(temp_file)++ sheet_obj = wb_obj.active+ max_col = sheet_obj.max_column+ max_row = sheet_obj.max_row+ headers = [sheet_obj.cell(row=1, column=i).value for i in range(1, max_col + 1)]+ data = []+ for i in range(2, max_row + 1):+ row = []+ for j in range(1, max_col + 1):+ row.append(sheet_obj.cell(row=i, column=j).value)+ data.append(row)++ assert headers == ["code"]+ for card in gift_cards:+ assert [card.code] in data++ shutil.rmtree(tmpdir)++def test_parse_input():data = {"collections": None,diff --git a/saleor/csv/tests/test_notifications.py b/saleor/csv/tests/test_notifications.pyindex 4bb4558d8c..87a6a59309 100644--- a/saleor/csv/tests/test_notifications.py+++ b/saleor/csv/tests/test_notifications.py@@ -18,23 +18,25 @@ def test_send_export_download_link_notification(# givenfile_mock = mock.MagicMock(spec=File)file_mock.name = "temp_file.csv"+ data_type = "products"user_export_file.content_file = file_mockuser_export_file.save()# when- notifications.send_export_download_link_notification(user_export_file)+ notifications.send_export_download_link_notification(user_export_file, data_type)# thenexpected_payload = {"export": get_default_export_payload(user_export_file),"csv_link": build_absolute_uri(user_export_file.content_file.url),"recipient_email": user_export_file.user.email,+ "data_type": data_type,**get_site_context(),}mocked_notify.assert_called_once_with(- AdminNotifyEvent.CSV_PRODUCT_EXPORT_SUCCESS, expected_payload+ AdminNotifyEvent.CSV_EXPORT_SUCCESS, expected_payload)@@ -46,17 +48,19 @@ def test_send_export_failed_info(# givenfile_mock = mock.MagicMock(spec=File)file_mock.name = "temp_file.csv"+ data_type = "gift cards"user_export_file.content_file = file_mockuser_export_file.save()# when- notifications.send_export_failed_info(user_export_file)+ notifications.send_export_failed_info(user_export_file, data_type)# thenexpected_payload = {"export": get_default_export_payload(user_export_file),"recipient_email": user_export_file.user.email,+ "data_type": data_type,**get_site_context(),}diff --git a/saleor/csv/utils/export.py b/saleor/csv/utils/export.pyindex 84513dc44c..cbb0923f8f 100644--- a/saleor/csv/utils/export.py+++ b/saleor/csv/utils/export.py@@ -6,10 +6,11 @@ from typing import IO, TYPE_CHECKING, Any, Dict, List, Set, Unionimport petl as etlfrom django.utils import timezone+from ...giftcard.models import GiftCardfrom ...product.models import Productfrom .. import FileTypesfrom ..notifications import send_export_download_link_notification-from .product_headers import get_export_fields_and_headers_info+from .product_headers import get_product_export_fields_and_headers_infofrom .products_data import get_products_dataif TYPE_CHECKING:@@ -27,14 +28,18 @@ def export_products(scope: Dict[str, Union[str, dict]],export_info: Dict[str, list],file_type: str,- delimiter: str = ";",+ delimiter: str = ",",):+ from ...graphql.product.filters import ProductFilter+file_name = get_filename("product", file_type)- queryset = get_product_queryset(scope)+ queryset = get_queryset(Product, ProductFilter, scope)- export_fields, file_headers, data_headers = get_export_fields_and_headers_info(- export_info- )+ (+ export_fields,+ file_headers,+ data_headers,+ ) = get_product_export_fields_and_headers_info(export_info)temporary_file = create_file_with_headers(file_headers, delimiter, file_type)@@ -51,7 +56,38 @@ def export_products(save_csv_file_in_export_file(export_file, temporary_file, file_name)temporary_file.close()- send_export_download_link_notification(export_file)+ send_export_download_link_notification(export_file, "products")+++def export_gift_cards(+ export_file: "ExportFile",+ scope: Dict[str, Union[str, dict]],+ file_type: str,+ delimiter: str = ",",+):+ from ...graphql.giftcard.filters import GiftCardFilter++ file_name = get_filename("gift_card", file_type)++ queryset = get_queryset(GiftCard, GiftCardFilter, scope)+ # only unused gift cards codes can be exported+ queryset = queryset.filter(used_by_email__isnull=True)++ export_fields = ["code"]+ temporary_file = create_file_with_headers(export_fields, delimiter, file_type)++ export_gift_cards_in_batches(+ queryset,+ export_fields,+ delimiter,+ temporary_file,+ file_type,+ )++ save_csv_file_in_export_file(export_file, temporary_file, file_name)+ temporary_file.close()++ send_export_download_link_notification(export_file, "gift cards")def get_filename(model_name: str, file_type: str) -> str:@@ -61,6 +97,18 @@ def get_filename(model_name: str, file_type: str) -> str:)+def get_queryset(model, filter, scope: Dict[str, Union[str, dict]]) -> "QuerySet":+ queryset = model.objects.all()+ if "ids" in scope:+ queryset = model.objects.filter(pk__in=scope["ids"])+ elif "filter" in scope:+ queryset = filter(data=parse_input(scope["filter"]), queryset=queryset).qs++ queryset = queryset.order_by("pk")++ return queryset++def parse_input(data: Any) -> Dict[str, Union[str, dict]]:"""Parse input to correct data types, since scope coming from celery will be parsed to strings."""if "attributes" in data:@@ -87,41 +135,17 @@ def parse_input(data: Any) -> Dict[str, Union[str, dict]]:return data-def get_product_queryset(scope: Dict[str, Union[str, dict]]) -> "QuerySet":- """Get product queryset based on a scope."""-- from ...graphql.product.filters import ProductFilter-- queryset = Product.objects.all()- if "ids" in scope:- queryset = Product.objects.filter(pk__in=scope["ids"])- elif "filter" in scope:- queryset = ProductFilter(- data=parse_input(scope["filter"]), queryset=queryset- ).qs-- queryset = queryset.order_by("pk")-- return queryset---def queryset_in_batches(queryset):- """Slice a queryset into batches.-- Input queryset should be sorted be pk.- """- start_pk = 0-- while True:- qs = queryset.filter(pk__gt=start_pk)[:BATCH_SIZE]- pks = list(qs.values_list("pk", flat=True))-- if not pks:- break+def create_file_with_headers(file_headers: List[str], delimiter: str, file_type: str):+ table = etl.wrap([file_headers])- yield pks+ if file_type == FileTypes.CSV:+ temp_file = NamedTemporaryFile("ab+", suffix=".csv")+ etl.tocsv(table, temp_file.name, delimiter=delimiter)+ else:+ temp_file = NamedTemporaryFile("ab+", suffix=".xlsx")+ etl.io.xlsx.toxlsx(table, temp_file.name)- start_pk = pks[-1]+ return temp_filedef export_products_in_batches(@@ -154,17 +178,38 @@ def export_products_in_batches(append_to_file(export_data, headers, temporary_file, file_type, delimiter)-def create_file_with_headers(file_headers: List[str], delimiter: str, file_type: str):- table = etl.wrap([file_headers])+def export_gift_cards_in_batches(+ queryset: "QuerySet",+ export_fields: List[str],+ delimiter: str,+ temporary_file: Any,+ file_type: str,+):+ for batch_pks in queryset_in_batches(queryset):+ gift_card_batch = GiftCard.objects.filter(pk__in=batch_pks)- if file_type == FileTypes.CSV:- temp_file = NamedTemporaryFile("ab+", suffix=".csv")- etl.tocsv(table, temp_file.name, delimiter=delimiter)- else:- temp_file = NamedTemporaryFile("ab+", suffix=".xlsx")- etl.io.xlsx.toxlsx(table, temp_file.name)+ export_data = list(gift_card_batch.values(*export_fields))- return temp_file+ append_to_file(export_data, export_fields, temporary_file, file_type, delimiter)+++def queryset_in_batches(queryset):+ """Slice a queryset into batches.++ Input queryset should be sorted be pk.+ """+ start_pk = 0++ while True:+ qs = queryset.filter(pk__gt=start_pk)[:BATCH_SIZE]+ pks = list(qs.values_list("pk", flat=True))++ if not pks:+ break++ yield pks++ start_pk = pks[-1]def append_to_file(diff --git a/saleor/csv/utils/product_headers.py b/saleor/csv/utils/product_headers.pyindex 99f4bf9670..3dbe2b7452 100644--- a/saleor/csv/utils/product_headers.py+++ b/saleor/csv/utils/product_headers.py@@ -10,7 +10,7 @@ from ...warehouse.models import Warehousefrom . import ProductExportFields-def get_export_fields_and_headers_info(+def get_product_export_fields_and_headers_info(export_info: Dict[str, list]) -> Tuple[List[str], List[str], List[str]]:"""Get export fields, all headers and headers mapping.diff --git a/saleor/giftcard/__init__.py b/saleor/giftcard/__init__.pyindex 00af1441ce..e451819c87 100644--- a/saleor/giftcard/__init__.py+++ b/saleor/giftcard/__init__.py@@ -16,7 +16,7 @@ class GiftCardEvents:DEACTIVATED = "deactivated"BALANCE_RESET = "balance_reset"EXPIRY_DATE_UPDATED = "expiry_date_updated"- TAG_UPDATED = "tag_updated"+ TAGS_UPDATED = "tags_updated"SENT_TO_CUSTOMER = "sent_to_customer"RESENT = "resent"NOTE_ADDED = "note_added"@@ -30,7 +30,7 @@ class GiftCardEvents:(DEACTIVATED, "The gift card was deactivated."),(BALANCE_RESET, "The gift card balance was reset."),(EXPIRY_DATE_UPDATED, "The gift card expiry date was updated."),- (TAG_UPDATED, "The gift card tag was updated."),+ (TAGS_UPDATED, "The gift card tags were updated."),(SENT_TO_CUSTOMER, "The gift card was sent to the customer."),(RESENT, "The gift card was resent to the customer."),(NOTE_ADDED, "A note was added to the gift card."),diff --git a/saleor/giftcard/error_codes.py b/saleor/giftcard/error_codes.pyindex c81ddbe3cd..c4294a3083 100644--- a/saleor/giftcard/error_codes.py+++ b/saleor/giftcard/error_codes.py@@ -8,3 +8,5 @@ class GiftCardErrorCode(Enum):NOT_FOUND = "not_found"REQUIRED = "required"UNIQUE = "unique"+ EXPIRED_GIFT_CARD = "expired_gift_card"+ DUPLICATED_INPUT_ITEM = "duplicated_input_item"diff --git a/saleor/giftcard/events.py b/saleor/giftcard/events.pyindex dfff1dfe7b..c11458c877 100644--- a/saleor/giftcard/events.py+++ b/saleor/giftcard/events.py@@ -1,4 +1,4 @@-from typing import Iterable, Optional, Tuple+from typing import Iterable, List, Optional, Tuplefrom ..account.models import Userfrom ..app.models import App@@ -31,6 +31,29 @@ def gift_card_issued_event()+def gift_cards_issued_event(+ gift_cards: Iterable[GiftCard], user: UserType, app: AppType, balance: dict+):+ if not user_is_valid(user):+ user = None+ balance_data = {+ "currency": balance["currency"],+ "initial_balance": balance["amount"],+ "current_balance": balance["amount"],+ }+ events = [+ GiftCardEvent(+ gift_card=gift_card,+ user=user,+ app=app,+ type=GiftCardEvents.ISSUED,+ parameters={"balance": balance_data, "expiry_date": gift_card.expiry_date},+ )+ for gift_card in gift_cards+ ]+ return GiftCardEvent.objects.bulk_create(events)++def gift_card_sent_event(gift_card_id: int, user_id: Optional[int], app_id: Optional[int], email: str):@@ -100,9 +123,9 @@ def gift_card_expiry_date_updated_event()-def gift_card_tag_updated_event(+def gift_card_tags_updated_event(gift_card: GiftCard,- old_gift_card: GiftCard,+ old_tags: List[str],user: UserType,app: AppType,):@@ -112,10 +135,12 @@ def gift_card_tag_updated_event(gift_card=gift_card,user=user,app=app,- type=GiftCardEvents.TAG_UPDATED,+ type=GiftCardEvents.TAGS_UPDATED,parameters={- "tag": gift_card.tag,- "old_tag": old_gift_card.tag,+ "tags": list(+ gift_card.tags.order_by("name").values_list("name", flat=True)+ ),+ "old_tags": old_tags,},)diff --git a/saleor/giftcard/migrations/0010_auto_20211007_0546.py b/saleor/giftcard/migrations/0010_auto_20211007_0546.pynew file mode 100644index 0000000000..62e1f057fb--- /dev/null+++ b/saleor/giftcard/migrations/0010_auto_20211007_0546.py@@ -0,0 +1,57 @@+# Generated by Django 3.2.6 on 2021-10-07 05:46++import django.contrib.postgres.indexes+from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("giftcard", "0009_giftcard_fulfillment_line"),+ ]++ operations = [+ migrations.CreateModel(+ name="GiftCardTag",+ fields=[+ (+ "id",+ models.AutoField(+ auto_created=True,+ primary_key=True,+ serialize=False,+ verbose_name="ID",+ ),+ ),+ ("name", models.CharField(max_length=255, unique=True)),+ ],+ options={"ordering": ("name",)},+ ),+ migrations.RemoveIndex(+ model_name="giftcard",+ name="giftcard_p_meta_idx",+ ),+ migrations.RemoveIndex(+ model_name="giftcard",+ name="giftcard_meta_idx",+ ),+ migrations.RemoveIndex(+ model_name="giftcard",+ name="giftcard_search_gin",+ ),+ migrations.AddField(+ model_name="giftcard",+ name="tags",+ field=models.ManyToManyField(+ related_name="gift_cards", to="giftcard.GiftCardTag"+ ),+ ),+ migrations.AddIndex(+ model_name="giftcardtag",+ index=django.contrib.postgres.indexes.GinIndex(+ fields=["name"],+ name="gift_card_tag_search_gin",+ opclasses=["gin_trgm_ops"],+ ),+ ),+ ]diff --git a/saleor/giftcard/migrations/0011_auto_20211007_0547.py b/saleor/giftcard/migrations/0011_auto_20211007_0547.pynew file mode 100644index 0000000000..84ea1efba0--- /dev/null+++ b/saleor/giftcard/migrations/0011_auto_20211007_0547.py@@ -0,0 +1,23 @@+# Generated by Django 3.2.6 on 2021-10-07 05:47++from django.db import migrations+++def move_gift_card_tags_to_objects(apps, schema_editor):+ GiftCard = apps.get_model("giftcard", "GiftCard")+ GiftCardTag = apps.get_model("giftcard", "GiftCardTag")+ for card in GiftCard.objects.iterator():+ if card.tag:+ tag, _created = GiftCardTag.objects.get_or_create(name=card.tag)+ card.tags.add(tag)+++class Migration(migrations.Migration):++ dependencies = [+ ("giftcard", "0010_auto_20211007_0546"),+ ]++ operations = [+ migrations.RunPython(move_gift_card_tags_to_objects, migrations.RunPython.noop),+ ]diff --git a/saleor/giftcard/migrations/0012_auto_20211007_0655.py b/saleor/giftcard/migrations/0012_auto_20211007_0655.pynew file mode 100644index 0000000000..4433ff3631--- /dev/null+++ b/saleor/giftcard/migrations/0012_auto_20211007_0655.py@@ -0,0 +1,38 @@+# Generated by Django 3.2.6 on 2021-10-07 06:55++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("giftcard", "0011_auto_20211007_0547"),+ ]++ operations = [+ migrations.RemoveField(+ model_name="giftcard",+ name="tag",+ ),+ migrations.AlterField(+ model_name="giftcardevent",+ name="type",+ field=models.CharField(+ choices=[+ ("issued", "The gift card was created be staff user or app."),+ ("bought", "The gift card was bought by customer."),+ ("updated", "The gift card was updated."),+ ("activated", "The gift card was activated."),+ ("deactivated", "The gift card was deactivated."),+ ("balance_reset", "The gift card balance was reset."),+ ("expiry_date_updated", "The gift card expiry date was updated."),+ ("tags_updated", "The gift card tags were updated."),+ ("sent_to_customer", "The gift card was sent to the customer."),+ ("resent", "The gift card was resent to the customer."),+ ("note_added", "A note was added to the gift card."),+ ("used_in_order", "The gift card was used in order."),+ ],+ max_length=255,+ ),+ ),+ ]diff --git a/saleor/giftcard/models.py b/saleor/giftcard/models.pyindex 9b733a0135..e1eed6ff5e 100644--- a/saleor/giftcard/models.py+++ b/saleor/giftcard/models.py@@ -14,6 +14,21 @@ from ..core.utils.json_serializer import CustomJsonEncoderfrom . import GiftCardEvents+class GiftCardTag(models.Model):+ name = models.CharField(max_length=255, unique=True)++ class Meta:+ ordering = ("name",)+ indexes = [+ GinIndex(+ name="gift_card_tag_search_gin",+ # `opclasses` and `fields` should be the same length+ fields=["name"],+ opclasses=["gin_trgm_ops"],+ ),+ ]++class GiftCardQueryset(models.QuerySet):def active(self, date):return self.filter(@@ -51,7 +66,7 @@ class GiftCard(ModelWithMetadata):expiry_date = models.DateField(null=True, blank=True)- tag = models.CharField(max_length=255, null=True, blank=True)+ tags = models.ManyToManyField(GiftCardTag, "gift_cards")created = models.DateTimeField(auto_now_add=True)last_used_on = models.DateTimeField(null=True, blank=True)product = models.ForeignKey(@@ -97,19 +112,10 @@ class GiftCard(ModelWithMetadata):permissions = ((GiftcardPermissions.MANAGE_GIFT_CARD.codename, "Manage gift cards."),)- indexes = [- *ModelWithMetadata.Meta.indexes,- GinIndex(- name="giftcard_search_gin",- # `opclasses` and `fields` should be the same length- fields=["tag"],- opclasses=["gin_trgm_ops"],- ),- ]@propertydef display_code(self):- return "****%s" % self.code[-4:]+ return self.code[-4:]class GiftCardEvent(models.Model):diff --git a/saleor/giftcard/tasks.py b/saleor/giftcard/tasks.pynew file mode 100644index 0000000000..7356b519aa--- /dev/null+++ b/saleor/giftcard/tasks.py@@ -0,0 +1,20 @@+from celery.utils.log import get_task_logger+from django.utils import timezone++from ..celeryconf import app+from .events import gift_cards_deactivated_event+from .models import GiftCard++task_logger = get_task_logger(__name__)+++def deactivate_expired_cards_task():+ today = timezone.now().date()+ gift_cards = GiftCard.objects.filter(expiry_date__lt=today, is_active=True)+ if not gift_cards:+ return+ gift_card_ids = list(gift_cards.values_list("id", flat=True))+ count = gift_cards.update(is_active=False)+ gift_cards_deactivated_event(gift_card_ids, user=None, app=None)+ task_logger.debug("Deactivate %s gift cards", count)diff --git a/saleor/giftcard/tests/test_tasks.py b/saleor/giftcard/tests/test_tasks.pynew file mode 100644index 0000000000..fe06db1377--- /dev/null+++ b/saleor/giftcard/tests/test_tasks.py@@ -0,0 +1,71 @@+import datetime++import pytest++from .. import GiftCardEvents+from ..models import GiftCard+from ..tasks import deactivate_expired_cards_task+++def test_deactivate_expired_cards_task(+ gift_card, gift_card_used, gift_card_expiry_date, gift_card_created_by_staff+):+ # given+ gift_card.expiry_date = datetime.date.today() - datetime.timedelta(days=1)+ gift_card_used.expiry_date = datetime.date.today() - datetime.timedelta(days=10)+ gift_card_created_by_staff.expiry_date = datetime.date.today() - datetime.timedelta(+ days=10+ )+ gift_card_created_by_staff.is_active = False+ gift_cards = [gift_card, gift_card_used]+ GiftCard.objects.bulk_update(+ gift_cards + [gift_card_created_by_staff], ["expiry_date", "is_active"]+ )++ for card in gift_cards:+ assert card.is_active++ # when+ deactivate_expired_cards_task()++ # then+ for card in gift_cards:+ card.refresh_from_db()+ assert not card.is_active+ assert card.events.filter(type=GiftCardEvents.DEACTIVATED)++ assert not gift_card_created_by_staff.events.filter(type=GiftCardEvents.DEACTIVATED)++ gift_card_expiry_date.refresh_from_db()+ assert gift_card_expiry_date.is_active+++ "expiry_date",+ [+ datetime.date.today(),+ datetime.date.today() + datetime.timedelta(days=1),+ ],+)+def test_deactivate_expired_cards_task_cards_not_deactivated(+ expiry_date, gift_card, gift_card_used, gift_card_expiry_date+):+ # given+ gift_card.expiry_date = expiry_date+ gift_card_used.expiry_date = expiry_date+ gift_cards = [gift_card, gift_card_used]+ GiftCard.objects.bulk_update(gift_cards, ["expiry_date"])++ for card in gift_cards:+ assert card.is_active++ # when+ deactivate_expired_cards_task()++ # then+ for card in gift_cards:+ card.refresh_from_db()+ assert card.is_active++ gift_card_expiry_date.refresh_from_db()+ assert gift_card_expiry_date.is_activediff --git a/saleor/giftcard/tests/test_utils.py b/saleor/giftcard/tests/test_utils.pyindex a94bf90564..d08cdd19a3 100644--- a/saleor/giftcard/tests/test_utils.py+++ b/saleor/giftcard/tests/test_utils.py@@ -24,6 +24,7 @@ from ..utils import (get_gift_card_lines,get_non_shippable_gift_card_lines,gift_cards_create,+ is_gift_card_expired,order_has_gift_card_lines,remove_gift_card_code_from_checkout,)@@ -263,6 +264,8 @@ def test_gift_cards_create(assert non_shippable_event.app is Noneassert non_shippable_event.parameters == {"order_id": order.id, "expiry_date": None}+ flush_post_commit_hooks()+send_notification_mock.assert_called_once_with(staff_user,None,@@ -338,6 +341,8 @@ def test_gift_cards_create_expiry_date_set("expiry_date": gift_card.expiry_date.isoformat(),}+ flush_post_commit_hooks()+send_notification_mock.assert_called_once_with(staff_user,None,@@ -383,6 +388,7 @@ def test_gift_cards_create_multiple_quantity()# then+ flush_post_commit_hooks()assert len(gift_cards) == quantityprice = gift_card_non_shippable_order_line.unit_price_grossfor gift_card in gift_cards:@@ -713,3 +719,41 @@ def test_assign_user_gift_cards_no_gift_cards_to_assign(# thengift_card_created_by_staff.refresh_from_db()assert not gift_card_created_by_staff.created_by+++def test_is_gift_card_expired_never_expired_gift_card(gift_card):+ # given+ assert not gift_card.expiry_date++ # when+ result = is_gift_card_expired(gift_card)++ # then+ assert result is False+++def test_is_gift_card_expired_true(gift_card):+ # given+ gift_card.expiry_date = date.today() - timedelta(days=1)+ gift_card.save(update_fields=["expiry_date"])++ # when+ result = is_gift_card_expired(gift_card)++ # then+ assert result is True+++ "expiry_date", [date.today(), date.today() + timedelta(days=1)]+)+def test_is_gift_card_expired_false(expiry_date, gift_card):+ # given+ gift_card.expiry_date = expiry_date+ gift_card.save(update_fields=["expiry_date"])++ # when+ result = is_gift_card_expired(gift_card)++ # then+ assert result is Falsediff --git a/saleor/giftcard/utils.py b/saleor/giftcard/utils.pyindex 7f4c76b0f9..53e2348660 100644--- a/saleor/giftcard/utils.py+++ b/saleor/giftcard/utils.py@@ -4,11 +4,13 @@ from typing import TYPE_CHECKING, Iterable, Optionalfrom dateutil.relativedelta import relativedeltafrom django.core.exceptions import ValidationError+from django.db import transactionfrom django.db.models.expressions import Exists, OuterReffrom django.utils import timezonefrom ..checkout.error_codes import CheckoutErrorCodefrom ..checkout.models import Checkout+from ..core.tracing import traced_atomic_transactionfrom ..core.utils.promo_code import InvalidPromoCode, generate_promo_codefrom ..core.utils.validators import user_is_validfrom ..order.actions import create_fulfillments@@ -151,6 +153,7 @@ def fulfill_gift_card_lines()+@traced_atomic_transaction()def gift_cards_create(order: "Order",gift_card_lines_info: Iterable["GiftCardLineData"],@@ -190,14 +193,16 @@ def gift_cards_create(channel_slug = order.channel.slug# send to customer all non-shippable gift cards- send_gift_cards_to_customer(- non_shippable_gift_cards,- user_email,- requestor_user,- app,- customer_user,- manager,- channel_slug,+ transaction.on_commit(+ lambda: send_gift_cards_to_customer(+ non_shippable_gift_cards,+ user_email,+ requestor_user,+ app,+ customer_user,+ manager,+ channel_slug,+ ))return gift_cards@@ -257,3 +262,9 @@ def order_has_gift_card_lines(order):def assign_user_gift_cards(user):GiftCard.objects.filter(used_by_email=user.email).update(used_by=user)GiftCard.objects.filter(created_by_email=user.email).update(created_by=user)+++def is_gift_card_expired(gift_card: GiftCard):+ """Return True when gift card expiry date pass."""+ today = timezone.now().date()+ return bool(gift_card.expiry_date) and gift_card.expiry_date < today # type: ignorediff --git a/saleor/graphql/channel/mutations.py b/saleor/graphql/channel/mutations.pyindex 3d9c880f58..2bb3dbca63 100644--- a/saleor/graphql/channel/mutations.py+++ b/saleor/graphql/channel/mutations.py@@ -15,7 +15,7 @@ from ..account.enums import CountryCodeEnumfrom ..core.descriptions import ADDED_IN_31from ..core.mutations import BaseMutation, ModelDeleteMutation, ModelMutationfrom ..core.types.common import ChannelError, ChannelErrorCode-from ..core.utils import get_duplicated_values, get_duplicates_ids+from ..core.utils import get_duplicated_values, get_duplicates_itemsfrom ..utils.validators import check_for_duplicatesfrom .types import Channel@@ -269,7 +269,7 @@ class BaseChannelListingMutation(BaseMutation):errors: ErrorType,error_code,):- duplicated_ids = get_duplicates_ids(add_channels_ids, remove_channels_ids)+ duplicated_ids = get_duplicates_items(add_channels_ids, remove_channels_ids)if duplicated_ids:error_msg = ("The same object cannot be in both lists "diff --git a/saleor/graphql/checkout/tests/deprecated/test_checkout_promo_codes.py b/saleor/graphql/checkout/tests/deprecated/test_checkout_promo_codes.pyindex e92dec0d0d..cafb00d197 100644--- a/saleor/graphql/checkout/tests/deprecated/test_checkout_promo_codes.py+++ b/saleor/graphql/checkout/tests/deprecated/test_checkout_promo_codes.py@@ -21,7 +21,7 @@ MUTATION_CHECKOUT_ADD_PROMO_CODE = """}giftCards {id- displayCode+ last4CodeChars}totalPrice {gross {@@ -91,7 +91,7 @@ MUTATION_CHECKOUT_REMOVE_PROMO_CODE = """voucherCodegiftCards {id- displayCode+ last4CodeChars}}}diff --git a/saleor/graphql/checkout/tests/test_checkout_complete.py b/saleor/graphql/checkout/tests/test_checkout_complete.pyindex ff15569d61..6ba37474bd 100644--- a/saleor/graphql/checkout/tests/test_checkout_complete.py+++ b/saleor/graphql/checkout/tests/test_checkout_complete.py@@ -24,6 +24,7 @@ from ....payment import ChargeStatus, PaymentError, TransactionKindfrom ....payment.gateways.dummy_credit_card import TOKEN_VALIDATION_MAPPINGfrom ....payment.interface import GatewayResponsefrom ....plugins.manager import PluginsManager, get_plugins_manager+from ....tests.utils import flush_post_commit_hooksfrom ....warehouse.models import Reservation, Stock, WarehouseClickAndCollectOptionfrom ....warehouse.tests.utils import get_available_quantity_for_stockfrom ...tests.utils import get_graphql_content@@ -465,6 +466,7 @@ def test_checkout_complete_gift_card_bought(order = Order.objects.first()assert order.status == OrderStatus.PARTIALLY_FULFILLED+ flush_post_commit_hooks()gift_card = GiftCard.objects.get()assert GiftCardEvent.objects.filter(gift_card=gift_card, type=GiftCardEvents.BOUGHT)send_notification_mock.assert_called_once_with(diff --git a/saleor/graphql/checkout/tests/test_checkout_promo_codes.py b/saleor/graphql/checkout/tests/test_checkout_promo_codes.pyindex fd1d14247c..3a654e986c 100644--- a/saleor/graphql/checkout/tests/test_checkout_promo_codes.py+++ b/saleor/graphql/checkout/tests/test_checkout_promo_codes.py@@ -177,7 +177,7 @@ query getCheckout($token: UUID!) {checkout(token: $token) {tokengiftCards {- displayCode+ last4CodeCharscurrentBalance {amount}@@ -195,7 +195,7 @@ def test_checkout_get_gift_card_code(user_api_client, checkout_with_gift_card):)content = get_graphql_content(response)data = content["data"]["checkout"]["giftCards"][0]- assert data["displayCode"] == gift_card.display_code+ assert data["last4CodeChars"] == gift_card.display_codeassert data["currentBalance"]["amount"] == gift_card.current_balance.amount@@ -212,9 +212,9 @@ def test_checkout_get_gift_card_codes()content = get_graphql_content(response)data = content["data"]["checkout"]["giftCards"]- assert data[0]["displayCode"] == gift_card_first.display_code+ assert data[0]["last4CodeChars"] == gift_card_first.display_codeassert data[0]["currentBalance"]["amount"] == gift_card_first.current_balance.amount- assert data[1]["displayCode"] == gift_card_last.display_code+ assert data[1]["last4CodeChars"] == gift_card_last.display_codeassert data[1]["currentBalance"]["amount"] == gift_card_last.current_balance.amount@@ -243,7 +243,7 @@ MUTATION_CHECKOUT_ADD_PROMO_CODE = """voucherCodegiftCards {id- displayCode+ last4CodeChars}totalPrice {gross {@@ -602,7 +602,7 @@ def test_checkout_add_gift_card_code(api_client, checkout_with_item, gift_card):assert not data["errors"]assert data["checkout"]["token"] == str(checkout_with_item.token)assert data["checkout"]["giftCards"][0]["id"] == gift_card_id- assert data["checkout"]["giftCards"][0]["displayCode"] == gift_card.display_code+ assert data["checkout"]["giftCards"][0]["last4CodeChars"] == gift_card.display_codedef test_checkout_add_many_gift_card_code(@@ -679,7 +679,8 @@ def test_checkout_add_used_gift_card_code(assert data["checkout"]["token"] == str(checkout_with_item.token)assert data["checkout"]["giftCards"][0]["id"] == gift_card_idassert (- data["checkout"]["giftCards"][0]["displayCode"] == gift_card_used.display_code+ data["checkout"]["giftCards"][0]["last4CodeChars"]+ == gift_card_used.display_code)@@ -778,7 +779,7 @@ def test_checkout_add_same_gift_card_code(api_client, checkout_with_gift_card):assert not data["errors"]assert data["checkout"]["token"] == str(checkout_with_gift_card.token)assert data["checkout"]["giftCards"][0]["id"] == gift_card_id- assert data["checkout"]["giftCards"][0]["displayCode"] == gift_card.display_code+ assert data["checkout"]["giftCards"][0]["last4CodeChars"] == gift_card.display_codeassert len(data["checkout"]["giftCards"]) == gift_card_count@@ -890,7 +891,7 @@ MUTATION_CHECKOUT_REMOVE_PROMO_CODE = """voucherCodegiftCards {id- displayCode+ last4CodeChars}}}diff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.pyindex fa74a1a026..f4a7144d40 100644--- a/saleor/graphql/core/types/common.py+++ b/saleor/graphql/core/types/common.py@@ -321,6 +321,11 @@ class PaymentError(Error):class GiftCardError(Error):code = GiftCardErrorCode(description="The error code.", required=True)+ tags = graphene.List(+ graphene.NonNull(graphene.String),+ description="List of tag values that cause the error.",+ required=False,+ )class PluginError(Error):diff --git a/saleor/graphql/core/utils/__init__.py b/saleor/graphql/core/utils/__init__.pyindex 1bae07f2bf..8e24fee864 100644--- a/saleor/graphql/core/utils/__init__.py+++ b/saleor/graphql/core/utils/__init__.py@@ -116,7 +116,7 @@ def validate_slug_value(cleaned_input, slug_field_name: str = "slug"):)-def get_duplicates_ids(first_list, second_list):+def get_duplicates_items(first_list, second_list):"""Return items that appear on both provided lists."""if first_list and second_list:return set(first_list) & set(second_list)diff --git a/saleor/graphql/csv/mutations.py b/saleor/graphql/csv/mutations.pyindex c518cd4743..d3491a9091 100644--- a/saleor/graphql/csv/mutations.py+++ b/saleor/graphql/csv/mutations.py@@ -3,15 +3,18 @@ from typing import Dict, List, Mapping, Unionimport graphenefrom django.core.exceptions import ValidationError-from ...core.permissions import ProductPermissions+from ...core.permissions import GiftcardPermissions, ProductPermissionsfrom ...csv import models as csv_modelsfrom ...csv.events import export_started_event-from ...csv.tasks import export_products_task+from ...csv.tasks import export_gift_cards_task, export_products_taskfrom ..attribute.types import Attributefrom ..channel.types import Channel+from ..core.descriptions import ADDED_IN_31from ..core.enums import ExportErrorCodefrom ..core.mutations import BaseMutationfrom ..core.types.common import ExportError+from ..giftcard.filters import GiftCardFilterInput+from ..giftcard.types import GiftCardfrom ..product.filters import ProductFilterInputfrom ..product.types import Productfrom ..warehouse.types import Warehouse@@ -19,6 +22,56 @@ from .enums import ExportScope, FileTypeEnum, ProductFieldEnumfrom .types import ExportFile+class BaseExportMutation(BaseMutation):+ export_file = graphene.Field(+ ExportFile,+ description=(+ "The newly created export file job which is responsible for export data."+ ),+ )++ class Meta:+ abstract = True++ @classmethod+ def get_scope(cls, input, only_type) -> Mapping[str, Union[list, dict, str]]:+ scope = input["scope"]+ if scope == ExportScope.IDS.value: # type: ignore+ return cls.clean_ids(input, only_type)+ elif scope == ExportScope.FILTER.value: # type: ignore+ return cls.clean_filter(input)+ return {"all": ""}++ @classmethod+ def clean_ids(cls, input, only_type) -> Dict[str, List[str]]:+ ids = input.get("ids", [])+ if not ids:+ raise ValidationError(+ {+ "ids": ValidationError(+ "You must provide at least one id.",+ code=ExportErrorCode.REQUIRED.value,+ )+ }+ )+ pks = cls.get_global_ids_or_error(ids, only_type=only_type, field="ids")+ return {"ids": pks}++ @staticmethod+ def clean_filter(input) -> Dict[str, dict]:+ filter = input.get("filter")+ if not filter:+ raise ValidationError(+ {+ "filter": ValidationError(+ "You must provide filter input.",+ code=ExportErrorCode.REQUIRED.value,+ )+ }+ )+ return {"filter": filter}++class ExportInfoInput(graphene.InputObjectType):attributes = graphene.List(graphene.NonNull(graphene.ID),@@ -47,7 +100,7 @@ class ExportProductsInput(graphene.InputObjectType):)ids = graphene.List(graphene.NonNull(graphene.ID),- description="List of products IDS to export.",+ description="List of products IDs to export.",required=False,)export_info = ExportInfoInput(@@ -57,17 +110,10 @@ class ExportProductsInput(graphene.InputObjectType):file_type = FileTypeEnum(description="Type of exported file.", required=True)-class ExportProducts(BaseMutation):- export_file = graphene.Field(- ExportFile,- description=(- "The newly created export file job which is responsible for export data."- ),- )-+class ExportProducts(BaseExportMutation):class Arguments:input = ExportProductsInput(- required=True, description="Fields required to export product data"+ required=True, description="Fields required to export product data.")class Meta:@@ -79,7 +125,7 @@ class ExportProducts(BaseMutation):@classmethoddef perform_mutation(cls, root, info, **data):input = data["input"]- scope = cls.get_products_scope(input)+ scope = cls.get_scope(input, Product)export_info = cls.get_export_info(input["export_info"])file_type = input["file_type"]@@ -93,44 +139,6 @@ class ExportProducts(BaseMutation):export_file.refresh_from_db()return cls(export_file=export_file)- @classmethod- def get_products_scope(cls, input) -> Mapping[str, Union[list, dict, str]]:- scope = input["scope"]- if scope == ExportScope.IDS.value: # type: ignore- return cls.clean_ids(input)- elif scope == ExportScope.FILTER.value: # type: ignore- return cls.clean_filter(input)- return {"all": ""}-- @classmethod- def clean_ids(cls, input) -> Dict[str, List[str]]:- ids = input.get("ids", [])- if not ids:- raise ValidationError(- {- "ids": ValidationError(- "You must provide at least one product id.",- code=ExportErrorCode.REQUIRED.value,- )- }- )- pks = cls.get_global_ids_or_error(ids, only_type=Product, field="ids")- return {"ids": pks}-- @staticmethod- def clean_filter(input) -> Dict[str, dict]:- filter = input.get("filter")- if not filter:- raise ValidationError(- {- "filter": ValidationError(- "You must provide filter input.",- code=ExportErrorCode.REQUIRED.value,- )- }- )- return {"filter": filter}-@classmethoddef get_export_info(cls, export_info_input):export_info = {}@@ -156,3 +164,46 @@ class ExportProducts(BaseMutation):returnpks = cls.get_global_ids_or_error(ids, only_type=graphene_type, field=field)return pks+++class ExportGiftCardsInput(graphene.InputObjectType):+ scope = ExportScope(+ description="Determine which gift cards should be exported.", required=True+ )+ filter = GiftCardFilterInput(+ description="Filtering options for gift cards.", required=False+ )+ ids = graphene.List(+ graphene.NonNull(graphene.ID),+ description="List of gift cards IDs to export.",+ required=False,+ )+ file_type = FileTypeEnum(description="Type of exported file.", required=True)+++class ExportGiftCards(BaseExportMutation):+ class Arguments:+ input = ExportGiftCardsInput(+ required=True, description="Fields required to export gift cards data."+ )++ class Meta:+ description = f"{ADDED_IN_31} Export gift cards to csv file."+ permissions = (GiftcardPermissions.MANAGE_GIFT_CARD,)+ error_type_class = ExportError++ @classmethod+ def perform_mutation(cls, root, info, **data):+ input = data["input"]+ scope = cls.get_scope(input, GiftCard)+ file_type = input["file_type"]++ app = info.context.app+ kwargs = {"app": app} if app else {"user": info.context.user}++ export_file = csv_models.ExportFile.objects.create(**kwargs)+ export_started_event(export_file=export_file, **kwargs)+ export_gift_cards_task.delay(export_file.pk, scope, file_type)++ export_file.refresh_from_db()+ return cls(export_file=export_file)diff --git a/saleor/graphql/csv/schema.py b/saleor/graphql/csv/schema.pyindex a376fc10ac..8e552898e7 100644--- a/saleor/graphql/csv/schema.py+++ b/saleor/graphql/csv/schema.py@@ -6,7 +6,7 @@ from ..core.fields import FilterConnectionFieldfrom ..core.utils import from_global_id_or_errorfrom ..decorators import permission_requiredfrom .filters import ExportFileFilterInput-from .mutations import ExportProducts+from .mutations import ExportGiftCards, ExportProductsfrom .resolvers import resolve_export_file, resolve_export_filesfrom .sorters import ExportFileSortingInputfrom .types import ExportFile, ExportFileCountableConnection@@ -41,3 +41,4 @@ class CsvQueries(graphene.ObjectType):class CsvMutations(graphene.ObjectType):export_products = ExportProducts.Field()+ export_gift_cards = ExportGiftCards.Field()diff --git a/saleor/graphql/csv/tests/mutations/test_export_gift_cards.py b/saleor/graphql/csv/tests/mutations/test_export_gift_cards.pynew file mode 100644index 0000000000..290030c97f--- /dev/null+++ b/saleor/graphql/csv/tests/mutations/test_export_gift_cards.py@@ -0,0 +1,330 @@+from unittest.mock import ANY, patch++import graphene+import pytest++from .....csv import ExportEvents+from .....csv.error_codes import ExportErrorCode+from .....csv.models import ExportEvent+from ....tests.utils import get_graphql_content+from ...enums import ExportScope, FileTypeEnum++EXPORT_GIFT_CARDS_MUTATION = """+ mutation ExportGiftCards($input: ExportGiftCardsInput!){+ exportGiftCards(input: $input){+ exportFile {+ id+ status+ createdAt+ updatedAt+ url+ user {+ }+ app {+ name+ }+ }+ errors {+ field+ code+ message+ }+ }+ }+"""+++ "input, called_data",+ [+ (+ {+ "scope": ExportScope.ALL.name,+ "fileType": FileTypeEnum.CSV.name,+ },+ {"all": ""},+ ),+ (+ {+ "scope": ExportScope.FILTER.name,+ "filter": {"tags": ["abc"]},+ "fileType": FileTypeEnum.CSV.name,+ },+ {"filter": {"tags": ["abc"]}},+ ),+ ],+)+@patch("saleor.graphql.csv.mutations.export_gift_cards_task.delay")+def test_export_gift_cards_mutation(+ export_gift_cards_mock,+ input,+ called_data,+ staff_api_client,+ gift_card,+ gift_card_expiry_date,+ permission_manage_gift_card,+ permission_manage_apps,+):+ query = EXPORT_GIFT_CARDS_MUTATION+ user = staff_api_client.user+ variables = {"input": input}++ response = staff_api_client.post_graphql(+ query,+ variables=variables,+ permissions=[permission_manage_gift_card, permission_manage_apps],+ )+ content = get_graphql_content(response)+ data = content["data"]["exportGiftCards"]+ export_file_data = data["exportFile"]++ export_gift_cards_mock.assert_called_once_with(+ ANY, called_data, FileTypeEnum.CSV.value+ )++ assert not data["errors"]+ assert data["exportFile"]["id"]+ assert export_file_data["createdAt"]+ assert export_file_data["user"]["email"] == staff_api_client.user.email+ assert export_file_data["app"] is None+ assert ExportEvent.objects.filter(+ user=user, app=None, type=ExportEvents.EXPORT_PENDING+ ).exists()+++@patch("saleor.graphql.csv.mutations.export_gift_cards_task.delay")+def test_export_gift_cards_mutation_ids_scope(+ export_gift_cards_mock,+ staff_api_client,+ gift_card,+ gift_card_expiry_date,+ gift_card_used,+ permission_manage_gift_card,+ permission_manage_apps,+ permission_manage_staff,+):+ query = EXPORT_GIFT_CARDS_MUTATION+ user = staff_api_client.user++ gift_cards = [gift_card_expiry_date, gift_card_used]++ ids = [graphene.Node.to_global_id("GiftCard", card.pk) for card in gift_cards]++ variables = {+ "input": {+ "scope": ExportScope.IDS.name,+ "ids": ids,+ "fileType": FileTypeEnum.XLSX.name,+ }+ }++ response = staff_api_client.post_graphql(+ query,+ variables=variables,+ permissions=[+ permission_manage_gift_card,+ permission_manage_apps,+ permission_manage_staff,+ ],+ )+ content = get_graphql_content(response)+ data = content["data"]["exportGiftCards"]+ export_file_data = data["exportFile"]++ export_gift_cards_mock.assert_called_once()+ (+ call_args,+ call_kwargs,+ ) = export_gift_cards_mock.call_args++ assert set(call_args[1]["ids"]) == {str(card.pk) for card in gift_cards}+ assert call_args[2] == FileTypeEnum.XLSX.value++ assert not data["errors"]+ assert data["exportFile"]["id"]+ assert export_file_data["createdAt"]+ assert export_file_data["user"]["email"] == staff_api_client.user.email+ assert export_file_data["app"] is None+ assert ExportEvent.objects.filter(+ user=user, app=None, type=ExportEvents.EXPORT_PENDING+ ).exists()+++@patch("saleor.graphql.csv.mutations.export_gift_cards_task.delay")+def test_export_gift_cards_mutation_ids_scope_invalid_object_type(+ export_gift_cards_mock,+ staff_api_client,+ gift_card,+ gift_card_expiry_date,+ gift_card_used,+ permission_manage_gift_card,+ permission_manage_apps,+ permission_manage_staff,+):+ query = EXPORT_GIFT_CARDS_MUTATION+ user = staff_api_client.user++ gift_cards = [gift_card_expiry_date, gift_card_used]++ ids = [graphene.Node.to_global_id("Product", card.pk) for card in gift_cards]++ variables = {+ "input": {+ "scope": ExportScope.IDS.name,+ "ids": ids,+ "fileType": FileTypeEnum.CSV.name,+ }+ }++ response = staff_api_client.post_graphql(+ query,+ variables=variables,+ permissions=[+ permission_manage_gift_card,+ permission_manage_apps,+ permission_manage_staff,+ ],+ )+ content = get_graphql_content(response)+ data = content["data"]["exportGiftCards"]++ errors = data["errors"]+ assert len(errors) == 1+ assert not data["exportFile"]+ assert errors[0]["field"] == "ids"+ assert errors[0]["code"] == ExportErrorCode.GRAPHQL_ERROR.name++ assert not ExportEvent.objects.filter(+ user=user, app=None, type=ExportEvents.EXPORT_PENDING+ )++ export_gift_cards_mock.assert_not_called()+++ "input, error_field",+ [+ (+ {+ "scope": ExportScope.FILTER.name,+ "fileType": FileTypeEnum.CSV.name,+ },+ "filter",+ ),+ (+ {+ "scope": ExportScope.IDS.name,+ "fileType": FileTypeEnum.CSV.name,+ },+ "ids",+ ),+ ],+)+@patch("saleor.graphql.csv.mutations.export_gift_cards_task.delay")+def test_export_gift_cards_mutation_failed(+ export_gift_cards_mock,+ input,+ error_field,+ app_api_client,+ gift_card,+ gift_card_expiry_date,+ permission_manage_gift_card,+ permission_manage_apps,+ permission_manage_staff,+):+ query = EXPORT_GIFT_CARDS_MUTATION+ app = app_api_client.app++ variables = {"input": input}++ response = app_api_client.post_graphql(+ query,+ variables=variables,+ permissions=[+ permission_manage_gift_card,+ permission_manage_apps,+ permission_manage_staff,+ ],+ )+ content = get_graphql_content(response)+ data = content["data"]["exportGiftCards"]++ errors = data["errors"]+ assert len(errors) == 1+ assert not data["exportFile"]+ assert errors[0]["field"] == error_field+ assert errors[0]["code"] == ExportErrorCode.REQUIRED.name++ assert not ExportEvent.objects.filter(+ user=None, app=app, type=ExportEvents.EXPORT_PENDING+ )++ export_gift_cards_mock.assert_not_called()+++EXPORT_GIFT_CARDS_MUTATION_BY_APP = """+ mutation ExportGiftCards($input: ExportGiftCardsInput!){+ exportGiftCards(input: $input){+ exportFile {+ id+ status+ createdAt+ updatedAt+ url+ app {+ name+ }+ }+ errors {+ field+ code+ message+ }+ }+ }+"""+++@patch("saleor.graphql.csv.mutations.export_gift_cards_task.delay")+def test_export_gift_cards_mutation_by_app(+ export_gift_cards_mock,+ app_api_client,+ gift_card,+ gift_card_expiry_date,+ permission_manage_gift_card,+ permission_manage_apps,+ permission_manage_staff,+):+ query = EXPORT_GIFT_CARDS_MUTATION_BY_APP+ app = app_api_client.app+ variables = {+ "input": {+ "scope": ExportScope.ALL.name,+ "fileType": FileTypeEnum.XLSX.name,+ }+ }++ response = app_api_client.post_graphql(+ query,+ variables=variables,+ permissions=[+ permission_manage_gift_card,+ permission_manage_apps,+ ],+ )+ content = get_graphql_content(response)+ data = content["data"]["exportGiftCards"]+ export_file_data = data["exportFile"]++ export_gift_cards_mock.assert_called_once_with(+ ANY, {"all": ""}, FileTypeEnum.XLSX.value+ )++ assert not data["errors"]+ assert data["exportFile"]["id"]+ assert export_file_data["createdAt"]+ assert export_file_data["app"]["name"] == app.name+ assert ExportEvent.objects.filter(+ user=None, app=app, type=ExportEvents.EXPORT_PENDING+ ).exists()diff --git a/saleor/graphql/giftcard/bulk_mutations.py b/saleor/graphql/giftcard/bulk_mutations.pyindex 13b7dfff9b..c27a2ed5ce 100644--- a/saleor/graphql/giftcard/bulk_mutations.py+++ b/saleor/graphql/giftcard/bulk_mutations.py@@ -1,11 +1,151 @@+from typing import Iterable+import graphene+from django.core.exceptions import ValidationErrorfrom ...core.permissions import GiftcardPermissionsfrom ...core.tracing import traced_atomic_transaction+from ...core.utils.promo_code import generate_promo_code+from ...core.utils.validators import is_date_in_futurefrom ...giftcard import events, models+from ...giftcard.error_codes import GiftCardErrorCode+from ...giftcard.utils import is_gift_card_expiredfrom ..core.descriptions import ADDED_IN_31-from ..core.mutations import BaseBulkMutation, ModelBulkDeleteMutation-from ..core.types.common import GiftCardError+from ..core.mutations import BaseBulkMutation, BaseMutation, ModelBulkDeleteMutation+from ..core.types.common import GiftCardError, PriceInput+from ..core.validators import validate_price_precision+from .mutations import GiftCardCreate+from .types import GiftCard+++class GiftCardBulkCreateInput(graphene.InputObjectType):+ count = graphene.Int(required=True, description="The number of cards to issue.")+ balance = graphene.Field(+ PriceInput, description="Balance of the gift card.", required=True+ )+ tags = graphene.List(+ graphene.NonNull(graphene.String),+ description="The gift card tags.",+ )+ expiry_date = graphene.types.datetime.Date(description="The gift card expiry date.")+ is_active = graphene.Boolean(+ required=True, description="Determine if gift card is active."+ )+++class GiftCardBulkCreate(BaseMutation):+ count = graphene.Int(+ required=True,+ default_value=0,+ description="Returns how many objects were created.",+ )+ gift_cards = graphene.List(+ graphene.NonNull(GiftCard),+ required=True,+ default_value=[],+ description="List of created gift cards.",+ )++ class Arguments:+ input = GiftCardBulkCreateInput(+ required=True, description="Fields required to create gift cards."+ )++ class Meta:+ description = f"{ADDED_IN_31} Create gift cards."+ model = models.GiftCard+ permissions = (GiftcardPermissions.MANAGE_GIFT_CARD,)+ error_type_class = GiftCardError++ @classmethod+ @traced_atomic_transaction()+ def perform_mutation(cls, _root, info, **data):+ input_data = data["input"]+ cls.clean_count_value(input_data)+ cls.clean_expiry_date(input_data)+ cls.clean_balance(input_data)+ GiftCardCreate.set_created_by_user(input_data, info)+ tags = input_data.pop("tags", None)+ instances = cls.create_instances(input_data, info)+ if tags:+ cls.assign_gift_card_tags(instances, tags)+ return cls(count=len(instances), gift_cards=instances)++ @staticmethod+ def clean_count_value(input_data):+ if not input_data["count"] > 0:+ raise ValidationError(+ {+ "count": ValidationError(+ "Count value must be greater than 0.",+ code=GiftCardErrorCode.INVALID.value,+ )+ }+ )++ @staticmethod+ def clean_expiry_date(input_data):+ expiry_date = input_data.get("expiry_date")+ if expiry_date and not is_date_in_future(expiry_date):+ raise ValidationError(+ {+ "expiry_date": ValidationError(+ "Expiry date cannot be in the past.",+ code=GiftCardErrorCode.INVALID.value,+ )+ }+ )++ @staticmethod+ def clean_balance(cleaned_input):+ balance = cleaned_input["balance"]+ amount = balance["amount"]+ currency = balance["currency"]+ try:+ validate_price_precision(amount, currency)+ except ValidationError as error:+ error.code = GiftCardErrorCode.INVALID.value+ raise ValidationError({"balance": error})+ if not amount > 0:+ raise ValidationError(+ {+ "balance": ValidationError(+ "Balance amount have to be greater than 0.",+ code=GiftCardErrorCode.INVALID.value,+ )+ }+ )+ cleaned_input["currency"] = currency+ cleaned_input["current_balance_amount"] = amount+ cleaned_input["initial_balance_amount"] = amount++ @staticmethod+ def create_instances(cleaned_input, info):+ count = cleaned_input.pop("count")+ balance = cleaned_input.pop("balance")+ gift_cards = models.GiftCard.objects.bulk_create(+ [+ models.GiftCard(code=generate_promo_code(), **cleaned_input)+ for _ in range(count)+ ]+ )+ events.gift_cards_issued_event(+ gift_cards, info.context.user, info.context.app, balance+ )+ return gift_cards++ @staticmethod+ def assign_gift_card_tags(+ instances: Iterable[models.GiftCard], tags_values: Iterable[str]+ ):+ tags = {tag.lower() for tag in tags_values}+ tags_instances = models.GiftCardTag.objects.filter(name__in=tags)+ tags_to_create = tags - set(tags_instances.values_list("name", flat=True))+ models.GiftCardTag.objects.bulk_create(+ [models.GiftCardTag(name=tag) for tag in tags_to_create]+ )+ for tag_instance in tags_instances.iterator():+ tag_instance.gift_cards.set(instances)class GiftCardBulkDelete(ModelBulkDeleteMutation):@@ -33,6 +173,14 @@ class GiftCardBulkActivate(BaseBulkMutation):permissions = (GiftcardPermissions.MANAGE_GIFT_CARD,)error_type_class = GiftCardError+ @classmethod+ def clean_instance(cls, info, instance):+ if is_gift_card_expired(instance):+ raise ValidationError(+ "Cannot activate expired card.",+ code=GiftCardErrorCode.EXPIRED_GIFT_CARD,+ )+@classmethod@traced_atomic_transaction()def bulk_action(cls, info, queryset):diff --git a/saleor/graphql/giftcard/dataloaders.py b/saleor/graphql/giftcard/dataloaders.pyindex 8627552f7c..a57987d5f7 100644--- a/saleor/graphql/giftcard/dataloaders.py+++ b/saleor/graphql/giftcard/dataloaders.py@@ -1,6 +1,6 @@from collections import defaultdict-from ...giftcard.models import GiftCard, GiftCardEvent+from ...giftcard.models import GiftCard, GiftCardEvent, GiftCardTagfrom ..core.dataloaders import DataLoader@@ -24,3 +24,22 @@ class GiftCardEventsByGiftCardIdLoader(DataLoader):for event in events.iterator():events_map[event.gift_card_id].append(event)return [events_map.get(gift_card_id, []) for gift_card_id in keys]+++class GiftCardTagsByGiftCardIdLoader(DataLoader):+ context_key = "giftcardtags_by_giftcard"++ def batch_load(self, keys):+ gift_card_gift_card_tags = GiftCard.tags.through.objects.filter(+ giftcard_id__in=keys+ )+ tags_ids = [+ gift_card_tag.giftcardtag_id for gift_card_tag in gift_card_gift_card_tags+ ]+ tags = GiftCardTag.objects.in_bulk(tags_ids)+ tags_map = defaultdict(list)+ for gift_card_tag in gift_card_gift_card_tags:+ tags_map[gift_card_tag.giftcard_id].append(+ tags[gift_card_tag.giftcardtag_id]+ )+ return [tags_map.get(gift_card_id, []) for gift_card_id in keys]diff --git a/saleor/graphql/giftcard/filters.py b/saleor/graphql/giftcard/filters.pyindex 47636ab8de..d24aa18394 100644--- a/saleor/graphql/giftcard/filters.py+++ b/saleor/graphql/giftcard/filters.py@@ -1,3 +1,5 @@+from typing import List+import django_filtersimport graphenefrom django.db.models import Exists, OuterRef@@ -7,25 +9,16 @@ from graphql.error import GraphQLErrorfrom ...account import models as account_modelsfrom ...giftcard import modelsfrom ...product import models as product_models-from ..account import types as account_typesfrom ..core.filters import ListObjectTypeFilter, MetadataFilterBase, ObjectTypeFilterfrom ..core.types import FilterInputObjectTypefrom ..core.types.common import PriceRangeInput-from ..product.types import products as product_typesfrom ..utils import resolve_global_ids_to_primary_keys---def filter_gift_card_tag(qs, _, value):- if not value:- return qs- return qs.filter(tag__ilike=value)+from .enums import GiftCardEventsEnumdef filter_products(qs, _, value):if value:- _, product_pks = resolve_global_ids_to_primary_keys(- value, product_types.Product- )+ _, product_pks = resolve_global_ids_to_primary_keys(value, "Product")qs = filter_gift_cards_by_products(qs, product_pks)return qs@@ -37,7 +30,7 @@ def filter_gift_cards_by_products(qs, product_ids):def filter_used_by(qs, _, value):if value:- _, user_pks = resolve_global_ids_to_primary_keys(value, account_types.User)+ _, user_pks = resolve_global_ids_to_primary_keys(value, "User")qs = filter_gift_cards_by_used_by_user(qs, user_pks)return qs@@ -50,7 +43,14 @@ def filter_gift_cards_by_used_by_user(qs, user_pks):def filter_tags_list(qs, _, value):if not value:return qs- return qs.filter(tag__in=value)+ tags = models.GiftCardTag.objects.filter(name__in=value)+ return qs.filter(Exists(tags.filter(pk=OuterRef("tags__id"))))+++def filter_gift_card_used(qs, _, value):+ if value is None:+ return qs+ return qs.filter(used_by_email__isnull=not value)def filter_currency(qs, _, value):@@ -75,10 +75,10 @@ def filter_code(qs, _, value):class GiftCardFilter(MetadataFilterBase):- tag = django_filters.CharFilter(method=filter_gift_card_tag)tags = ListObjectTypeFilter(input_class=graphene.String, method=filter_tags_list)products = GlobalIDMultipleChoiceFilter(method=filter_products)used_by = GlobalIDMultipleChoiceFilter(method=filter_used_by)+ used = django_filters.BooleanFilter(method=filter_gift_card_used)currency = django_filters.CharFilter(method=filter_currency)current_balance = ObjectTypeFilter(input_class=PriceRangeInput, method="filter_current_balance"@@ -113,3 +113,40 @@ def check_currency_in_filter_data(filter_data: dict):class GiftCardFilterInput(FilterInputObjectType):class Meta:filterset_class = GiftCardFilter+++def filter_events_by_type(events: List[models.GiftCardEvent], type_value: str):+ filtered_events = []+ for event in events:+ if event.type == type_value:+ filtered_events.append(event)+ return filtered_events+++def filter_events_by_orders(events: List[models.GiftCardEvent], order_ids: List[str]):+ _, order_pks = resolve_global_ids_to_primary_keys(order_ids, "Order")+ filtered_events = []+ for event in events:+ if str(event.parameters.get("order_id")) in order_pks:+ filtered_events.append(event)+ return filtered_events+++class GiftCardEventFilterInput(graphene.InputObjectType):+ type = graphene.Argument(GiftCardEventsEnum)+ orders = graphene.List(graphene.NonNull(graphene.ID))+++def filter_gift_card_tag_search(qs, _, value):+ if not value:+ return qs+ return qs.filter(name__ilike=value)+++class GiftCardTagFilter(django_filters.FilterSet):+ search = django_filters.CharFilter(method=filter_gift_card_tag_search)+++class GiftCardTagFilterInput(FilterInputObjectType):+ class Meta:+ filterset_class = GiftCardTagFilterdiff --git a/saleor/graphql/giftcard/mutations.py b/saleor/graphql/giftcard/mutations.pyindex b1f0d7af1a..65f336c1a9 100644--- a/saleor/graphql/giftcard/mutations.py+++ b/saleor/graphql/giftcard/mutations.py@@ -1,4 +1,5 @@from copy import deepcopy+from typing import Iterableimport graphenefrom django.core.exceptions import ValidationError@@ -6,23 +7,44 @@ from django.core.validators import validate_emailfrom ...account.models import Userfrom ...core.permissions import GiftcardPermissions+from ...core.tracing import traced_atomic_transactionfrom ...core.utils.promo_code import generate_promo_codefrom ...core.utils.validators import is_date_in_future, user_is_validfrom ...giftcard import events, modelsfrom ...giftcard.error_codes import GiftCardErrorCodefrom ...giftcard.notifications import send_gift_card_notification-from ...giftcard.utils import activate_gift_card, deactivate_gift_card+from ...giftcard.utils import (+ activate_gift_card,+ deactivate_gift_card,+ is_gift_card_expired,+)from ..core.descriptions import ADDED_IN_31, DEPRECATED_IN_3X_INPUTfrom ..core.mutations import BaseMutation, ModelDeleteMutation, ModelMutationfrom ..core.scalars import PositiveDecimalfrom ..core.types.common import GiftCardError, PriceInputfrom ..core.utils import validate_required_string_fieldfrom ..core.validators import validate_price_precision+from ..utils.validators import check_for_duplicatesfrom .types import GiftCard, GiftCardEvent+def clean_gift_card(gift_card: GiftCard):+ if is_gift_card_expired(gift_card):+ raise ValidationError(+ {+ "id": ValidationError(+ "Expired gift card cannot be activated and resend.",+ code=GiftCardErrorCode.EXPIRED_GIFT_CARD.value,+ )+ }+ )++class GiftCardInput(graphene.InputObjectType):- tag = graphene.String(description=f"{ADDED_IN_31} The gift card tag.")+ add_tags = graphene.List(+ graphene.NonNull(graphene.String),+ description=f"{ADDED_IN_31} The gift card tags to add.",+ )expiry_date = graphene.types.datetime.Date(description=f"{ADDED_IN_31} The gift card expiry date.")@@ -70,6 +92,10 @@ class GiftCardCreateInput(GiftCardInput):class GiftCardUpdateInput(GiftCardInput):+ remove_tags = graphene.List(+ graphene.NonNull(graphene.String),+ description=f"{ADDED_IN_31} The gift card tags to remove.",+ )balance_amount = PositiveDecimal(description=f"{ADDED_IN_31} The gift card balance amount.", required=False)@@ -134,8 +160,8 @@ class GiftCardCreate(ModelMutation):cleaned_input["created_by_email"] = user.emailcleaned_input["app"] = info.context.app- @staticmethod- def clean_expiry_date(cleaned_input, instance):+ @classmethod+ def clean_expiry_date(cls, cleaned_input, instance):expiry_date = cleaned_input.get("expiry_date")if expiry_date and not is_date_in_future(expiry_date):raise ValidationError(@@ -206,6 +232,26 @@ class GiftCardCreate(ModelMutation):resending=False,)+ @staticmethod+ def assign_gift_card_tags(instance: models.GiftCard, tags_values: Iterable[str]):+ add_tags = {tag.lower() for tag in tags_values}+ add_tags_instances = models.GiftCardTag.objects.filter(name__in=add_tags)+ tags_to_create = add_tags - set(+ add_tags_instances.values_list("name", flat=True)+ )+ models.GiftCardTag.objects.bulk_create(+ [models.GiftCardTag(name=tag) for tag in tags_to_create]+ )+ instance.tags.add(*add_tags_instances)++ @classmethod+ @traced_atomic_transaction()+ def _save_m2m(cls, info, instance, cleaned_data):+ super()._save_m2m(info, instance, cleaned_data)+ tags = cleaned_data.get("add_tags")+ if tags:+ cls.assign_gift_card_tags(instance, tags)+class GiftCardUpdate(GiftCardCreate):class Arguments:@@ -221,6 +267,13 @@ class GiftCardUpdate(GiftCardCreate):error_type_class = GiftCardErrorerror_type_field = "gift_card_errors"+ @classmethod+ def clean_expiry_date(cls, cleaned_input, instance):+ super().clean_expiry_date(cleaned_input, instance)+ expiry_date = cleaned_input.get("expiry_date")+ if expiry_date and expiry_date == instance.expiry_date:+ del cleaned_input["expiry_date"]+@staticmethoddef clean_balance(cleaned_input, instance):amount = cleaned_input.pop("balance_amount", None)@@ -237,32 +290,66 @@ class GiftCardUpdate(GiftCardCreate):cleaned_input["current_balance_amount"] = amountcleaned_input["initial_balance_amount"] = amount+ @staticmethod+ def clean_tags(cleaned_input):+ error = check_for_duplicates(cleaned_input, "add_tags", "remove_tags", "tags")+ if error:+ error.code = GiftCardErrorCode.DUPLICATED_INPUT_ITEM.value+ raise ValidationError({"tags": error})+@classmethoddef perform_mutation(cls, _root, info, **data):instance = cls.get_instance(info, **data)+old_instance = deepcopy(instance)data = data.get("input")cleaned_input = cls.clean_input(info, instance, data)++ tags_updated = "add_tags" in cleaned_input or "remove_tags" in cleaned_input+ if tags_updated:+ old_tags = list(+ old_instance.tags.order_by("name").values_list("name", flat=True)+ )+instance = cls.construct_instance(instance, cleaned_input)cls.clean_instance(info, instance)cls.save(info, instance, cleaned_input)+ cls._save_m2m(info, instance, cleaned_input)+ user = info.context.user+ app = info.context.appif "initial_balance_amount" in cleaned_input:- events.gift_card_balance_reset_event(- instance, old_instance, info.context.user, info.context.app- )+ events.gift_card_balance_reset_event(instance, old_instance, user, app)if "expiry_date" in cleaned_input:events.gift_card_expiry_date_updated_event(- instance, old_instance, info.context.user, info.context.app- )- if "tag" in cleaned_input:- events.gift_card_tag_updated_event(- instance, old_instance, info.context.user, info.context.app+ instance, old_instance, user, app)+ if tags_updated:+ events.gift_card_tags_updated_event(instance, old_tags, user, app)return cls.success_response(instance)+ @classmethod+ def clean_input(cls, info, instance, data):+ cleaned_input = super().clean_input(info, instance, data)+ cls.clean_tags(cleaned_input)+ return cleaned_input++ @classmethod+ @traced_atomic_transaction()+ def _save_m2m(cls, info, instance, cleaned_data):+ super()._save_m2m(info, instance, cleaned_data)+ remove_tags = cleaned_data.get("remove_tags")+ if remove_tags:+ remove_tags = {tag.lower() for tag in remove_tags}+ remove_tags_instances = models.GiftCardTag.objects.filter(+ name__in=remove_tags+ )+ instance.tags.remove(*remove_tags_instances)+ # delete tags without gift card assigned+ remove_tags_instances.filter(gift_cards__isnull=True).delete()+class GiftCardDelete(ModelDeleteMutation):class Arguments:@@ -322,6 +409,7 @@ class GiftCardActivate(BaseMutation):gift_card = cls.get_node_or_error(info, gift_card_id, field="gift_card_id", only_type=GiftCard)+ clean_gift_card(gift_card)# create event only when is_active value has changedcreate_event = not gift_card.is_activeactivate_gift_card(gift_card)@@ -391,6 +479,7 @@ class GiftCardResend(BaseMutation):gift_card = cls.get_node_or_error(info, gift_card_id, field="gift_card_id", only_type=GiftCard)+ clean_gift_card(gift_card)target_email = cls.get_target_email(data, gift_card)customer_user = cls.get_customer_user(target_email)user = info.context.userdiff --git a/saleor/graphql/giftcard/resolvers.py b/saleor/graphql/giftcard/resolvers.pyindex 518e90c0d8..beeadfcf0b 100644--- a/saleor/graphql/giftcard/resolvers.py+++ b/saleor/graphql/giftcard/resolvers.py@@ -7,3 +7,7 @@ def resolve_gift_card(id):def resolve_gift_cards():return models.GiftCard.objects.all()+++def resolve_gift_card_tags():+ return models.GiftCardTag.objects.all()diff --git a/saleor/graphql/giftcard/schema.py b/saleor/graphql/giftcard/schema.pyindex a20a921b64..1c95117dcc 100644--- a/saleor/graphql/giftcard/schema.py+++ b/saleor/graphql/giftcard/schema.py@@ -10,10 +10,11 @@ from ..core.utils import from_global_id_or_errorfrom ..decorators import permission_requiredfrom .bulk_mutations import (GiftCardBulkActivate,+ GiftCardBulkCreate,GiftCardBulkDeactivate,GiftCardBulkDelete,)-from .filters import GiftCardFilterInput+from .filters import GiftCardFilterInput, GiftCardTagFilterInputfrom .mutations import (GiftCardActivate,GiftCardAddNote,@@ -23,9 +24,9 @@ from .mutations import (GiftCardResend,GiftCardUpdate,)-from .resolvers import resolve_gift_card, resolve_gift_cards+from .resolvers import resolve_gift_card, resolve_gift_card_tags, resolve_gift_cardsfrom .sorters import GiftCardSortingInput-from .types import GiftCard, GiftCardCountableConnection+from .types import GiftCard, GiftCardCountableConnection, GiftCardTagCountableConnectionclass GiftCardQueries(graphene.ObjectType):@@ -49,6 +50,13 @@ class GiftCardQueries(graphene.ObjectType):description=f"{ADDED_IN_31} List of gift card currencies.",required=True,)+ gift_card_tags = FilterConnectionField(+ GiftCardTagCountableConnection,+ filter=GiftCardTagFilterInput(+ description="Filtering options for gift card tags."+ ),+ description="{ADDED_IN_31} List of gift card tags.",+ )@permission_required(GiftcardPermissions.MANAGE_GIFT_CARD)def resolve_gift_card(self, info, **data):@@ -71,6 +79,12 @@ class GiftCardQueries(graphene.ObjectType):def resolve_gift_card_currencies(self, info, **data):return set(models.GiftCard.objects.values_list("currency", flat=True))+ @permission_required(GiftcardPermissions.MANAGE_GIFT_CARD)+ def resolve_gift_card_tags(self, info, **data):+ qs = resolve_gift_card_tags()+ qs = filter_connection_queryset(qs, data)+ return create_connection_slice(qs, info, data, GiftCardTagCountableConnection)+class GiftCardMutations(graphene.ObjectType):gift_card_activate = GiftCardActivate.Field()@@ -81,6 +95,7 @@ class GiftCardMutations(graphene.ObjectType):gift_card_resend = GiftCardResend.Field()gift_card_add_note = GiftCardAddNote.Field()+ gift_card_bulk_create = GiftCardBulkCreate.Field()gift_card_bulk_delete = GiftCardBulkDelete.Field()gift_card_bulk_activate = GiftCardBulkActivate.Field()gift_card_bulk_deactivate = GiftCardBulkDeactivate.Field()diff --git a/saleor/graphql/giftcard/sorters.py b/saleor/graphql/giftcard/sorters.pyindex 62b7d1438d..68e5b831d3 100644--- a/saleor/graphql/giftcard/sorters.py+++ b/saleor/graphql/giftcard/sorters.py@@ -4,7 +4,6 @@ from ..core.types import SortInputObjectTypeclass GiftCardSortField(graphene.Enum):- TAG = ["tag"]PRODUCT = ["product__name", "product__slug"]USED_BY = ["used_by__first_name", "used_by__last_name", "created"]CURRENT_BALANCE = ["current_balance_amount", "created"]diff --git a/saleor/graphql/giftcard/tests/benchmark/fixtures.py b/saleor/graphql/giftcard/tests/benchmark/fixtures.pyindex 90d73a6ceb..d1b68bc800 100644--- a/saleor/graphql/giftcard/tests/benchmark/fixtures.py+++ b/saleor/graphql/giftcard/tests/benchmark/fixtures.py@@ -4,7 +4,7 @@ import pytestfrom prices import Moneyfrom .....giftcard import GiftCardEvents-from .....giftcard.models import GiftCard, GiftCardEvent+from .....giftcard.models import GiftCard, GiftCardEvent, GiftCardTagGIFT_CARD_COUNT_IN_BENCHMARKS = 20@@ -23,11 +23,12 @@ def gift_cards_for_benchmarks(created_by_email=customer_user.email,initial_balance=Money(10, "USD"),current_balance=Money(10, "USD"),- tag="test-tag",)for _ in range(GIFT_CARD_COUNT_IN_BENCHMARKS)]created_gift_cards = GiftCard.objects.bulk_create(gift_cards)+ tag = GiftCardTag.objects.create(name="benchmark-test-tag")+ tag.gift_cards.add(*created_gift_cards)parameters = {"message": "test message",diff --git a/saleor/graphql/giftcard/tests/benchmark/test_gift_card_mutations.py b/saleor/graphql/giftcard/tests/benchmark/test_gift_card_mutations.pyindex 8ec0783591..3ba9b80d36 100644--- a/saleor/graphql/giftcard/tests/benchmark/test_gift_card_mutations.py+++ b/saleor/graphql/giftcard/tests/benchmark/test_gift_card_mutations.py@@ -5,73 +5,22 @@ import pytestfrom .....giftcard.models import GiftCardfrom ....tests.utils import get_graphql_content+from .test_gift_card_queries import FRAGMENT_GIFT_CARD_DETAILS-CREATE_GIFT_CARD_MUTATION = """+CREATE_GIFT_CARD_MUTATION = (+ FRAGMENT_GIFT_CARD_DETAILS+ + """mutation giftCardCreate(- $balance: PriceInput!, $userEmail: String, $tag: String, $channel: String,- $note: String, $expiryDate: Date, $isActive: Boolean!+ $balance: PriceInput!, $userEmail: String, $addTags: [String!],+ $channel: String, $note: String, $expiryDate: Date, $isActive: Boolean!){giftCardCreate(input: {- balance: $balance, userEmail: $userEmail, tag: $tag, channel: $channel,- expiryDate: $expiryDate, note: $note, isActive: $isActive }) {+ balance: $balance, userEmail: $userEmail, addTags: $addTags,+ channel: $channel, expiryDate: $expiryDate, note: $note,+ isActive: $isActive+ }) {giftCard {- id- code- displayCode- isActive- expiryDate- tag- created- lastUsedOn- initialBalance {- currency- amount- }- currentBalance {- currency- amount- }- createdBy {- }- usedBy {- }- createdByEmail- usedByEmail- app {- name- }- product {- name- }- events {- type- user {- }- app {- name- }- balance {- initialBalance {- amount- currency- }- oldInitialBalance {- amount- currency- }- currentBalance {- amount- currency- }- oldCurrentBalance {- amount- currency- }- }- }+ ...GiftCardDetails}errors {field@@ -81,6 +30,7 @@ CREATE_GIFT_CARD_MUTATION = """}}"""+)@pytest.mark.django_db@@ -105,7 +55,7 @@ def test_create_never_expiry_gift_card(},"userEmail": customer_user.email,"channel": channel_USD.slug,- "tag": tag,+ "addTags": [tag],"note": "This is gift card note that will be save in gift card event.","expiry_date": None,"isActive": True,@@ -129,71 +79,15 @@ def test_create_never_expiry_gift_card(assert data-UPDATE_GIFT_CARD_MUTATION = """+UPDATE_GIFT_CARD_MUTATION = (+ FRAGMENT_GIFT_CARD_DETAILS+ + """mutation giftCardUpdate($id: ID!, $input: GiftCardUpdateInput!){giftCardUpdate(id: $id, input: $input) {giftCard {- id- code- displayCode- isActive- expiryDate- tag- created- lastUsedOn- initialBalance {- currency- amount- }- currentBalance {- currency- amount- }- createdBy {- }- usedBy {- }- createdByEmail- usedByEmail- app {- name- }- product {- name- }- events {- type- user {- }- app {- name- }- balance {- initialBalance {- amount- currency- }- oldInitialBalance {- amount- currency- }- currentBalance {- amount- currency- }- oldCurrentBalance {- amount- currency- }- }- expiryDate- oldExpiryDate- }+ ...GiftCardDetails}errors {field@@ -203,6 +97,7 @@ UPDATE_GIFT_CARD_MUTATION = """}}"""+)@pytest.mark.django_db@@ -218,12 +113,14 @@ def test_update_gift_card(# giveninitial_balance = 100.0date_value = date.today() + timedelta(days=365)+ old_tag = gift_card.tags.first()tag = "new-gift-card-tag"variables = {"id": graphene.Node.to_global_id("GiftCard", gift_card.pk),"input": {"balanceAmount": initial_balance,- "tag": tag,+ "addTags": [tag],+ "removeTags": [old_tag.name],"expiryDate": date_value,},}@@ -287,3 +184,62 @@ def test_gift_card_bulk_activate_by_staff(# thencontent = get_graphql_content(response)assert content["data"]["giftCardBulkActivate"]["count"] == len(ids)+++MUTATION_GIFT_CARD_BULK_CREATE = (+ FRAGMENT_GIFT_CARD_DETAILS+ + """+ mutation GiftCardBulkCreate($input: GiftCardBulkCreateInput!) {+ giftCardBulkCreate(input: $input) {+ count+ giftCards {+ ...GiftCardDetails+ }+ errors {+ code+ field+ }+ }+ }+"""+)+++def test_bulk_create_gift_cards(+ staff_api_client,+ permission_manage_gift_card,+ permission_manage_users,+ permission_manage_apps,+):+ # given+ initial_balance = 100+ currency = "USD"+ tag = "gift-card-tag"+ count = 10+ is_active = True+ variables = {+ "input": {+ "count": count,+ "balance": {+ "amount": initial_balance,+ "currency": currency,+ },+ "tags": [tag],+ "isActive": is_active,+ }+ }++ # when+ response = staff_api_client.post_graphql(+ MUTATION_GIFT_CARD_BULK_CREATE,+ variables,+ permissions=(+ permission_manage_gift_card,+ permission_manage_users,+ permission_manage_apps,+ ),+ )++ # then+ content = get_graphql_content(response)+ assert content["data"]["giftCardBulkCreate"]["count"] == countdiff --git a/saleor/graphql/giftcard/tests/benchmark/test_gift_card_queries.py b/saleor/graphql/giftcard/tests/benchmark/test_gift_card_queries.pyindex 57fa521fd7..f99aa8d0e1 100644--- a/saleor/graphql/giftcard/tests/benchmark/test_gift_card_queries.py+++ b/saleor/graphql/giftcard/tests/benchmark/test_gift_card_queries.py@@ -19,8 +19,8 @@ FRAGMENT_EVENTS = """orderIdorderNumber- tag- oldTag+ tags+ oldTagsbalance {initialBalance {amount@@ -50,10 +50,12 @@ FRAGMENT_GIFT_CARD_DETAILS = (fragment GiftCardDetails on GiftCard {idcode- displayCode+ last4CodeCharsisActiveexpiryDate- tag+ tags {+ name+ }createdlastUsedOnboughtInChannel@@ -168,7 +170,7 @@ def test_query_gift_cards(@pytest.mark.django_db@pytest.mark.count_queries(autouse=False)-def test_filter_gift_cards_by_tag(+def test_filter_gift_cards_by_tags(staff_api_client,gift_cards_for_benchmarks,permission_manage_gift_card,@@ -193,7 +195,7 @@ def test_filter_gift_cards_by_tag(content = get_graphql_content(staff_api_client.post_graphql(query,- {"filter": {"tag": "tag"}},+ {"filter": {"tags": ["benchmark-test-tag"]}},permissions=[permission_manage_gift_card,permission_manage_apps,diff --git a/saleor/graphql/giftcard/tests/deprecated/test_gift_card_mutations.py b/saleor/graphql/giftcard/tests/deprecated/test_gift_card_mutations.pyindex b164a16377..267e0a9a3d 100644--- a/saleor/graphql/giftcard/tests/deprecated/test_gift_card_mutations.py+++ b/saleor/graphql/giftcard/tests/deprecated/test_gift_card_mutations.py@@ -16,12 +16,14 @@ CREATE_GIFT_CARD_MUTATION = """giftCard {idcode- displayCode+ last4CodeCharsisActivestartDateendDateexpiryDate- tag+ tags {+ name+ }createdlastUsedOninitialBalance {@@ -67,7 +69,7 @@ def test_create_never_expiry_gift_card(},"userEmail": customer_user.email,"channel": channel_USD.slug,- "tag": tag,+ "tags": [tag],"note": "This is gift card note that will be save in gift card event.","startDate": start_date.isoformat(),"endDate": end_date.isoformat(),@@ -87,7 +89,7 @@ def test_create_never_expiry_gift_card(data = content["data"]["giftCardCreate"]["giftCard"]assert not errors- assert data["displayCode"]+ assert data["last4CodeChars"]assert data["user"]["email"] == staff_api_client.user.emailassert data["startDate"] is Noneassert data["endDate"] is Nonediff --git a/saleor/graphql/giftcard/tests/deprecated/test_gift_card_query.py b/saleor/graphql/giftcard/tests/deprecated/test_gift_card_query.pyindex e9a874fcbd..b25455c1e3 100644--- a/saleor/graphql/giftcard/tests/deprecated/test_gift_card_query.py+++ b/saleor/graphql/giftcard/tests/deprecated/test_gift_card_query.py@@ -9,7 +9,7 @@ QUERY_GIFT_CARD_BY_ID = """giftCard(id: $id){idcode- displayCode+ last4CodeCharsuser {}@@ -41,7 +41,7 @@ def test_query_gift_card(content = get_graphql_content(response)data = content["data"]["giftCard"]assert data["id"] == gift_card_id- assert data["displayCode"] == gift_card.display_code+ assert data["last4CodeChars"] == gift_card.display_codeassert data["user"]["email"] == gift_card.created_by.emailassert data["endDate"] == end_date.isoformat()assert data["startDate"] is Nonediff --git a/saleor/graphql/giftcard/tests/mutations/test_gift_card_activate.py b/saleor/graphql/giftcard/tests/mutations/test_gift_card_activate.pyindex 5cf42a3696..01859cce5e 100644--- a/saleor/graphql/giftcard/tests/mutations/test_gift_card_activate.py+++ b/saleor/graphql/giftcard/tests/mutations/test_gift_card_activate.py@@ -1,6 +1,9 @@+from datetime import date, timedelta+import graphenefrom .....giftcard import GiftCardEvents+from .....giftcard.error_codes import GiftCardErrorCodefrom ....tests.utils import assert_no_permission, get_graphql_contentACTIVATE_GIFT_CARD_MUTATION = """@@ -8,6 +11,7 @@ ACTIVATE_GIFT_CARD_MUTATION = """giftCardActivate(id: $id) {errors {field+ codemessage}giftCard {@@ -139,3 +143,39 @@ def test_activate_active_gift_card(data = content["data"]["giftCardActivate"]["giftCard"]assert data["isActive"]assert not data["events"]+++def test_activate_expired_gift_card(+ staff_api_client,+ gift_card,+ permission_manage_gift_card,+ permission_manage_users,+ permission_manage_apps,+):+ # given+ gift_card.is_active = False+ gift_card.expiry_date = date.today() - timedelta(days=1)+ gift_card.save(update_fields=["expiry_date", "is_active"])++ variables = {"id": graphene.Node.to_global_id("GiftCard", gift_card.id)}++ # when+ response = staff_api_client.post_graphql(+ ACTIVATE_GIFT_CARD_MUTATION,+ variables,+ permissions=[+ permission_manage_gift_card,+ permission_manage_users,+ permission_manage_apps,+ ],+ )++ # then+ content = get_graphql_content(response)+ errors = content["data"]["giftCardActivate"]["errors"]+ data = content["data"]["giftCardActivate"]["giftCard"]++ assert not data+ assert len(errors) == 1+ assert errors[0]["field"] == "id"+ assert errors[0]["code"] == GiftCardErrorCode.EXPIRED_GIFT_CARD.namediff --git a/saleor/graphql/giftcard/tests/mutations/test_gift_card_add_note.py b/saleor/graphql/giftcard/tests/mutations/test_gift_card_add_note.pyindex ef58871b2a..ea2ad69cbb 100644--- a/saleor/graphql/giftcard/tests/mutations/test_gift_card_add_note.py+++ b/saleor/graphql/giftcard/tests/mutations/test_gift_card_add_note.py@@ -1,3 +1,5 @@+from datetime import date, timedelta+import grapheneimport pytest@@ -38,10 +40,13 @@ def test_gift_card_add_note_as_staff_user(gift_card,staff_user,):+ # givenassert not gift_card.events.all()gift_card_id = graphene.Node.to_global_id("GiftCard", gift_card.id)message = "nuclear note"variables = {"id": gift_card_id, "message": message}++ # whenresponse = staff_api_client.post_graphql(GIFT_CARD_ADD_NOTE_MUTATION,variables,@@ -51,6 +56,8 @@ def test_gift_card_add_note_as_staff_user(permission_manage_gift_card,],)++ # thencontent = get_graphql_content(response)data = content["data"]["giftCardAddNote"]@@ -73,10 +80,13 @@ def test_gift_card_add_note_as_app(gift_card,staff_user,):+ # givenassert not gift_card.events.all()gift_card_id = graphene.Node.to_global_id("GiftCard", gift_card.id)message = "nuclear note"variables = {"id": gift_card_id, "message": message}++ # whenresponse = app_api_client.post_graphql(GIFT_CARD_ADD_NOTE_MUTATION,variables,@@ -86,6 +96,8 @@ def test_gift_card_add_note_as_app(permission_manage_gift_card,],)++ # thencontent = get_graphql_content(response)data = content["data"]["giftCardAddNote"]@@ -116,8 +128,11 @@ def test_gift_card_add_note_fail_on_empty_message(permission_manage_gift_card,gift_card,):+ # givengift_card_id = graphene.Node.to_global_id("GiftCard", gift_card.id)variables = {"id": gift_card_id, "message": message}++ # whenresponse = staff_api_client.post_graphql(GIFT_CARD_ADD_NOTE_MUTATION,variables,@@ -127,7 +142,52 @@ def test_gift_card_add_note_fail_on_empty_message(permission_manage_gift_card,],)++ # thencontent = get_graphql_content(response)data = content["data"]["giftCardAddNote"]assert data["errors"][0]["field"] == "message"assert data["errors"][0]["code"] == GiftCardErrorCode.REQUIRED.name+++def test_gift_card_add_note_expired_card(+ staff_api_client,+ permission_manage_apps,+ permission_manage_users,+ permission_manage_gift_card,+ gift_card,+):+ # given+ staff_user = staff_api_client.user++ gift_card.expiry_date = date.today() - timedelta(days=1)+ gift_card.save(update_fields=["expiry_date"])++ gift_card_id = graphene.Node.to_global_id("GiftCard", gift_card.id)+ message = "nuclear note"+ variables = {"id": gift_card_id, "message": message}++ # when+ response = staff_api_client.post_graphql(+ GIFT_CARD_ADD_NOTE_MUTATION,+ variables,+ permissions=[+ permission_manage_apps,+ permission_manage_users,+ permission_manage_gift_card,+ ],+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["giftCardAddNote"]++ assert data["giftCard"]["id"] == gift_card_id+ assert data["event"]["user"]["email"] == staff_user.email+ assert data["event"]["app"] is None+ assert data["event"]["message"] == message++ event = gift_card.events.get()+ assert event.type == GiftCardEvents.NOTE_ADDED+ assert event.user == staff_user+ assert event.parameters == {"message": message}diff --git a/saleor/graphql/giftcard/tests/mutations/test_gift_card_bulk_activate.py b/saleor/graphql/giftcard/tests/mutations/test_gift_card_bulk_activate.pyindex 8712f2c123..c99e64d424 100644--- a/saleor/graphql/giftcard/tests/mutations/test_gift_card_bulk_activate.py+++ b/saleor/graphql/giftcard/tests/mutations/test_gift_card_bulk_activate.py@@ -1,6 +1,9 @@+from datetime import date, timedelta+import graphenefrom .....giftcard import GiftCardEvents+from .....giftcard.error_codes import GiftCardErrorCodefrom .....giftcard.models import GiftCard, GiftCardEventfrom ....tests.utils import assert_no_permission, get_graphql_content@@ -134,3 +137,46 @@ def test_gift_card_bulk_activate_by_customer(# thenassert_no_permission(response)+++def test_gift_card_bulk_activate_expired_cards(+ staff_api_client,+ gift_card,+ gift_card_expiry_date,+ gift_card_created_by_staff,+ permission_manage_gift_card,+):+ # given+ gift_card.is_active = False+ gift_card_expiry_date.is_active = True+ gift_card_created_by_staff.expiry_date = date.today() - timedelta(days=2)+ gift_card.expiry_date = date.today() - timedelta(days=1)+ gift_cards = [gift_card, gift_card_expiry_date, gift_card_created_by_staff]+ GiftCard.objects.bulk_update(gift_cards, ["is_active", "expiry_date"])++ ids = [graphene.Node.to_global_id("GiftCard", card.pk) for card in gift_cards]+ variables = {"ids": ids}++ # when+ response = staff_api_client.post_graphql(+ MUTATION_GIFT_CARD_BULK_ACTIVATE,+ variables,+ permissions=(permission_manage_gift_card,),+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["giftCardBulkActivate"]++ # assert data["count"] == 0+ errors = data["errors"]+ assert len(errors) == 2+ expected_errors = [+ {+ "field": graphene.Node.to_global_id("GiftCard", card.pk),+ "code": GiftCardErrorCode.INVALID.name,+ }+ for card in [gift_card, gift_card_created_by_staff]+ ]+ for error in errors:+ assert error in expected_errorsdiff --git a/saleor/graphql/giftcard/tests/mutations/test_gift_card_bulk_create.py b/saleor/graphql/giftcard/tests/mutations/test_gift_card_bulk_create.pynew file mode 100644index 0000000000..aa42b3e824--- /dev/null+++ b/saleor/graphql/giftcard/tests/mutations/test_gift_card_bulk_create.py@@ -0,0 +1,467 @@+from datetime import date, timedelta++import pytest++from .....giftcard import GiftCardEvents+from .....giftcard.error_codes import GiftCardErrorCode+from ....tests.utils import assert_no_permission, get_graphql_content++GIFT_CARD_BULK_CREATE_MUTATION = """+ mutation GiftCardBulkCreate($input: GiftCardBulkCreateInput!) {+ giftCardBulkCreate(input: $input) {+ count+ giftCards {+ id+ code+ last4CodeChars+ isActive+ expiryDate+ tags {+ name+ }+ created+ lastUsedOn+ initialBalance {+ currency+ amount+ }+ currentBalance {+ currency+ amount+ }+ createdBy {+ }+ usedBy {+ }+ createdByEmail+ usedByEmail+ app {+ name+ }+ product {+ name+ }+ events {+ type+ user {+ }+ app {+ name+ }+ balance {+ initialBalance {+ amount+ currency+ }+ oldInitialBalance {+ amount+ currency+ }+ currentBalance {+ amount+ currency+ }+ oldCurrentBalance {+ amount+ currency+ }+ }+ }+ }+ errors {+ code+ field+ message+ }+ }+ }+"""+++def test_create_never_expiry_gift_cards(+ staff_api_client,+ permission_manage_gift_card,+ permission_manage_users,+ permission_manage_apps,+):+ # given+ initial_balance = 100+ currency = "USD"+ tags = ["gift-card-tag", "gift-card-tag-2"]+ count = 10+ is_active = True+ variables = {+ "input": {+ "count": count,+ "balance": {+ "amount": initial_balance,+ "currency": currency,+ },+ "tags": tags,+ "isActive": is_active,+ }+ }++ # when+ response = staff_api_client.post_graphql(+ GIFT_CARD_BULK_CREATE_MUTATION,+ variables,+ permissions=[+ permission_manage_gift_card,+ permission_manage_users,+ permission_manage_apps,+ ],+ )++ # then+ content = get_graphql_content(response)+ errors = content["data"]["giftCardBulkCreate"]["errors"]+ data = content["data"]["giftCardBulkCreate"]++ assert not errors+ assert data["count"] == count+ assert len(data["giftCards"]) == count+ for card_data in data["giftCards"]:+ assert card_data["isActive"] == is_active+ assert len(card_data["tags"]) == len(tags)+ assert {tag["name"] for tag in card_data["tags"]} == set(tags)+ assert card_data["expiryDate"] is None+ assert card_data["usedBy"] is None+ assert card_data["usedByEmail"] is None+ assert card_data["createdBy"]["email"] == staff_api_client.user.email+ assert card_data["createdByEmail"] == staff_api_client.user.email+ assert card_data["app"] is None+ assert card_data["product"] is None+ assert card_data["initialBalance"]["amount"] == initial_balance+ assert card_data["initialBalance"]["currency"] == currency+ assert card_data["currentBalance"]["amount"] == initial_balance+ assert card_data["currentBalance"]["currency"] == currency+ assert len(card_data["events"]) == 1+ assert card_data["events"][0]["type"] == GiftCardEvents.ISSUED.upper()+ assert card_data["events"][0]["app"] is None+ assert card_data["events"][0]["user"]["email"] == staff_api_client.user.email+ assert (+ card_data["events"][0]["balance"]["initialBalance"]["amount"]+ == initial_balance+ )+ assert (+ card_data["events"][0]["balance"]["initialBalance"]["currency"] == currency+ )+ assert (+ card_data["events"][0]["balance"]["currentBalance"]["amount"]+ == initial_balance+ )+ assert (+ card_data["events"][0]["balance"]["currentBalance"]["currency"] == currency+ )+ assert not card_data["events"][0]["balance"]["oldInitialBalance"]+ assert not card_data["events"][0]["balance"]["oldCurrentBalance"]+++def test_create_gift_cards_with_expiry_date_by_app(+ app_api_client,+ permission_manage_gift_card,+ permission_manage_users,+ permission_manage_apps,+):+ # given+ initial_balance = 100+ currency = "USD"+ tag = "gift-card-tag"+ count = 5+ is_active = False+ date_value = date.today() + timedelta(days=365)+ variables = {+ "input": {+ "count": count,+ "balance": {+ "amount": initial_balance,+ "currency": currency,+ },+ "tags": [tag],+ "isActive": is_active,+ "expiryDate": date_value,+ }+ }++ # when+ response = app_api_client.post_graphql(+ GIFT_CARD_BULK_CREATE_MUTATION,+ variables,+ permissions=[+ permission_manage_gift_card,+ permission_manage_users,+ permission_manage_apps,+ ],+ )++ # then+ content = get_graphql_content(response)+ errors = content["data"]["giftCardBulkCreate"]["errors"]+ data = content["data"]["giftCardBulkCreate"]++ assert not errors+ assert data["count"] == count+ assert len(data["giftCards"]) == count+ for card_data in data["giftCards"]:+ assert card_data["isActive"] == is_active+ assert len(card_data["tags"]) == 1+ assert card_data["tags"][0]["name"] == tag+ assert card_data["expiryDate"] == date_value.isoformat()+ assert card_data["usedBy"] is None+ assert card_data["usedByEmail"] is None+ assert card_data["createdBy"] is None+ assert card_data["createdByEmail"] is None+ assert card_data["app"]["name"] == app_api_client.app.name+ assert card_data["product"] is None+ assert card_data["initialBalance"]["amount"] == initial_balance+ assert card_data["initialBalance"]["currency"] == currency+ assert card_data["currentBalance"]["amount"] == initial_balance+ assert card_data["currentBalance"]["currency"] == currency+ assert len(card_data["events"]) == 1+ assert card_data["events"][0]["type"] == GiftCardEvents.ISSUED.upper()+ assert card_data["events"][0]["app"]["name"] == app_api_client.app.name+ assert card_data["events"][0]["user"] is None+ assert (+ card_data["events"][0]["balance"]["initialBalance"]["amount"]+ == initial_balance+ )+ assert (+ card_data["events"][0]["balance"]["initialBalance"]["currency"] == currency+ )+ assert (+ card_data["events"][0]["balance"]["currentBalance"]["amount"]+ == initial_balance+ )+ assert (+ card_data["events"][0]["balance"]["currentBalance"]["currency"] == currency+ )+ assert not card_data["events"][0]["balance"]["oldInitialBalance"]+ assert not card_data["events"][0]["balance"]["oldCurrentBalance"]+++def test_create_gift_cards_by_cutomer(api_client):+ # given+ initial_balance = 100+ currency = "USD"+ tag = "gift-card-tag"+ count = 10+ is_active = True+ variables = {+ "input": {+ "count": count,+ "balance": {+ "amount": initial_balance,+ "currency": currency,+ },+ "tags": [tag],+ "isActive": is_active,+ }+ }++ # when+ response = api_client.post_graphql(+ GIFT_CARD_BULK_CREATE_MUTATION,+ variables,+ )++ # then+ assert_no_permission(response)++[email protected]("count_value", [0, -2])+def test_create_gift_cards_invalid_count_value(+ count_value,+ app_api_client,+ permission_manage_gift_card,+ permission_manage_users,+ permission_manage_apps,+):+ # given+ initial_balance = 100+ currency = "USD"+ tag = "gift-card-tag"+ is_active = False+ date_value = date.today() + timedelta(days=365)+ variables = {+ "input": {+ "count": count_value,+ "balance": {+ "amount": initial_balance,+ "currency": currency,+ },+ "tags": [tag],+ "isActive": is_active,+ "expiryDate": date_value,+ }+ }++ # when+ response = app_api_client.post_graphql(+ GIFT_CARD_BULK_CREATE_MUTATION,+ variables,+ permissions=[+ permission_manage_gift_card,+ permission_manage_users,+ permission_manage_apps,+ ],+ )++ # then+ content = get_graphql_content(response)+ errors = content["data"]["giftCardBulkCreate"]["errors"]+ data = content["data"]["giftCardBulkCreate"]++ assert not data["giftCards"]+ assert data["count"] == 0+ assert len(errors) == 1+ assert errors[0]["field"] == "count"+ assert errors[0]["code"] == GiftCardErrorCode.INVALID.name+++def test_create_gift_cards_too_many_decimal_places_in_balance_amount(+ app_api_client,+ permission_manage_gift_card,+ permission_manage_users,+ permission_manage_apps,+):+ # given+ initial_balance = 14.3455+ currency = "USD"+ tag = "gift-card-tag"+ is_active = False+ date_value = date.today() + timedelta(days=365)+ variables = {+ "input": {+ "count": 2,+ "balance": {+ "amount": initial_balance,+ "currency": currency,+ },+ "tags": [tag],+ "isActive": is_active,+ "expiryDate": date_value,+ }+ }++ # when+ response = app_api_client.post_graphql(+ GIFT_CARD_BULK_CREATE_MUTATION,+ variables,+ permissions=[+ permission_manage_gift_card,+ permission_manage_users,+ permission_manage_apps,+ ],+ )++ # then+ content = get_graphql_content(response)+ errors = content["data"]["giftCardBulkCreate"]["errors"]+ data = content["data"]["giftCardBulkCreate"]++ assert not data["giftCards"]+ assert data["count"] == 0+ assert len(errors) == 1+ assert errors[0]["field"] == "balance"+ assert errors[0]["code"] == GiftCardErrorCode.INVALID.name+++def test_create_gift_cards_zero_balance_amount(+ app_api_client,+ permission_manage_gift_card,+ permission_manage_users,+ permission_manage_apps,+):+ # given+ initial_balance = 0+ currency = "USD"+ tag = "gift-card-tag"+ is_active = False+ date_value = date.today() + timedelta(days=365)+ variables = {+ "input": {+ "count": 2,+ "balance": {+ "amount": initial_balance,+ "currency": currency,+ },+ "tags": [tag],+ "isActive": is_active,+ "expiryDate": date_value,+ }+ }++ # when+ response = app_api_client.post_graphql(+ GIFT_CARD_BULK_CREATE_MUTATION,+ variables,+ permissions=[+ permission_manage_gift_card,+ permission_manage_users,+ permission_manage_apps,+ ],+ )++ # then+ content = get_graphql_content(response)+ errors = content["data"]["giftCardBulkCreate"]["errors"]+ data = content["data"]["giftCardBulkCreate"]++ assert not data["giftCards"]+ assert data["count"] == 0+ assert len(errors) == 1+ assert errors[0]["field"] == "balance"+ assert errors[0]["code"] == GiftCardErrorCode.INVALID.name++[email protected]("date_value", [date(1999, 1, 1), date.today()])+def test_create_gift_cards_invalid_expiry_date(+ date_value,+ app_api_client,+ permission_manage_gift_card,+ permission_manage_users,+ permission_manage_apps,+):+ # given+ initial_balance = 10+ currency = "USD"+ tag = "gift-card-tag"+ is_active = False+ variables = {+ "input": {+ "count": 2,+ "balance": {+ "amount": initial_balance,+ "currency": currency,+ },+ "tags": [tag],+ "isActive": is_active,+ "expiryDate": date_value,+ }+ }++ # when+ response = app_api_client.post_graphql(+ GIFT_CARD_BULK_CREATE_MUTATION,+ variables,+ permissions=[+ permission_manage_gift_card,+ permission_manage_users,+ permission_manage_apps,+ ],+ )++ # then+ content = get_graphql_content(response)+ errors = content["data"]["giftCardBulkCreate"]["errors"]+ data = content["data"]["giftCardBulkCreate"]++ assert not data["giftCards"]+ assert data["count"] == 0+ assert len(errors) == 1+ assert errors[0]["field"] == "expiryDate"+ assert errors[0]["code"] == GiftCardErrorCode.INVALID.namediff --git a/saleor/graphql/giftcard/tests/mutations/test_gift_card_create.py b/saleor/graphql/giftcard/tests/mutations/test_gift_card_create.pyindex 2a00a5ce84..c31a8b207d 100644--- a/saleor/graphql/giftcard/tests/mutations/test_gift_card_create.py+++ b/saleor/graphql/giftcard/tests/mutations/test_gift_card_create.py@@ -14,10 +14,12 @@ CREATE_GIFT_CARD_MUTATION = """giftCard {idcode- displayCode+ last4CodeCharsisActiveexpiryDate- tag+ tags {+ name+ }createdlastUsedOninitialBalance {@@ -90,11 +92,14 @@ def test_create_never_expiry_gift_card(permission_manage_gift_card,permission_manage_users,permission_manage_apps,+ gift_card_tag_list,):# giveninitial_balance = 100currency = "USD"- tag = "gift-card-tag"+ new_tag = "gift-card-tag"+ existing_tag_name = gift_card_tag_list[0].name+ tags = [new_tag, existing_tag_name]note = "This is gift card note that will be save in gift card event."variables = {"input": {@@ -104,7 +109,7 @@ def test_create_never_expiry_gift_card(},"userEmail": customer_user.email,"channel": channel_USD.slug,- "tag": tag,+ "addTags": tags,"note": note,"isActive": True,}@@ -128,9 +133,10 @@ def test_create_never_expiry_gift_card(assert not errorsassert data["code"]- assert data["displayCode"]+ assert data["last4CodeChars"]assert not data["expiryDate"]- assert data["tag"] == tag+ assert len(data["tags"]) == 2+ assert {tag["name"] for tag in data["tags"]} == set(tags)assert data["createdBy"]["email"] == staff_api_client.user.emailassert data["createdByEmail"] == staff_api_client.user.emailassert not data["usedBy"]@@ -176,7 +182,6 @@ def test_create_never_expiry_gift_card(def test_create_gift_card_by_app(send_notification_mock,app_api_client,- customer_user,permission_manage_gift_card,permission_manage_users,):@@ -191,7 +196,7 @@ def test_create_gift_card_by_app("amount": initial_balance,"currency": currency,},- "tag": tag,+ "addTags": [tag],"note": note,"expiryDate": None,"isActive": False,@@ -212,9 +217,10 @@ def test_create_gift_card_by_app(assert not errorsassert data["code"]- assert data["displayCode"]+ assert data["last4CodeChars"]assert not data["expiryDate"]- assert data["tag"] == tag+ assert len(data["tags"]) == 1+ assert data["tags"][0]["name"] == tagassert not data["createdBy"]assert not data["createdByEmail"]assert not data["usedBy"]@@ -259,7 +265,7 @@ def test_create_gift_card_by_customer(api_client, customer_user, channel_USD):},"userEmail": customer_user.email,"channel": channel_USD.slug,- "tag": tag,+ "addTags": [tag],"note": "This is gift card note that will be save in gift card event.","expiryDate": None,"isActive": True,@@ -287,7 +293,7 @@ def test_create_gift_card_no_premissions(staff_api_client):"amount": initial_balance,"currency": currency,},- "tag": tag,+ "addTags": [tag],"note": "This is gift card note that will be save in gift card event.","expiryDate": None,"isActive": True,@@ -322,7 +328,7 @@ def test_create_gift_card_with_too_many_decimal_places_in_balance_amount("currency": currency,},"userEmail": customer_user.email,- "tag": tag,+ "addTags": [tag],"note": "This is gift card note that will be save in gift card event.","isActive": True,}@@ -367,7 +373,7 @@ def test_create_gift_card_with_malformed_email("currency": currency,},"userEmail": "malformed",- "tag": tag,+ "addTags": [tag],"note": "This is gift card note that will be save in gift card event.","isActive": True,}@@ -414,7 +420,7 @@ def test_create_gift_card_lack_of_channel("currency": currency,},"userEmail": customer_user.email,- "tag": tag,+ "addTags": [tag],"note": "This is gift card note that will be save in gift card event.","isActive": True,}@@ -460,7 +466,7 @@ def test_create_gift_card_with_zero_balance_amount("currency": currency,},"userEmail": customer_user.email,- "tag": tag,+ "addTags": [tag],"note": "This is gift card note that will be save in gift card event.","isActive": True,}@@ -511,7 +517,7 @@ def test_create_gift_card_with_expiry_date(},"userEmail": customer_user.email,"channel": channel_USD.slug,- "tag": tag,+ "addTags": [tag],"expiryDate": date_value,"isActive": True,}@@ -535,7 +541,7 @@ def test_create_gift_card_with_expiry_date(assert not errorsassert data["code"]- assert data["displayCode"]+ assert data["last4CodeChars"]assert data["expiryDate"] == date_value.isoformat()assert len(data["events"]) == 1@@ -584,7 +590,7 @@ def test_create_gift_card_with_expiry_date_type_invalid("currency": currency,},"userEmail": customer_user.email,- "tag": tag,+ "addTags": [tag],"note": "This is gift card note that will be save in gift card event.","expiryDate": date_value,"isActive": True,diff --git a/saleor/graphql/giftcard/tests/mutations/test_gift_card_resend.py b/saleor/graphql/giftcard/tests/mutations/test_gift_card_resend.pyindex 72fecb37fd..1c99dab406 100644--- a/saleor/graphql/giftcard/tests/mutations/test_gift_card_resend.py+++ b/saleor/graphql/giftcard/tests/mutations/test_gift_card_resend.py@@ -1,3 +1,4 @@+from datetime import date, timedeltafrom unittest import mockimport graphene@@ -213,3 +214,47 @@ def test_resend_gift_card_malformed_email(assert error["code"] == GiftCardErrorCode.INVALID.namesend_notification_mock.assert_not_called()+++def test_resend_gift_card_expired_card(+ staff_api_client,+ gift_card,+ channel_USD,+ permission_manage_gift_card,+ permission_manage_users,+ permission_manage_apps,+):+ # given+ gift_card.expiry_date = date.today() - timedelta(days=1)+ gift_card.save(update_fields=["expiry_date"])++ email = "[email protected]"+ variables = {+ "input": {+ "id": graphene.Node.to_global_id("GiftCard", gift_card.pk),+ "email": email,+ "channel": channel_USD.slug,+ }+ }++ # when+ response = staff_api_client.post_graphql(+ GIFT_CARD_RESEND_MUTATION,+ variables,+ permissions=[+ permission_manage_gift_card,+ permission_manage_users,+ permission_manage_apps,+ ],+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["giftCardResend"]+ errors = data["errors"]++ assert not data["giftCard"]+ assert len(errors) == 1+ error = errors[0]+ assert error["field"] == "id"+ assert error["code"] == GiftCardErrorCode.EXPIRED_GIFT_CARD.namediff --git a/saleor/graphql/giftcard/tests/mutations/test_gift_card_update.py b/saleor/graphql/giftcard/tests/mutations/test_gift_card_update.pyindex ce52944213..821c0909b9 100644--- a/saleor/graphql/giftcard/tests/mutations/test_gift_card_update.py+++ b/saleor/graphql/giftcard/tests/mutations/test_gift_card_update.py@@ -5,6 +5,7 @@ import pytestfrom .....giftcard import GiftCardEventsfrom .....giftcard.error_codes import GiftCardErrorCode+from .....giftcard.models import GiftCardTagfrom ....tests.utils import assert_no_permission, get_graphql_contentUPDATE_GIFT_CARD_MUTATION = """@@ -14,10 +15,12 @@ UPDATE_GIFT_CARD_MUTATION = """giftCardUpdate(id: $id, input: $input) {giftCard {id- displayCode+ last4CodeCharsisActiveexpiryDate- tag+ tags {+ name+ }createdlastUsedOninitialBalance {@@ -50,8 +53,8 @@ UPDATE_GIFT_CARD_MUTATION = """app {name}- tag- oldTag+ tags+ oldTagsbalance {initialBalance {amount@@ -94,17 +97,18 @@ def test_update_gift_card(# givenold_initial_balance = float(gift_card.initial_balance.amount)old_current_balance = float(gift_card.current_balance.amount)- old_tag = gift_card.taginitial_balance = 100.0currency = gift_card.currencydate_value = date.today() + timedelta(days=365)- tag = "new-gift-card-tag"+ old_tag = gift_card.tags.first().name+ new_tag = "new-gift-card-tag"+ tags_count = GiftCardTag.objects.count()variables = {"id": graphene.Node.to_global_id("GiftCard", gift_card.pk),"input": {"balanceAmount": initial_balance,- "tag": tag,+ "addTags": [new_tag],"expiryDate": date_value,},}@@ -126,9 +130,10 @@ def test_update_gift_card(data = content["data"]["giftCardUpdate"]["giftCard"]assert not errors- assert data["displayCode"]+ assert data["last4CodeChars"]assert data["expiryDate"] == date_value.isoformat()- assert data["tag"] == tag+ assert len(data["tags"]) == 2+ assert {tag["name"] for tag in data["tags"]} == {old_tag, new_tag}assert data["createdBy"]["email"] == gift_card.created_by.emailassert data["createdByEmail"] == gift_card.created_by_emailassert not data["usedBy"]@@ -167,8 +172,8 @@ def test_update_gift_card(},"expiryDate": None,"oldExpiryDate": None,- "tag": None,- "oldTag": None,+ "tags": None,+ "oldTags": None,},{"type": GiftCardEvents.EXPIRY_DATE_UPDATED.upper(),@@ -179,11 +184,11 @@ def test_update_gift_card("balance": None,"expiryDate": date_value.isoformat(),"oldExpiryDate": None,- "tag": None,- "oldTag": None,+ "tags": None,+ "oldTags": None,},{- "type": GiftCardEvents.TAG_UPDATED.upper(),+ "type": GiftCardEvents.TAGS_UPDATED.upper(),"user": {"email": staff_api_client.user.email,},@@ -191,13 +196,15 @@ def test_update_gift_card("balance": None,"expiryDate": None,"oldExpiryDate": None,- "tag": tag,- "oldTag": old_tag,+ "tags": [new_tag, old_tag],+ "oldTags": [old_tag],},]for event in data["events"]:assert event in events+ assert GiftCardTag.objects.count() == tags_count + 1+def test_update_gift_card_by_app(app_api_client,@@ -205,21 +212,24 @@ def test_update_gift_card_by_app(permission_manage_gift_card,permission_manage_users,permission_manage_apps,+ gift_card_tag_list,):# givenold_initial_balance = float(gift_card.initial_balance.amount)old_current_balance = float(gift_card.current_balance.amount)- old_tag = gift_card.tag+ old_tag = gift_card.tags.first()initial_balance = 100.0currency = gift_card.currencydate_value = date.today() + timedelta(days=365)- tag = "new-gift-card-tag"+ new_tag = gift_card_tag_list[0].name+ tags_count = GiftCardTag.objects.count()variables = {"id": graphene.Node.to_global_id("GiftCard", gift_card.pk),"input": {"balanceAmount": initial_balance,- "tag": tag,+ "addTags": [new_tag],+ "removeTags": [old_tag.name],"expiryDate": date_value,},}@@ -241,9 +251,10 @@ def test_update_gift_card_by_app(data = content["data"]["giftCardUpdate"]["giftCard"]assert not errors- assert data["displayCode"]+ assert data["last4CodeChars"]assert data["expiryDate"] == date_value.isoformat()- assert data["tag"] == tag+ assert len(data["tags"]) == 1+ assert {tag["name"] for tag in data["tags"]} == {new_tag}assert data["createdBy"]["email"] == gift_card.created_by.emailassert data["createdByEmail"] == gift_card.created_by_emailassert not data["usedBy"]@@ -280,8 +291,8 @@ def test_update_gift_card_by_app(},"expiryDate": None,"oldExpiryDate": None,- "tag": None,- "oldTag": None,+ "tags": None,+ "oldTags": None,},{"type": GiftCardEvents.EXPIRY_DATE_UPDATED.upper(),@@ -290,25 +301,30 @@ def test_update_gift_card_by_app("balance": None,"expiryDate": date_value.isoformat(),"oldExpiryDate": None,- "tag": None,- "oldTag": None,+ "tags": None,+ "oldTags": None,},{- "type": GiftCardEvents.TAG_UPDATED.upper(),+ "type": GiftCardEvents.TAGS_UPDATED.upper(),"user": None,"app": {"name": app_api_client.app.name},"balance": None,"expiryDate": None,"oldExpiryDate": None,- "tag": tag,- "oldTag": old_tag,+ "tags": [new_tag],+ "oldTags": [old_tag.name],},]for event in data["events"]:assert event in events+ with pytest.raises(old_tag._meta.model.DoesNotExist):+ old_tag.refresh_from_db()++ assert GiftCardTag.objects.count() == tags_count - 1-def test_update_gift_card_by_customer(api_client, customer_user, gift_card):++def test_update_gift_card_by_customer(api_client, gift_card):# giveninitial_balance = 100.0tag = "new-gift-card-tag"@@ -316,7 +332,7 @@ def test_update_gift_card_by_customer(api_client, customer_user, gift_card):"id": graphene.Node.to_global_id("GiftCard", gift_card.pk),"input": {"balanceAmount": initial_balance,- "tag": tag,+ "addTags": [tag],},}@@ -369,7 +385,7 @@ def test_update_gift_card_balance(assert not errorsassert not data["expiryDate"]- assert data["tag"] == gift_card.tag+ assert data["tags"][0]["name"] == gift_card.tags.first().nameassert data["isActive"]assert data["initialBalance"]["amount"] == initial_balanceassert data["currentBalance"]["amount"] == initial_balance@@ -401,8 +417,8 @@ def test_update_gift_card_balance(},"expiryDate": None,"oldExpiryDate": None,- "tag": None,- "oldTag": None,+ "tags": None,+ "oldTags": None,}assert expected_event == data["events"][0]@@ -442,9 +458,9 @@ def test_update_gift_card_change_to_never_expire(data = content["data"]["giftCardUpdate"]["giftCard"]assert not errors- assert data["displayCode"]+ assert data["last4CodeChars"]assert not data["expiryDate"]- assert data["tag"] == gift_card.tag+ assert data["tags"][0]["name"] == gift_card.tags.first().nameassert data["createdBy"]["email"] == gift_card.created_by.emailassert data["createdByEmail"] == gift_card.created_by_email@@ -457,8 +473,8 @@ def test_update_gift_card_change_to_never_expire("app": None,"balance": None,"expiryDate": None,- "tag": None,- "oldTag": None,+ "tags": None,+ "oldTags": None,"oldExpiryDate": old_expiry_date.isoformat(),}assert expected_event == data["events"][0]@@ -499,7 +515,7 @@ def test_update_used_gift_card_to_expiry_date(data = content["data"]["giftCardUpdate"]["giftCard"]assert not errors- assert data["displayCode"]+ assert data["last4CodeChars"]assert data["expiryDate"] == date_value.isoformat()assert len(data["events"]) == 1event = data["events"][0]@@ -541,7 +557,7 @@ def test_update_used_gift_card_to_never_expired(data = content["data"]["giftCardUpdate"]["giftCard"]assert not errors- assert data["displayCode"]+ assert data["last4CodeChars"]assert data["expiryDate"] is None@@ -581,3 +597,131 @@ def test_update_gift_card_date_in_past(assert len(errors) == 1assert errors[0]["field"] == "expiryDate"assert errors[0]["code"] == GiftCardErrorCode.INVALID.name+++def test_update_gift_card_expired_card(+ staff_api_client,+ gift_card,+ permission_manage_gift_card,+ permission_manage_users,+ permission_manage_apps,+):+ # given+ gift_card.expiry_date = date.today() - timedelta(days=1)+ gift_card.save(update_fields=["expiry_date"])++ variables = {+ "id": graphene.Node.to_global_id("GiftCard", gift_card.pk),+ "input": {+ "expiryDate": None,+ },+ }++ # when+ response = staff_api_client.post_graphql(+ UPDATE_GIFT_CARD_MUTATION,+ variables,+ permissions=[+ permission_manage_gift_card,+ permission_manage_users,+ permission_manage_apps,+ ],+ )++ # then+ content = get_graphql_content(response)+ errors = content["data"]["giftCardUpdate"]["errors"]+ data = content["data"]["giftCardUpdate"]["giftCard"]++ assert not errors+ assert data["last4CodeChars"]+ assert not data["expiryDate"]+ assert len(data["tags"]) == 1+ assert data["tags"][0]["name"] == gift_card.tags.first().name+ assert data["createdBy"]["email"] == gift_card.created_by.email+ assert data["createdByEmail"] == gift_card.created_by_email++ assert len(data["events"]) == 1+ assert data["events"][0]["type"] == GiftCardEvents.EXPIRY_DATE_UPDATED.upper()+++def test_update_gift_card_expiry_date_not_changed(+ staff_api_client,+ gift_card_expiry_date,+ permission_manage_gift_card,+ permission_manage_users,+ permission_manage_apps,+):+ # given+ gift_card = gift_card_expiry_date+ old_expiry_date = gift_card.expiry_date++ variables = {+ "id": graphene.Node.to_global_id("GiftCard", gift_card.pk),+ "input": {+ "expiryDate": old_expiry_date,+ },+ }++ # when+ response = staff_api_client.post_graphql(+ UPDATE_GIFT_CARD_MUTATION,+ variables,+ permissions=[+ permission_manage_gift_card,+ permission_manage_users,+ permission_manage_apps,+ ],+ )++ # then+ content = get_graphql_content(response)+ errors = content["data"]["giftCardUpdate"]["errors"]+ data = content["data"]["giftCardUpdate"]["giftCard"]++ assert not errors+ assert data["last4CodeChars"]+ assert data["expiryDate"] == old_expiry_date.isoformat()+ assert data["tags"][0]["name"] == gift_card.tags.first().name+ assert data["createdBy"]["email"] == gift_card.created_by.email+ assert data["createdByEmail"] == gift_card.created_by_email++ # no events should be created+ assert len(data["events"]) == 0+++def test_update_gift_card_duplicated_tags_item(+ staff_api_client,+ gift_card,+ permission_manage_gift_card,+ permission_manage_users,+ permission_manage_apps,+ gift_card_tag_list,+):+ # given+ tag = gift_card_tag_list[0]+ variables = {+ "id": graphene.Node.to_global_id("GiftCard", gift_card.pk),+ "input": {"addTags": tag.name, "removeTags": tag.name},+ }++ # when+ response = staff_api_client.post_graphql(+ UPDATE_GIFT_CARD_MUTATION,+ variables,+ permissions=[+ permission_manage_gift_card,+ permission_manage_users,+ permission_manage_apps,+ ],+ )++ # then+ content = get_graphql_content(response)+ errors = content["data"]["giftCardUpdate"]["errors"]+ data = content["data"]["giftCardUpdate"]["giftCard"]++ assert not data+ assert len(errors) == 1+ assert errors[0]["field"] == "tags"+ assert errors[0]["code"] == GiftCardErrorCode.DUPLICATED_INPUT_ITEM.namediff --git a/saleor/graphql/giftcard/tests/queries/test_gift_card.py b/saleor/graphql/giftcard/tests/queries/test_gift_card.pyindex 1b17dd3b82..4d0ca7ec6b 100644--- a/saleor/graphql/giftcard/tests/queries/test_gift_card.py+++ b/saleor/graphql/giftcard/tests/queries/test_gift_card.py@@ -2,6 +2,7 @@ import datetimefrom copy import deepcopyimport graphene+import pytestfrom django.utils import timezonefrom .....giftcard import GiftCardEvents, events@@ -11,16 +12,19 @@ from ....tests.utils import (get_graphql_content,get_graphql_content_from_response,)+from ...enums import GiftCardEventsEnumQUERY_GIFT_CARD_BY_ID = """query giftCard($id: ID!) {giftCard(id: $id){idcode- displayCode+ last4CodeCharsisActiveexpiryDate- tag+ tags {+ name+ }createdlastUsedOnboughtInChannel@@ -79,10 +83,10 @@ def test_query_gift_card_with_permissions(data = content["data"]["giftCard"]assert data["id"] == gift_card_idassert data["code"] == gift_card.code- assert data["displayCode"] == gift_card.display_code+ assert data["last4CodeChars"] == gift_card.display_codeassert data["isActive"] == gift_card.is_activeassert data["expiryDate"] is None- assert data["tag"] == gift_card.tag+ assert data["tags"][0]["name"] == gift_card.tags.first().nameassert data["created"] == gift_card.created.isoformat()assert data["lastUsedOn"] == gift_card.last_used_onassert data["boughtInChannel"] is None@@ -144,10 +148,10 @@ def test_query_gift_card_by_app(data = content["data"]["giftCard"]assert data["id"] == gift_card_idassert data["code"] == gift_card.code- assert data["displayCode"] == gift_card.display_code+ assert data["last4CodeChars"] == gift_card.display_codeassert data["isActive"] == gift_card.is_activeassert data["expiryDate"] is None- assert data["tag"] == gift_card.tag+ assert data["tags"][0]["name"] == gift_card.tags.first().nameassert data["created"] == gift_card.created.isoformat()assert data["lastUsedOn"] == gift_card.last_used_onassert data["initialBalance"]["currency"] == gift_card.initial_balance.currency@@ -205,7 +209,7 @@ def test_query_gift_card_with_expiry_date(data = content["data"]["giftCard"]assert data["id"] == gift_card_idassert data["code"] == gift_card_expiry_date.code- assert data["displayCode"] == gift_card_expiry_date.display_code+ assert data["last4CodeChars"] == gift_card_expiry_date.display_codeassert data["expiryDate"] == gift_card_expiry_date.expiry_date.isoformat()@@ -363,11 +367,11 @@ def test_staff_query_gift_card_with_invalid_object_type(QUERY_GIFT_CARD_EVENTS = """- query giftCard($id: ID!) {+ query giftCard($id: ID!, $filter: GiftCardEventFilterInput) {giftCard(id: $id){idboughtInChannel- events {+ events(filter: $filter) {iddatetype@@ -381,8 +385,8 @@ QUERY_GIFT_CARD_EVENTS = """orderIdorderNumber- tag- oldTag+ tags+ oldTagsbalance {initialBalance {amount@@ -454,8 +458,8 @@ def test_query_gift_card_events(assert events_data[0]["email"] is Noneassert events_data[0]["orderId"] is Noneassert events_data[0]["orderNumber"] is None- assert events_data[0]["tag"] is None- assert events_data[0]["oldTag"] is None+ assert events_data[0]["tags"] is None+ assert events_data[0]["oldTags"] is Noneassert events_data[0]["balance"] is Noneassert events_data[0]["expiryDate"] is None@@ -471,8 +475,8 @@ def test_query_gift_card_events(assert events_data[1]["email"] == parameters["email"]assert events_data[1]["orderId"] == graphene.Node.to_global_id("Order", order.pk)assert events_data[1]["orderNumber"] == str(order.pk)- assert events_data[1]["tag"] == parameters["tag"]- assert events_data[1]["oldTag"] == parameters["old_tag"]+ assert events_data[1]["tags"] == parameters["tags"]+ assert events_data[1]["oldTags"] == parameters["old_tags"]assert (events_data[1]["balance"]["initialBalance"]["amount"]== parameters["balance"]["initial_balance"]@@ -626,3 +630,168 @@ def test_query_gift_card_bought_event(assert event_data["type"] == GiftCardEvents.BOUGHT.upper()assert event_data["user"] is Noneassert event_data["app"]["name"] == app.name+++ "gift_card_type, count",+ [+ (GiftCardEventsEnum.BOUGHT.name, 1),+ (GiftCardEventsEnum.USED_IN_ORDER.name, 2),+ ((GiftCardEventsEnum.ISSUED.name, 0)),+ ],+)+def test_query_gift_card_events_filter_by_type(+ gift_card_type,+ count,+ staff_api_client,+ gift_card_expiry_date,+ gift_card,+ order,+ app,+ permission_manage_gift_card,+ permission_manage_apps,+ permission_manage_users,+):+ # given+ previous_balance = 10.0+ balance_data = [(gift_card, previous_balance)]+ events.gift_cards_bought_event(+ [gift_card, gift_card_expiry_date], order.id, None, app+ )+ events.gift_cards_used_in_order_event(balance_data, 1, None, app)+ events.gift_cards_used_in_order_event(balance_data, 2, None, app)++ assert gift_card.events.count() == 3+ assert GiftCardEvent.objects.count() == 4++ variables = {+ "id": graphene.Node.to_global_id("GiftCard", gift_card.pk),+ "filter": {+ "type": gift_card_type,+ },+ }++ # when+ response = staff_api_client.post_graphql(+ QUERY_GIFT_CARD_EVENTS,+ variables,+ permissions=[+ permission_manage_gift_card,+ permission_manage_apps,+ permission_manage_users,+ ],+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["giftCard"]+ events_data = data["events"]+ assert len(events_data) == count+ for event_data in events_data:+ assert event_data["type"] == gift_card_type+++def test_query_gift_card_events_filter_by_orders(+ staff_api_client,+ gift_card_expiry_date,+ gift_card,+ app,+ permission_manage_gift_card,+ permission_manage_apps,+ permission_manage_users,+):+ # given+ previous_balance = 10.0+ order_pk_1 = 1+ events.gift_cards_bought_event(+ [gift_card, gift_card_expiry_date], order_pk_1, None, app+ )+ balance_data = [(gift_card, previous_balance)]+ order_pk_2 = 2+ events.gift_cards_used_in_order_event(balance_data, order_pk_2, None, app)+ order_pk_3 = 3+ events.gift_cards_used_in_order_event(balance_data, order_pk_3, None, app)++ assert gift_card.events.count() == 3+ assert GiftCardEvent.objects.count() == 4++ order_ids = [+ graphene.Node.to_global_id("Order", order_pk)+ for order_pk in [order_pk_1, order_pk_2]+ ]+ variables = {+ "id": graphene.Node.to_global_id("GiftCard", gift_card.pk),+ "filter": {+ "orders": order_ids,+ },+ }++ # when+ response = staff_api_client.post_graphql(+ QUERY_GIFT_CARD_EVENTS,+ variables,+ permissions=[+ permission_manage_gift_card,+ permission_manage_apps,+ permission_manage_users,+ ],+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["giftCard"]+ events_data = data["events"]+ assert len(events_data) == 2+ assert {event["orderId"] for event in events_data} == set(order_ids)+ assert {event["type"] for event in events_data} == {+ GiftCardEvents.USED_IN_ORDER.upper(),+ GiftCardEvents.BOUGHT.upper(),+ }+++def test_query_gift_card_events_filter_by_orders_no_events(+ staff_api_client,+ gift_card_expiry_date,+ gift_card,+ order,+ app,+ permission_manage_gift_card,+ permission_manage_apps,+ permission_manage_users,+):+ # given+ previous_balance = 10.0+ balance_data = [(gift_card, previous_balance)]+ order_pk = 1+ events.gift_cards_bought_event(+ [gift_card, gift_card_expiry_date], order.id, None, app+ )+ events.gift_cards_used_in_order_event(balance_data, order_pk, None, app)++ assert gift_card.events.count() == 2+ assert GiftCardEvent.objects.count() == 3++ order_id = graphene.Node.to_global_id("Order", 2)+ variables = {+ "id": graphene.Node.to_global_id("GiftCard", gift_card.pk),+ "filter": {+ "orders": [order_id],+ },+ }++ # when+ response = staff_api_client.post_graphql(+ QUERY_GIFT_CARD_EVENTS,+ variables,+ permissions=[+ permission_manage_gift_card,+ permission_manage_apps,+ permission_manage_users,+ ],+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["giftCard"]+ events_data = data["events"]+ assert not events_datadiff --git a/saleor/graphql/giftcard/tests/queries/test_gift_card_filtering.py b/saleor/graphql/giftcard/tests/queries/test_gift_card_filtering.pyindex 3d10a7161c..9a2ae6dee4 100644--- a/saleor/graphql/giftcard/tests/queries/test_gift_card_filtering.py+++ b/saleor/graphql/giftcard/tests/queries/test_gift_card_filtering.py@@ -10,7 +10,7 @@ QUERY_GIFT_CARDS = """edges {node {id- displayCode+ last4CodeCharsproduct {name}@@ -26,49 +26,6 @@ QUERY_GIFT_CARDS = """"""- "filter_value, expected_gift_card_indexes",- [- ("test-tag", [0]),- ("another-tag", [1]),- ("tag", [0, 1, 2]),- ("not existing", []),- ("", [0, 1, 2]),- ],-)-def test_query_filter_gift_cards_by_tag(- filter_value,- expected_gift_card_indexes,- staff_api_client,- gift_card,- gift_card_expiry_date,- gift_card_used,- permission_manage_gift_card,-):- # given- query = QUERY_GIFT_CARDS- gift_cards = [- gift_card,- gift_card_expiry_date,- gift_card_used,- ]- variables = {"filter": {"tag": filter_value}}-- # when- response = staff_api_client.post_graphql(- query, variables, permissions=[permission_manage_gift_card]- )-- # then- content = get_graphql_content(response)- data = content["data"]["giftCards"]["edges"]- assert len(data) == len(expected_gift_card_indexes)- assert {card["node"]["id"] for card in data} == {- graphene.Node.to_global_id("GiftCard", gift_cards[i].pk)- for i in expected_gift_card_indexes- }--@pytest.mark.parametrize("filter_value, expected_gift_card_indexes",[@@ -270,6 +227,47 @@ def test_query_filter_gift_cards_by_is_active(}+ "filter_value, expected_gift_card_indexes",+ [+ (True, [2]),+ (False, [0, 1]),+ ],+)+def test_query_filter_gift_cards_used(+ filter_value,+ expected_gift_card_indexes,+ staff_api_client,+ gift_card,+ gift_card_expiry_date,+ gift_card_used,+ permission_manage_gift_card,+):+ # given+ query = QUERY_GIFT_CARDS+ gift_cards = [+ gift_card,+ gift_card_expiry_date,+ gift_card_used,+ ]++ variables = {"filter": {"used": filter_value}}++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_gift_card]+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["giftCards"]["edges"]+ assert len(data) == len(expected_gift_card_indexes)+ assert {card["node"]["id"] for card in data} == {+ graphene.Node.to_global_id("GiftCard", gift_cards[i].pk)+ for i in expected_gift_card_indexes+ }++def test_query_filter_gift_cards_by_current_balance_no_currency_given(staff_api_client,gift_card,diff --git a/saleor/graphql/giftcard/tests/queries/test_gift_card_sorting.py b/saleor/graphql/giftcard/tests/queries/test_gift_card_sorting.pyindex 97792f3636..9c44102a95 100644--- a/saleor/graphql/giftcard/tests/queries/test_gift_card_sorting.py+++ b/saleor/graphql/giftcard/tests/queries/test_gift_card_sorting.py@@ -13,7 +13,7 @@ QUERY_GIFT_CARDS = """edges {node {id- displayCode+ last4CodeChars}}totalCount@@ -177,42 +177,3 @@ def test_sorting_gift_cards_by_used_by(assert [card["node"]["id"] for card in data] == [graphene.Node.to_global_id("GiftCard", card.pk) for card in gift_card_list]--- "direction",- ("ASC", "DESC"),-)-def test_sorting_gift_cards_by_tag(- direction,- staff_api_client,- gift_card,- gift_card_expiry_date,- gift_card_used,- permission_manage_gift_card,-):- # given- gift_card_list = [gift_card_expiry_date, gift_card_used, gift_card]-- variables = {- "sortBy": {- "direction": direction,- "field": "TAG",- }- }-- # when- response = staff_api_client.post_graphql(- QUERY_GIFT_CARDS, variables, permissions=[permission_manage_gift_card]- )-- # then- if direction == "DESC":- gift_card_list.reverse()-- content = get_graphql_content(response)- data = content["data"]["giftCards"]["edges"]- assert len(data) == 3- assert [card["node"]["id"] for card in data] == [- graphene.Node.to_global_id("GiftCard", card.pk) for card in gift_card_list- ]diff --git a/saleor/graphql/giftcard/tests/queries/test_gift_card_tags.py b/saleor/graphql/giftcard/tests/queries/test_gift_card_tags.pynew file mode 100644index 0000000000..0d03e2796d--- /dev/null+++ b/saleor/graphql/giftcard/tests/queries/test_gift_card_tags.py@@ -0,0 +1,66 @@+from ....tests.utils import assert_no_permission, get_graphql_content++QUERY_GIFT_CARD_TAGS = """+ query giftCardTags{+ giftCardTags(first: 10) {+ edges {+ node {+ id+ name+ }+ }+ totalCount+ }+ }+"""+++def test_query_gift_card_tags_by_staff(+ staff_api_client, gift_card_tag_list, permission_manage_gift_card+):+ # given+ query = QUERY_GIFT_CARD_TAGS++ # when+ response = staff_api_client.post_graphql(+ query, permissions=[permission_manage_gift_card]+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["giftCardTags"]["edges"]+ assert len(data) == len(gift_card_tag_list)+ assert {tag["node"]["name"] for tag in data} == {+ tag.name for tag in gift_card_tag_list+ }+++def test_query_gift_card_tags_by_app(+ app_api_client, gift_card_tag_list, permission_manage_gift_card+):+ # given+ query = QUERY_GIFT_CARD_TAGS++ # when+ response = app_api_client.post_graphql(+ query, permissions=[permission_manage_gift_card]+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["giftCardTags"]["edges"]+ assert len(data) == len(gift_card_tag_list)+ assert {tag["node"]["name"] for tag in data} == {+ tag.name for tag in gift_card_tag_list+ }+++def test_query_gift_card_tags_by_customer(api_client, gift_card_tag_list):+ # given+ query = QUERY_GIFT_CARD_TAGS++ # when+ response = api_client.post_graphql(query)++ # then+ assert_no_permission(response)diff --git a/saleor/graphql/giftcard/tests/queries/test_gift_card_tags_filtering.py b/saleor/graphql/giftcard/tests/queries/test_gift_card_tags_filtering.pynew file mode 100644index 0000000000..b3738ecf25--- /dev/null+++ b/saleor/graphql/giftcard/tests/queries/test_gift_card_tags_filtering.py@@ -0,0 +1,52 @@+import pytest++from ....tests.utils import get_graphql_content++QUERY_GIFT_CARD_TAGS = """+ query giftCardTags($filter: GiftCardTagFilterInput){+ giftCardTags(first: 10, filter: $filter) {+ edges {+ node {+ id+ name+ }+ }+ totalCount+ }+ }+"""+++ "value, expected_tag_indexes",+ [+ ("tag", [0, 1, 2, 3, 4]),+ ("test-tag", [0, 1, 2, 3, 4]),+ ("test", [0, 1, 2, 3, 4]),+ ("0", [0]),+ ("tag-3", [3]),+ ],+)+def test_filter_gift_card_tags_by_name(+ staff_api_client,+ gift_card_tag_list,+ permission_manage_gift_card,+ value,+ expected_tag_indexes,+):+ # given+ query = QUERY_GIFT_CARD_TAGS+ variables = {"filter": {"search": value}}++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_gift_card]+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["giftCardTags"]["edges"]+ assert len(data) == len(expected_tag_indexes)+ assert {tag["node"]["name"] for tag in data} == {+ gift_card_tag_list[index].name for index in expected_tag_indexes+ }diff --git a/saleor/graphql/giftcard/tests/queries/test_gift_cards.py b/saleor/graphql/giftcard/tests/queries/test_gift_cards.pyindex c9395ce9d6..82efc0536c 100644--- a/saleor/graphql/giftcard/tests/queries/test_gift_cards.py+++ b/saleor/graphql/giftcard/tests/queries/test_gift_cards.py@@ -8,7 +8,7 @@ QUERY_GIFT_CARDS = """edges {node {id- displayCode+ last4CodeChars}}totalCount@@ -37,9 +37,9 @@ def test_query_gift_cards_by_staff(data = content["data"]["giftCards"]["edges"]assert len(data) == 2assert data[0]["node"]["id"] == gift_card_created_by_staff_id- assert data[0]["node"]["displayCode"] == gift_card_created_by_staff.display_code+ assert data[0]["node"]["last4CodeChars"] == gift_card_created_by_staff.display_codeassert data[1]["node"]["id"] == gift_card_id- assert data[1]["node"]["displayCode"] == gift_card.display_code+ assert data[1]["node"]["last4CodeChars"] == gift_card.display_codedef test_query_gift_cards_by_app(@@ -62,9 +62,9 @@ def test_query_gift_cards_by_app(data = content["data"]["giftCards"]["edges"]assert len(data) == 2assert data[0]["node"]["id"] == gift_card_created_by_staff_id- assert data[0]["node"]["displayCode"] == gift_card_created_by_staff.display_code+ assert data[0]["node"]["last4CodeChars"] == gift_card_created_by_staff.display_codeassert data[1]["node"]["id"] == gift_card_id- assert data[1]["node"]["displayCode"] == gift_card.display_code+ assert data[1]["node"]["last4CodeChars"] == gift_card.display_codedef test_query_own_gift_cards(@@ -77,7 +77,7 @@ def test_query_own_gift_cards(edges {node {id- displayCode+ last4CodeCharscode}}@@ -91,6 +91,6 @@ def test_query_own_gift_cards(content = get_graphql_content(response)data = content["data"]["me"]["giftCards"]assert data["edges"][0]["node"]["id"] == gift_card_id- assert data["edges"][0]["node"]["displayCode"] == gift_card_used.display_code+ assert data["edges"][0]["node"]["last4CodeChars"] == gift_card_used.display_codeassert data["edges"][0]["node"]["code"] == gift_card_used.codeassert data["totalCount"] == 1diff --git a/saleor/graphql/giftcard/types.py b/saleor/graphql/giftcard/types.pyindex 90ca7ef837..22670643cb 100644--- a/saleor/graphql/giftcard/types.py+++ b/saleor/graphql/giftcard/types.py@@ -23,8 +23,16 @@ from ..meta.types import ObjectWithMetadatafrom ..order.dataloaders import OrderByIdLoaderfrom ..product.dataloaders.products import ProductByIdLoaderfrom ..utils import get_user_or_app_from_context-from .dataloaders import GiftCardEventsByGiftCardIdLoader+from .dataloaders import (+ GiftCardEventsByGiftCardIdLoader,+ GiftCardTagsByGiftCardIdLoader,+)from .enums import GiftCardEventsEnum+from .filters import (+ GiftCardEventFilterInput,+ filter_events_by_orders,+ filter_events_by_type,+)class GiftCardEventBalance(graphene.ObjectType):@@ -67,8 +75,14 @@ class GiftCardEvent(CountableDjangoObjectType):"User-friendly number of an order where gift card was used or bought."))- tag = graphene.String(description="The gift card tag.")- old_tag = graphene.String(description="Old gift card tag.")+ tags = graphene.List(+ graphene.NonNull(graphene.String),+ description="The list of gift card tags.",+ )+ old_tags = graphene.List(+ graphene.NonNull(graphene.String),+ description="The list of old gift card tags.",+ )balance = graphene.Field(GiftCardEventBalance, description="The gift card balance.")expiry_date = graphene.types.datetime.Date(description="The gift card expiry date.")old_expiry_date = graphene.types.datetime.Date(@@ -130,12 +144,12 @@ class GiftCardEvent(CountableDjangoObjectType):return str(order_id) if order_id else None@staticmethod- def resolve_tag(root: models.GiftCardEvent, _info):- return root.parameters.get("tag")+ def resolve_tags(root: models.GiftCardEvent, _info):+ return root.parameters.get("tags")@staticmethod- def resolve_old_tag(root: models.GiftCardEvent, _info):- return root.parameters.get("old_tag")+ def resolve_old_tags(root: models.GiftCardEvent, _info):+ return root.parameters.get("old_tags")@staticmethod@traced_resolver@@ -172,9 +186,17 @@ class GiftCardEvent(CountableDjangoObjectType):)+class GiftCardTag(CountableDjangoObjectType):+ class Meta:+ description = f"{ADDED_IN_31} The gift card tag."+ model = models.GiftCardTag+ interfaces = [graphene.relay.Node]+ only_fields = ["id", "name"]++class GiftCard(CountableDjangoObjectType):- display_code = graphene.String(- description="Code in format which allows displaying in a user interface.",+ last_4_code_chars = graphene.String(+ description="Last 4 characters of gift card code.",required=True,)code = graphene.String(@@ -215,10 +237,17 @@ class GiftCard(CountableDjangoObjectType):)events = graphene.List(graphene.NonNull(GiftCardEvent),+ filter=GiftCardEventFilterInput(+ description="Filtering options for gift card events."+ ),description=f"{ADDED_IN_31} List of events associated with the gift card.",required=True,)- tag = graphene.String(description=f"{ADDED_IN_31} The gift card tag.")+ tags = graphene.List(+ graphene.NonNull(GiftCardTag),+ description=f"{ADDED_IN_31} The gift card tag.",+ required=True,+ )bought_in_channel = graphene.String(description=("{ADDED_IN_31} Slug of the channel where the gift card was bought."@@ -255,13 +284,12 @@ class GiftCard(CountableDjangoObjectType):"initial_balance","current_balance","expiry_date",- "tag",]interfaces = [graphene.relay.Node, ObjectWithMetadata]model = models.GiftCard@staticmethod- def resolve_display_code(root: models.GiftCard, *_args, **_kwargs):+ def resolve_last_4_code_chars(root: models.GiftCard, *_args, **_kwargs):return root.display_code@staticmethod@@ -377,8 +405,25 @@ class GiftCard(CountableDjangoObjectType):@staticmethod@permission_required(GiftcardPermissions.MANAGE_GIFT_CARD)- def resolve_events(root: models.GiftCard, _info):- return GiftCardEventsByGiftCardIdLoader(_info.context).load(root.id)+ def resolve_events(root: models.GiftCard, info, **kwargs):+ def filter_events(events):+ event_filter = kwargs.get("filter", {})+ if event_type_value := event_filter.get("type"):+ events = filter_events_by_type(events, event_type_value)+ if orders_value := event_filter.get("orders"):+ events = filter_events_by_orders(events, orders_value)+ return events++ return (+ GiftCardEventsByGiftCardIdLoader(info.context)+ .load(root.id)+ .then(filter_events)+ )++ @staticmethod+ @permission_required(GiftcardPermissions.MANAGE_GIFT_CARD)+ def resolve_tags(root: models.GiftCard, info):+ return GiftCardTagsByGiftCardIdLoader(info.context).load(root.id)@staticmethod@traced_resolver@@ -444,3 +489,8 @@ class GiftCard(CountableDjangoObjectType):class GiftCardCountableConnection(CountableConnection):class Meta:node = GiftCard+++class GiftCardTagCountableConnection(CountableConnection):+ class Meta:+ node = GiftCardTagdiff --git a/saleor/graphql/order/filters.py b/saleor/graphql/order/filters.pyindex 54c8b959f3..0acc3dba4f 100644--- a/saleor/graphql/order/filters.py+++ b/saleor/graphql/order/filters.py@@ -1,8 +1,11 @@import django_filters-from django.db.models import Exists, OuterRef, Q, Sum+from django.db.models import Exists, IntegerField, OuterRef, Q, Sum+from django.db.models.functions import Castfrom django.utils import timezonefrom graphene_django.filter import GlobalIDMultipleChoiceFilter+from ...giftcard import GiftCardEvents+from ...giftcard.models import GiftCardEventfrom ...order.models import Order, OrderLinefrom ...order.search import search_ordersfrom ...product.models import ProductVariant@@ -110,6 +113,22 @@ def filter_order_ids(qs, _, values):return qs+def filter_gift_card_used(qs, _, value):+ return filter_by_gift_card(qs, value, GiftCardEvents.USED_IN_ORDER)+++def filter_gift_card_bought(qs, _, value):+ return filter_by_gift_card(qs, value, GiftCardEvents.BOUGHT)+++def filter_by_gift_card(qs, value, gift_card_type):+ gift_card_events = GiftCardEvent.objects.filter(type=gift_card_type).values(+ order_id=Cast("parameters__order_id", IntegerField())+ )+ lookup = Exists(gift_card_events.filter(order_id=OuterRef("id")))+ return qs.filter(lookup) if value is True else qs.exclude(lookup)++class DraftOrderFilter(MetadataFilterBase):customer = django_filters.CharFilter(method=filter_customer)created = ObjectTypeFilter(input_class=DateRangeInput, method=filter_created_range)@@ -135,6 +154,8 @@ class OrderFilter(DraftOrderFilter):)is_preorder = django_filters.BooleanFilter(method=filter_is_preorder)ids = GlobalIDMultipleChoiceFilter(method=filter_order_ids)+ gift_card_used = django_filters.BooleanFilter(method=filter_gift_card_used)+ gift_card_bought = django_filters.BooleanFilter(method=filter_gift_card_bought)class Meta:model = Orderdiff --git a/saleor/graphql/order/tests/test_fulfillment.py b/saleor/graphql/order/tests/test_fulfillment.pyindex ab13407de9..8e2aba32e1 100644--- a/saleor/graphql/order/tests/test_fulfillment.py+++ b/saleor/graphql/order/tests/test_fulfillment.py@@ -14,6 +14,7 @@ from ....order.fetch import OrderLineInfofrom ....order.models import Fulfillment, FulfillmentLine, FulfillmentStatus, OrderLinefrom ....plugins.manager import get_plugins_managerfrom ....product.models import Product, ProductVariant+from ....tests.utils import flush_post_commit_hooksfrom ....warehouse.models import Allocation, Stockfrom ...tests.utils import assert_no_permission, get_graphql_content@@ -572,6 +573,7 @@ def test_order_fulfill_with_gift_cards(query, variables, permissions=[permission_manage_orders])content = get_graphql_content(response)+ flush_post_commit_hooks()data = content["data"]["orderFulfill"]assert not data["errors"]gift_cards = GiftCard.objects.all()diff --git a/saleor/graphql/order/tests/test_order.py b/saleor/graphql/order/tests/test_order.pyindex 5534a5957c..672da78e83 100644--- a/saleor/graphql/order/tests/test_order.py+++ b/saleor/graphql/order/tests/test_order.py@@ -24,7 +24,7 @@ from ....core.prices import quantize_pricefrom ....core.taxes import TaxError, zero_taxed_moneyfrom ....discount.models import OrderDiscountfrom ....giftcard import GiftCardEvents-from ....giftcard.events import gift_cards_bought_event+from ....giftcard.events import gift_cards_bought_event, gift_cards_used_in_order_eventfrom ....order import FulfillmentStatus, OrderOrigin, OrderStatusfrom ....order import events as order_eventsfrom ....order.error_codes import OrderErrorCode@@ -936,7 +936,7 @@ def test_order_query_gift_cards(query OrderQuery($id: ID!) {order(id: $id) {giftCards {- displayCode+ last4CodeCharscurrentBalance {amount}@@ -954,7 +954,7 @@ def test_order_query_gift_cards(content = get_graphql_content(response)gift_card_data = content["data"]["order"]["giftCards"][0]- assert gift_card.display_code == gift_card_data["displayCode"]+ assert gift_card.display_code == gift_card_data["last4CodeChars"]assert (gift_card.current_balance.amount == gift_card_data["currentBalance"]["amount"])@@ -6743,6 +6743,118 @@ def test_order_query_with_filter_channels_with_empty_channel(assert len(orders) == 0+def test_order_query_with_filter_gift_card_used_true(+ orders_query_with_filter,+ staff_api_client,+ permission_manage_orders,+ gift_card,+ orders,+):+ # given+ gift_card_order = orders[0]+ gift_cards_used_in_order_event(+ [(gift_card, 20.0)], gift_card_order.id, staff_api_client.user, None+ )+ variables = {"filter": {"giftCardUsed": True}}++ # when+ response = staff_api_client.post_graphql(+ orders_query_with_filter, variables, permissions=(permission_manage_orders,)+ )++ # then+ content = get_graphql_content(response)+ orders = content["data"]["orders"]["edges"]+ assert len(orders) == 1+ assert orders[0]["node"]["id"] == graphene.Node.to_global_id(+ "Order", gift_card_order.id+ )+++def test_order_query_with_filter_gift_card_used_false(+ orders_query_with_filter,+ staff_api_client,+ permission_manage_orders,+ gift_card,+ orders,+):+ # given+ gift_card_order = orders[0]+ gift_card_order_id = graphene.Node.to_global_id("Order", gift_card_order.id)+ gift_cards_used_in_order_event(+ [(gift_card, 20.0)], gift_card_order.id, staff_api_client.user, None+ )+ variables = {"filter": {"giftCardUsed": False}}++ # when+ response = staff_api_client.post_graphql(+ orders_query_with_filter, variables, permissions=(permission_manage_orders,)+ )++ # then+ content = get_graphql_content(response)+ orders_data = content["data"]["orders"]["edges"]+ assert gift_card_order_id not in {+ order_data["node"]["id"] for order_data in orders_data+ }+++def test_order_query_with_filter_gift_card_bough_true(+ orders_query_with_filter,+ staff_api_client,+ permission_manage_orders,+ gift_card,+ orders,+):+ # given+ gift_card_order = orders[-1]+ gift_cards_bought_event(+ [gift_card], gift_card_order.id, staff_api_client.user, None+ )+ variables = {"filter": {"giftCardBought": True}}++ # when+ response = staff_api_client.post_graphql(+ orders_query_with_filter, variables, permissions=(permission_manage_orders,)+ )++ # then+ content = get_graphql_content(response)+ orders = content["data"]["orders"]["edges"]+ assert len(orders) == 1+ assert orders[0]["node"]["id"] == graphene.Node.to_global_id(+ "Order", gift_card_order.id+ )+++def test_order_query_with_filter_gift_card_bought_false(+ orders_query_with_filter,+ staff_api_client,+ permission_manage_orders,+ gift_card,+ orders,+):+ # given+ gift_card_order = orders[-1]+ gift_card_order_id = graphene.Node.to_global_id("Order", gift_card_order.id)+ gift_cards_bought_event(+ [gift_card], gift_card_order.id, staff_api_client.user, None+ )+ variables = {"filter": {"giftCardBought": False}}++ # when+ response = staff_api_client.post_graphql(+ orders_query_with_filter, variables, permissions=(permission_manage_orders,)+ )++ # then+ content = get_graphql_content(response)+ orders_data = content["data"]["orders"]["edges"]+ assert gift_card_order_id not in {+ order_data["node"]["id"] for order_data in orders_data+ }++@pytest.mark.parametrize("orders_filter, count",[diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 81560c9d1b..94c989d0f7 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -2194,6 +2194,18 @@ input ExportFileSortingInput {field: ExportFileSortField!}+type ExportGiftCards {+ exportFile: ExportFile+ errors: [ExportError!]!+}++input ExportGiftCardsInput {+ scope: ExportScope!+ filter: GiftCardFilterInput+ ids: [ID!]+ fileType: FileTypesEnum!+}+input ExportInfoInput {attributes: [ID!]warehouses: [ID!]@@ -2389,7 +2401,6 @@ type GiftCard implements Node & ObjectWithMetadata {code: String!isActive: Boolean!expiryDate: Date- tag: Stringcreated: DateTime!lastUsedOn: DateTimeinitialBalance: Money@@ -2397,14 +2408,15 @@ type GiftCard implements Node & ObjectWithMetadata {id: ID!privateMetadata: [MetadataItem]!metadata: [MetadataItem]!- displayCode: String!+ last4CodeChars: String!createdBy: UserusedBy: UsercreatedByEmail: StringusedByEmail: Stringapp: Appproduct: Product- events: [GiftCardEvent!]!+ events(filter: GiftCardEventFilterInput): [GiftCardEvent!]!+ tags: [GiftCardTag!]!boughtInChannel: Stringuser: User @deprecated(reason: "This field will be removed in Saleor 4.0. Use `createdBy` field instead.")endDate: DateTime @deprecated(reason: "This field will be removed in Saleor 4.0. Use `expiryDate` field instead.")@@ -2432,6 +2444,20 @@ type GiftCardBulkActivate {errors: [GiftCardError!]!}+type GiftCardBulkCreate {+ count: Int!+ giftCards: [GiftCard!]!+ errors: [GiftCardError!]!+}++input GiftCardBulkCreateInput {+ count: Int!+ balance: PriceInput!+ tags: [String!]+ expiryDate: Date+ isActive: Boolean!+}+type GiftCardBulkDeactivate {count: Int!errors: [GiftCardError!]!@@ -2460,7 +2486,7 @@ type GiftCardCreate {}input GiftCardCreateInput {- tag: String+ addTags: [String!]expiryDate: DatestartDate: DateendDate: Date@@ -2488,6 +2514,7 @@ type GiftCardError {field: Stringmessage: Stringcode: GiftCardErrorCode!+ tags: [String!]}enum GiftCardErrorCode {@@ -2497,6 +2524,8 @@ enum GiftCardErrorCode {NOT_FOUNDREQUIREDUNIQUE+ EXPIRED_GIFT_CARD+ DUPLICATED_INPUT_ITEM}type GiftCardEvent implements Node {@@ -2509,8 +2538,8 @@ type GiftCardEvent implements Node {email: StringorderId: IDorderNumber: String- tag: String- oldTag: String+ tags: [String!]+ oldTags: [String!]balance: GiftCardEventBalanceexpiryDate: DateoldExpiryDate: Date@@ -2523,6 +2552,11 @@ type GiftCardEventBalance {oldCurrentBalance: Money}+input GiftCardEventFilterInput {+ type: GiftCardEventsEnum+ orders: [ID!]+}+enum GiftCardEventsEnum {ISSUEDBOUGHT@@ -2531,7 +2565,7 @@ enum GiftCardEventsEnum {DEACTIVATEDBALANCE_RESETEXPIRY_DATE_UPDATED- TAG_UPDATED+ TAGS_UPDATEDSENT_TO_CUSTOMERRESENTNOTE_ADDED@@ -2541,10 +2575,10 @@ enum GiftCardEventsEnum {input GiftCardFilterInput {isActive: Booleanmetadata: [MetadataFilter]- tag: Stringtags: [String]products: [ID]usedBy: [ID]+ used: Booleancurrency: StringcurrentBalance: PriceRangeInputinitialBalance: PriceRangeInput@@ -2595,7 +2629,6 @@ input GiftCardSettingsUpdateInput {}enum GiftCardSortField {- TAGPRODUCTUSED_BYCURRENT_BALANCE@@ -2606,6 +2639,26 @@ input GiftCardSortingInput {field: GiftCardSortField!}+type GiftCardTag implements Node {+ id: ID!+ name: String!+}++type GiftCardTagCountableConnection {+ pageInfo: PageInfo!+ edges: [GiftCardTagCountableEdge!]!+ totalCount: Int+}++type GiftCardTagCountableEdge {+ node: GiftCardTag!+ cursor: String!+}++input GiftCardTagFilterInput {+ search: String+}+type GiftCardUpdate {giftCardErrors: [GiftCardError!]! @deprecated(reason: "This field will be removed in Saleor 4.0. Use `errors` field instead.")errors: [GiftCardError!]!@@ -2613,10 +2666,11 @@ type GiftCardUpdate {}input GiftCardUpdateInput {- tag: String+ addTags: [String!]expiryDate: DatestartDate: DateendDate: Date+ removeTags: [String!]balanceAmount: PositiveDecimal}@@ -4005,6 +4059,7 @@ type Mutation {giftCardUpdate(id: ID!, input: GiftCardUpdateInput!): GiftCardUpdategiftCardResend(input: GiftCardResendInput!): GiftCardResendgiftCardAddNote(id: ID!, input: GiftCardAddNoteInput!): GiftCardAddNote+ giftCardBulkCreate(input: GiftCardBulkCreateInput!): GiftCardBulkCreategiftCardBulkDelete(ids: [ID]!): GiftCardBulkDeletegiftCardBulkActivate(ids: [ID]!): GiftCardBulkActivategiftCardBulkDeactivate(ids: [ID]!): GiftCardBulkDeactivate@@ -4027,6 +4082,7 @@ type Mutation {voucherTranslate(id: ID!, input: NameTranslationInput!, languageCode: LanguageCodeEnum!): VoucherTranslatevoucherChannelListingUpdate(id: ID!, input: VoucherChannelListingInput!): VoucherChannelListingUpdateexportProducts(input: ExportProductsInput!): ExportProducts+ exportGiftCards(input: ExportGiftCardsInput!): ExportGiftCardsfileUpload(file: Upload!): FileUploadcheckoutAddPromoCode(checkoutId: ID, promoCode: String!, token: UUID): CheckoutAddPromoCodecheckoutBillingAddressUpdate(billingAddress: AddressInput!, checkoutId: ID, token: UUID): CheckoutBillingAddressUpdate@@ -4464,6 +4520,8 @@ input OrderFilterInput {isClickAndCollect: BooleanisPreorder: Booleanids: [ID]+ giftCardUsed: Boolean+ giftCardBought: Boolean}type OrderFulfill {@@ -6031,6 +6089,7 @@ type Query {giftCard(id: ID!): GiftCardgiftCards(sortBy: GiftCardSortingInput, filter: GiftCardFilterInput, before: String, after: String, first: Int, last: Int): GiftCardCountableConnectiongiftCardCurrencies: [String!]!+ giftCardTags(filter: GiftCardTagFilterInput, before: String, after: String, first: Int, last: Int): GiftCardTagCountableConnectionplugin(id: ID!): Pluginplugins(filter: PluginFilterInput, sortBy: PluginSortingInput, before: String, after: String, first: Int, last: Int): PluginCountableConnectionsale(id: ID!, channel: String): Salediff --git a/saleor/graphql/utils/validators.py b/saleor/graphql/utils/validators.pyindex a1482c18f3..9efcfeea49 100644--- a/saleor/graphql/utils/validators.py+++ b/saleor/graphql/utils/validators.py@@ -1,6 +1,6 @@from django.core.exceptions import ValidationError-from ..core.utils import get_duplicates_ids+from ..core.utils import get_duplicates_itemsdef check_for_duplicates(@@ -11,15 +11,15 @@ def check_for_duplicates(Raise error if some of items are duplicated."""error = None- duplicated_ids = get_duplicates_ids(+ duplicated_items = get_duplicates_items(input_data.get(add_field), input_data.get(remove_field))- if duplicated_ids:+ if duplicated_items:# add errorerror_msg = (- "The same object cannot be in both list" "for adding and removing items."+ "The same object cannot be in both list for adding and removing items.")- params = {error_class_field: list(duplicated_ids)}+ params = {error_class_field: list(duplicated_items)}error = ValidationError(message=error_msg, params=params)return errordiff --git a/saleor/plugins/admin_email/constants.py b/saleor/plugins/admin_email/constants.pyindex 66e6f6e92c..96d7b74d4a 100644--- a/saleor/plugins/admin_email/constants.py+++ b/saleor/plugins/admin_email/constants.py@@ -8,7 +8,7 @@ DEFAULT_EMAIL_TEMPLATES_PATH = os.path.join(STAFF_ORDER_CONFIRMATION_TEMPLATE_FIELD = "staff_order_confirmation_template"SET_STAFF_PASSWORD_TEMPLATE_FIELD = "set_staff_password_template"-CSV_PRODUCT_EXPORT_SUCCESS_TEMPLATE_FIELD = "csv_product_export_success_template"+CSV_EXPORT_SUCCESS_TEMPLATE_FIELD = "csv_export_success_template"CSV_EXPORT_FAILED_TEMPLATE_FIELD = "csv_export_failed_template"STAFF_PASSWORD_RESET_TEMPLATE_FIELD = "staff_password_reset_template"@@ -16,28 +16,28 @@ STAFF_PASSWORD_RESET_TEMPLATE_FIELD = "staff_password_reset_template"TEMPLATE_FIELDS = [STAFF_ORDER_CONFIRMATION_TEMPLATE_FIELD,SET_STAFF_PASSWORD_TEMPLATE_FIELD,- CSV_PRODUCT_EXPORT_SUCCESS_TEMPLATE_FIELD,+ CSV_EXPORT_SUCCESS_TEMPLATE_FIELD,CSV_EXPORT_FAILED_TEMPLATE_FIELD,STAFF_PASSWORD_RESET_TEMPLATE_FIELD,]SET_STAFF_PASSWORD_DEFAULT_TEMPLATE = "set_password.html"-CSV_PRODUCT_EXPORT_SUCCESS_DEFAULT_TEMPLATE = "export_products_file.html"+CSV_EXPORT_SUCCESS_DEFAULT_TEMPLATE = "export_success.html"CSV_EXPORT_FAILED_TEMPLATE_DEFAULT_TEMPLATE = "export_failed.html"STAFF_ORDER_CONFIRMATION_DEFAULT_TEMPLATE = "staff_confirm_order.html"STAFF_PASSWORD_RESET_DEFAULT_TEMPLATE = "password_reset.html"STAFF_ORDER_CONFIRMATION_SUBJECT_FIELD = "staff_order_confirmation_subject"SET_STAFF_PASSWORD_SUBJECT_FIELD = "set_staff_password_subject"-CSV_PRODUCT_EXPORT_SUCCESS_SUBJECT_FIELD = "csv_product_export_success_subject"+CSV_EXPORT_SUCCESS_SUBJECT_FIELD = "csv_export_success_subject"CSV_EXPORT_FAILED_SUBJECT_FIELD = "csv_export_failed_subject"STAFF_PASSWORD_RESET_SUBJECT_FIELD = "staff_password_reset_subject"STAFF_ORDER_CONFIRMATION_DEFAULT_SUBJECT = "Order {{ order.number }} details"SET_STAFF_PASSWORD_DEFAULT_SUBJECT = "Set password e-mail"-CSV_PRODUCT_EXPORT_SUCCESS_DEFAULT_SUBJECT = "Export products data"-CSV_EXPORT_FAILED_DEFAULT_SUBJECT = "Export products data"+CSV_EXPORT_SUCCESS_DEFAULT_SUBJECT = "Export {{ data_type }} data"+CSV_EXPORT_FAILED_DEFAULT_SUBJECT = "Export {{ data_type }} data"STAFF_PASSWORD_RESET_DEFAULT_SUBJECT = "Staff password reset"diff --git a/saleor/plugins/admin_email/default_email_templates/export_failed.html b/saleor/plugins/admin_email/default_email_templates/export_failed.htmlindex fd91cff7ef..79d319e633 100644--- a/saleor/plugins/admin_email/default_email_templates/export_failed.html+++ b/saleor/plugins/admin_email/default_email_templates/export_failed.html@@ -103,7 +103,7 @@<tr><td align="left" style="font-size: 0px; padding: 10px 25px; word-break: break-word;">- <div style="font-family:Ubuntu, Helvetica, Arial, sans-serif;font-size:13px;line-height:1;text-align:left;color:#000000;">Sorry, we couldn't finish exporting products, some unexpected errors occurred.+ <div style="font-family:Ubuntu, Helvetica, Arial, sans-serif;font-size:13px;line-height:1;text-align:left;color:#000000;">Sorry, we couldn't finish exporting {{data_type}}, some unexpected errors occurred.Please try again.</div></td>diff --git a/saleor/plugins/admin_email/default_email_templates/export_products_file.html b/saleor/plugins/admin_email/default_email_templates/export_success.htmlsimilarity index 98%rename from saleor/plugins/admin_email/default_email_templates/export_products_file.htmlrename to saleor/plugins/admin_email/default_email_templates/export_success.htmlindex 4003433302..208061192f 100644--- a/saleor/plugins/admin_email/default_email_templates/export_products_file.html+++ b/saleor/plugins/admin_email/default_email_templates/export_success.html@@ -103,7 +103,7 @@<tr><td align="left" style="font-size: 0px; padding: 10px 25px; word-break: break-word;">- <div style="font-family:Ubuntu, Helvetica, Arial, sans-serif;font-size:13px;line-height:1;text-align:left;color:#000000;">Your file with products data is ready to download: <a href="{{csv_link}}">{{csv_link}}</a></div>+ <div style="font-family:Ubuntu, Helvetica, Arial, sans-serif;font-size:13px;line-height:1;text-align:left;color:#000000;">Your file with {{data_type}} data is ready to download: <a href="{{csv_link}}">{{csv_link}}</a></div></td></tr>diff --git a/saleor/plugins/admin_email/notify_events.py b/saleor/plugins/admin_email/notify_events.pyindex 528a2c0f0d..1a2f21a734 100644--- a/saleor/plugins/admin_email/notify_events.py+++ b/saleor/plugins/admin_email/notify_events.py@@ -34,21 +34,19 @@ def send_set_staff_password_email()-def send_csv_product_export_success(- payload: dict, config: dict, plugin: "AdminEmailPlugin"-):+def send_csv_export_success(payload: dict, config: dict, plugin: "AdminEmailPlugin"):recipient_email = payload.get("recipient_email")if recipient_email:template = get_email_template_or_default(plugin,- constants.CSV_PRODUCT_EXPORT_SUCCESS_TEMPLATE_FIELD,- constants.CSV_PRODUCT_EXPORT_SUCCESS_DEFAULT_TEMPLATE,+ constants.CSV_EXPORT_SUCCESS_TEMPLATE_FIELD,+ constants.CSV_EXPORT_SUCCESS_DEFAULT_TEMPLATE,constants.DEFAULT_EMAIL_TEMPLATES_PATH,)subject = get_email_subject(plugin.configuration,- constants.CSV_PRODUCT_EXPORT_SUCCESS_SUBJECT_FIELD,- constants.CSV_PRODUCT_EXPORT_SUCCESS_DEFAULT_SUBJECT,+ constants.CSV_EXPORT_SUCCESS_SUBJECT_FIELD,+ constants.CSV_EXPORT_SUCCESS_DEFAULT_SUBJECT,)send_email_with_link_to_download_file_task.delay(recipient_email, payload, config, subject, templatediff --git a/saleor/plugins/admin_email/plugin.py b/saleor/plugins/admin_email/plugin.pyindex 20d4ff77cc..f3a56be926 100644--- a/saleor/plugins/admin_email/plugin.py+++ b/saleor/plugins/admin_email/plugin.py@@ -22,7 +22,7 @@ from ..models import EmailTemplate, PluginConfigurationfrom . import constantsfrom .notify_events import (send_csv_export_failed,- send_csv_product_export_success,+ send_csv_export_success,send_set_staff_password_email,send_staff_order_confirmation,send_staff_reset_password,@@ -35,7 +35,7 @@ logger = logging.getLogger(__name__)class AdminTemplate:staff_order_confirmation: Optional[str]set_staff_password_email: Optional[str]- csv_product_export_success: Optional[str]+ csv_export_success: Optional[str]csv_export_failed: Optional[str]staff_reset_password: Optional[str]@@ -44,9 +44,7 @@ def get_admin_template_map(templates: AdminTemplate):return {AdminNotifyEvent.STAFF_ORDER_CONFIRMATION: templates.staff_order_confirmation,AdminNotifyEvent.ACCOUNT_SET_STAFF_PASSWORD: templates.set_staff_password_email,- AdminNotifyEvent.CSV_PRODUCT_EXPORT_SUCCESS: (- templates.csv_product_export_success- ),+ AdminNotifyEvent.CSV_EXPORT_SUCCESS: (templates.csv_export_success),AdminNotifyEvent.CSV_EXPORT_FAILED: templates.csv_export_failed,AdminNotifyEvent.ACCOUNT_STAFF_RESET_PASSWORD: (templates.set_staff_password_email@@ -59,7 +57,7 @@ def get_admin_event_map():AdminNotifyEvent.STAFF_ORDER_CONFIRMATION: send_staff_order_confirmation,AdminNotifyEvent.ACCOUNT_SET_STAFF_PASSWORD: send_set_staff_password_email,AdminNotifyEvent.ACCOUNT_STAFF_RESET_PASSWORD: send_staff_reset_password,- AdminNotifyEvent.CSV_PRODUCT_EXPORT_SUCCESS: send_csv_product_export_success,+ AdminNotifyEvent.CSV_EXPORT_SUCCESS: send_csv_export_success,AdminNotifyEvent.CSV_EXPORT_FAILED: send_csv_export_failed,}@@ -97,11 +95,11 @@ class AdminEmailPlugin(BasePlugin):"value": DEFAULT_EMAIL_VALUE,},{- "name": constants.CSV_PRODUCT_EXPORT_SUCCESS_SUBJECT_FIELD,- "value": constants.CSV_PRODUCT_EXPORT_SUCCESS_DEFAULT_SUBJECT,+ "name": constants.CSV_EXPORT_SUCCESS_SUBJECT_FIELD,+ "value": constants.CSV_EXPORT_SUCCESS_DEFAULT_SUBJECT,},{- "name": constants.CSV_PRODUCT_EXPORT_SUCCESS_TEMPLATE_FIELD,+ "name": constants.CSV_EXPORT_SUCCESS_TEMPLATE_FIELD,"value": DEFAULT_EMAIL_VALUE,},{@@ -145,12 +143,12 @@ class AdminEmailPlugin(BasePlugin):"help_text": DEFAULT_TEMPLATE_HELP_TEXT,"label": "Set password email template",},- constants.CSV_PRODUCT_EXPORT_SUCCESS_SUBJECT_FIELD: {+ constants.CSV_EXPORT_SUCCESS_SUBJECT_FIELD: {"type": ConfigurationTypeField.STRING,"help_text": DEFAULT_SUBJECT_HELP_TEXT,"label": "CSV product export success subject",},- constants.CSV_PRODUCT_EXPORT_SUCCESS_TEMPLATE_FIELD: {+ constants.CSV_EXPORT_SUCCESS_TEMPLATE_FIELD: {"type": ConfigurationTypeField.MULTILINE,"help_text": DEFAULT_TEMPLATE_HELP_TEXT,"label": "CSV product export success template",@@ -205,8 +203,8 @@ class AdminEmailPlugin(BasePlugin):self.templates = AdminTemplate(csv_export_failed=configuration[constants.CSV_EXPORT_FAILED_TEMPLATE_FIELD],- csv_product_export_success=configuration[- constants.CSV_PRODUCT_EXPORT_SUCCESS_TEMPLATE_FIELD+ csv_export_success=configuration[+ constants.CSV_EXPORT_SUCCESS_TEMPLATE_FIELD],set_staff_password_email=configuration[constants.SET_STAFF_PASSWORD_TEMPLATE_FIELDdiff --git a/saleor/plugins/admin_email/tests/conftest.py b/saleor/plugins/admin_email/tests/conftest.pyindex b215de7ea3..c153a2173d 100644--- a/saleor/plugins/admin_email/tests/conftest.py+++ b/saleor/plugins/admin_email/tests/conftest.py@@ -9,9 +9,9 @@ from ..constants import (CSV_EXPORT_FAILED_DEFAULT_SUBJECT,CSV_EXPORT_FAILED_SUBJECT_FIELD,CSV_EXPORT_FAILED_TEMPLATE_FIELD,- CSV_PRODUCT_EXPORT_SUCCESS_DEFAULT_SUBJECT,- CSV_PRODUCT_EXPORT_SUCCESS_SUBJECT_FIELD,- CSV_PRODUCT_EXPORT_SUCCESS_TEMPLATE_FIELD,+ CSV_EXPORT_SUCCESS_DEFAULT_SUBJECT,+ CSV_EXPORT_SUCCESS_SUBJECT_FIELD,+ CSV_EXPORT_SUCCESS_TEMPLATE_FIELD,SET_STAFF_PASSWORD_DEFAULT_SUBJECT,SET_STAFF_PASSWORD_SUBJECT_FIELD,SET_STAFF_PASSWORD_TEMPLATE_FIELD,@@ -55,7 +55,7 @@ def admin_email_plugin(settings):csv_product_export_failed=DEFAULT_EMAIL_VALUE,set_staff_password_title=STAFF_ORDER_CONFIRMATION_DEFAULT_SUBJECT,staff_order_confirmation_title=SET_STAFF_PASSWORD_DEFAULT_SUBJECT,- csv_product_export_title=CSV_PRODUCT_EXPORT_SUCCESS_DEFAULT_SUBJECT,+ csv_product_export_title=CSV_EXPORT_SUCCESS_DEFAULT_SUBJECT,csv_product_export_failed_title=CSV_EXPORT_FAILED_DEFAULT_SUBJECT,staff_password_reset_template=DEFAULT_EMAIL_VALUE,staff_password_reset_subject=STAFF_PASSWORD_RESET_DEFAULT_SUBJECT,@@ -92,7 +92,7 @@ def admin_email_plugin(settings):"value": staff_order_confirmation,},{- "name": CSV_PRODUCT_EXPORT_SUCCESS_TEMPLATE_FIELD,+ "name": CSV_EXPORT_SUCCESS_TEMPLATE_FIELD,"value": csv_product_export,},{@@ -112,7 +112,7 @@ def admin_email_plugin(settings):"value": set_staff_password_title,},{- "name": CSV_PRODUCT_EXPORT_SUCCESS_SUBJECT_FIELD,+ "name": CSV_EXPORT_SUCCESS_SUBJECT_FIELD,"value": csv_product_export_title,},{diff --git a/saleor/plugins/admin_email/tests/test_notify_events.py b/saleor/plugins/admin_email/tests/test_notify_events.pyindex 1fd1d35954..4fbf302d52 100644--- a/saleor/plugins/admin_email/tests/test_notify_events.py+++ b/saleor/plugins/admin_email/tests/test_notify_events.py@@ -4,7 +4,7 @@ from ....account.notifications import get_default_user_payloadfrom ....order.notifications import get_default_order_payloadfrom ..notify_events import (send_csv_export_failed,- send_csv_product_export_success,+ send_csv_export_success,send_set_staff_password_email,send_staff_order_confirmation,send_staff_reset_password,@@ -58,15 +58,13 @@ def test_send_set_staff_password_email(mocked_email_task, admin_email_plugin):"saleor.plugins.admin_email.notify_events.""send_email_with_link_to_download_file_task.delay")-def test_send_csv_product_export_success(mocked_email_task, admin_email_plugin):+def test_send_csv_export_success(mocked_email_task, admin_email_plugin):payload = {"recipient_email": "[email protected]","csv_link": "http://127.0.0.1:8000/download/csv",}config = {"host": "localhost", "port": "1025"}- send_csv_product_export_success(- payload=payload, config=config, plugin=admin_email_plugin()- )+ send_csv_export_success(payload=payload, config=config, plugin=admin_email_plugin())mocked_email_task.assert_called_with(payload["recipient_email"], payload, config, mock.ANY, mock.ANY)diff --git a/saleor/plugins/admin_email/tests/test_plugin.py b/saleor/plugins/admin_email/tests/test_plugin.pyindex f667c638b8..cc83d9a549 100644--- a/saleor/plugins/admin_email/tests/test_plugin.py+++ b/saleor/plugins/admin_email/tests/test_plugin.py@@ -13,13 +13,13 @@ from ...manager import get_plugins_managerfrom ...models import PluginConfigurationfrom ..constants import (CSV_EXPORT_FAILED_TEMPLATE_FIELD,- CSV_PRODUCT_EXPORT_SUCCESS_TEMPLATE_FIELD,+ CSV_EXPORT_SUCCESS_TEMPLATE_FIELD,SET_STAFF_PASSWORD_TEMPLATE_FIELD,STAFF_ORDER_CONFIRMATION_TEMPLATE_FIELD,)from ..notify_events import (send_csv_export_failed,- send_csv_product_export_success,+ send_csv_export_success,send_set_staff_password_email,send_staff_order_confirmation,send_staff_reset_password,@@ -31,7 +31,7 @@ def test_event_map():assert get_admin_event_map() == {NotifyEventType.STAFF_ORDER_CONFIRMATION: send_staff_order_confirmation,NotifyEventType.ACCOUNT_SET_STAFF_PASSWORD: send_set_staff_password_email,- NotifyEventType.CSV_PRODUCT_EXPORT_SUCCESS: send_csv_product_export_success,+ NotifyEventType.CSV_EXPORT_SUCCESS: send_csv_export_success,NotifyEventType.CSV_EXPORT_FAILED: send_csv_export_failed,NotifyEventType.ACCOUNT_STAFF_RESET_PASSWORD: send_staff_reset_password,}@@ -42,7 +42,7 @@ def test_event_map():[NotifyEventType.STAFF_ORDER_CONFIRMATION,NotifyEventType.ACCOUNT_SET_STAFF_PASSWORD,- NotifyEventType.CSV_PRODUCT_EXPORT_SUCCESS,+ NotifyEventType.CSV_EXPORT_SUCCESS,NotifyEventType.CSV_EXPORT_FAILED,NotifyEventType.ACCOUNT_STAFF_RESET_PASSWORD,],@@ -185,7 +185,7 @@ def test_save_plugin_configuration_incorrect_template(mocked_open, admin_email_p"value": incorrect_template_str,},{- "name": CSV_PRODUCT_EXPORT_SUCCESS_TEMPLATE_FIELD,+ "name": CSV_EXPORT_SUCCESS_TEMPLATE_FIELD,"value": incorrect_template_str,},{"name": CSV_EXPORT_FAILED_TEMPLATE_FIELD, "value": incorrect_template_str},diff --git a/saleor/plugins/invoicing/tests/test_invoicing.py b/saleor/plugins/invoicing/tests/test_invoicing.pyindex 6102f8104a..b7b2f961f7 100644--- a/saleor/plugins/invoicing/tests/test_invoicing.py+++ b/saleor/plugins/invoicing/tests/test_invoicing.py@@ -1,12 +1,17 @@from datetime import datetime+from decimal import Decimalfrom unittest.mock import Mock, patchimport pytz+from prices import Money-from ....plugins.invoicing.utils import (+from ....giftcard.events import gift_cards_used_in_order_event+from ....giftcard.models import GiftCard+from ..utils import (chunk_products,generate_invoice_number,generate_invoice_pdf,+ get_gift_cards_payment_amount,get_product_limit_first_page,make_full_invoice_number,)@@ -32,11 +37,20 @@ def test_get_product_limit_first_page(product):@patch("saleor.plugins.invoicing.utils.get_template")@patch("saleor.plugins.invoicing.utils.os")def test_generate_invoice_pdf_for_order(- os_mock, get_template_mock, HTML_mock, fulfilled_order+ os_mock, get_template_mock, HTML_mock, fulfilled_order, customer_user, gift_card):get_template_mock.return_value.render = Mock(return_value="<html></html>")os_mock.path.join.return_value = "test"+ previous_current_balance = gift_card.current_balance+ gift_card.current_balance = Money(Decimal(5.0), "USD")+ gift_card.save(update_fields=["current_balance_amount"])++ balance_data = [(gift_card, previous_current_balance.amount)]+ gift_cards_used_in_order_event(+ balance_data, fulfilled_order.id, customer_user, None+ )+content, creation = generate_invoice_pdf(fulfilled_order.invoices.first())get_template_mock.return_value.render.assert_called_once_with(@@ -44,6 +58,7 @@ def test_generate_invoice_pdf_for_order("invoice": fulfilled_order.invoices.first(),"creation_date": datetime.now(tz=pytz.utc).strftime("%d %b %Y"),"order": fulfilled_order,+ "gift_cards_payment": previous_current_balance - gift_card.current_balance,"font_path": "file://test","products_first_page": list(fulfilled_order.lines.all()),"rest_of_products": [],@@ -64,3 +79,44 @@ def test_generate_invoice_number_invalid_numeration(fulfilled_order):def test_generate_invoice_number_no_existing_invoice(fulfilled_order):fulfilled_order.invoices.all().delete()assert generate_invoice_number() == make_full_invoice_number()+++def test_get_gift_cards_payment_amount(+ order, gift_card, gift_card_expiry_date, gift_card_used, customer_user+):+ # given+ previous_current_balance_gift_card = gift_card.current_balance.amount+ previous_current_balance_gift_card_used = gift_card_used.current_balance.amount++ new_current_value = Decimal(5.0)+ gift_card.current_balance = Money(new_current_value, "USD")+ gift_card_used.current_balance = Money(new_current_value, "USD")+ GiftCard.objects.bulk_update(+ [gift_card, gift_card_used], ["current_balance_amount"]+ )++ balance_data = [+ (gift_card, previous_current_balance_gift_card),+ (gift_card_used, previous_current_balance_gift_card_used),+ ]++ gift_cards_used_in_order_event(balance_data, order.id, customer_user, None)++ # when+ gift_cards_payment = get_gift_cards_payment_amount(order)++ # then+ value = (previous_current_balance_gift_card - new_current_value) + (+ previous_current_balance_gift_card_used - new_current_value+ )+ assert gift_cards_payment == Money(value, order.currency)+++def test_get_gift_cards_payment_amount_equal_zero(+ order, gift_card, gift_card_expiry_date, gift_card_used, customer_user+):+ # when+ gift_cards_payment = get_gift_cards_payment_amount(order)++ # then+ assert gift_cards_payment == Money(0, order.currency)diff --git a/saleor/plugins/invoicing/utils.py b/saleor/plugins/invoicing/utils.pyindex b20d6d9fb7..b87aec273b 100644--- a/saleor/plugins/invoicing/utils.py+++ b/saleor/plugins/invoicing/utils.py@@ -1,12 +1,16 @@import osimport refrom datetime import datetime+from decimal import Decimalimport pytzfrom django.conf import settingsfrom django.template.loader import get_template+from prices import Moneyfrom weasyprint import HTML+from ...giftcard import GiftCardEvents+from ...giftcard.models import GiftCardEventfrom ...invoice.models import InvoiceMAX_PRODUCTS_WITH_TABLE = 3@@ -62,6 +66,19 @@ def get_product_limit_first_page(products):return MAX_PRODUCTS_WITHOUT_TABLE+def get_gift_cards_payment_amount(order):+ events = GiftCardEvent.objects.filter(+ type=GiftCardEvents.USED_IN_ORDER, parameters__order_id=order.id+ )+ total_paid = 0+ for event in events:+ balance = event.parameters["balance"]+ total_paid += Decimal(balance["old_current_balance"]) - Decimal(+ balance["current_balance"]+ )+ return Money(total_paid, order.currency)++def generate_invoice_pdf(invoice):font_path = os.path.join(settings.PROJECT_ROOT, "templates", "invoices", "inter.ttf"@@ -75,12 +92,15 @@ def generate_invoice_pdf(invoice):rest_of_products = chunk_products(all_products[product_limit_first_page:], MAX_PRODUCTS_PER_PAGE)+ order = invoice.order+ gift_cards_payment = get_gift_cards_payment_amount(order)creation_date = datetime.now(tz=pytz.utc)rendered_template = get_template("invoices/invoice.html").render({"invoice": invoice,"creation_date": creation_date.strftime("%d %b %Y"),- "order": invoice.order,+ "order": order,+ "gift_cards_payment": gift_cards_payment,"font_path": f"file://{font_path}","products_first_page": products_first_page,"rest_of_products": rest_of_products,diff --git a/saleor/settings.py b/saleor/settings.pyindex ee6c823773..561f298079 100644--- a/saleor/settings.py+++ b/saleor/settings.py@@ -512,6 +512,10 @@ CELERY_BEAT_SCHEDULE = {"task": "saleor.core.tasks.delete_event_payloads_task","schedule": timedelta(days=1),},+ "deactivate-expired-gift-cards": {+ "task": "saleor.giftcard.tasks.deactivate_expired_cards_task",+ "schedule": crontab(hour=0, minute=0),+ },}EVENT_PAYLOAD_DELETE_PERIOD = timedelta(diff --git a/saleor/static/placeholders/saleordemoproduct_giftcard_01.png b/saleor/static/placeholders/saleordemoproduct_giftcard_01.pngnew file mode 100644index 0000000000..72783da02bBinary files /dev/null and b/saleor/static/placeholders/saleordemoproduct_giftcard_01.png differdiff --git a/saleor/static/placeholders/saleordemoproduct_giftcard_02.png b/saleor/static/placeholders/saleordemoproduct_giftcard_02.pngnew file mode 100644index 0000000000..012621ba44Binary files /dev/null and b/saleor/static/placeholders/saleordemoproduct_giftcard_02.png differdiff --git a/saleor/static/populatedb_data.json b/saleor/static/populatedb_data.jsonindex 2a23919422..56197c3d73 100644--- a/saleor/static/populatedb_data.json+++ b/saleor/static/populatedb_data.json@@ -266,6 +266,26 @@"level": 1}},+ {+ "model": "product.category",+ "pk": 24,+ "fields": {+ "private_metadata": {},+ "metadata": {},+ "seo_title": "",+ "seo_description": "",+ "name": "Gift cards",+ "slug": "gift-cards",+ "description": {},+ "parent": 7,+ "background_image": "",+ "background_image_alt": "",+ "lft": 8,+ "rght": 9,+ "tree_id": 1,+ "level": 1+ }+ },{"model": "product.producttype","pk": 7,@@ -277,11 +297,11 @@},"name": "Paint","slug": "paint",+ "kind": "normal","has_variants": true,"is_shipping_required": true,"is_digital": false,- "weight": "1.0:kg",- "kind": "normal"+ "weight": "1.0:kg"}},{@@ -295,11 +315,11 @@},"name": "Music","slug": "music",+ "kind": "normal","has_variants": true,"is_shipping_required": true,"is_digital": false,- "weight": "0.2:kg",- "kind": "normal"+ "weight": "0.2:kg"}},{@@ -313,11 +333,11 @@},"name": "Juice","slug": "juice",+ "kind": "normal","has_variants": true,"is_shipping_required": true,"is_digital": false,- "weight": "1.0:kg",- "kind": "normal"+ "weight": "1.0:kg"}},{@@ -331,11 +351,11 @@},"name": "Wine","slug": "wine",+ "kind": "normal","has_variants": false,"is_shipping_required": true,"is_digital": false,- "weight": "1.0:kg",- "kind": "normal"+ "weight": "1.0:kg"}},{@@ -349,11 +369,11 @@},"name": "Beer","slug": "beer",+ "kind": "normal","has_variants": false,"is_shipping_required": true,"is_digital": false,- "weight": "1.0:kg",- "kind": "normal"+ "weight": "1.0:kg"}},{@@ -367,11 +387,11 @@},"name": "Cushion","slug": "cushion",+ "kind": "normal","has_variants": true,"is_shipping_required": true,"is_digital": false,- "weight": "0.5:kg",- "kind": "normal"+ "weight": "0.5:kg"}},{@@ -385,11 +405,11 @@},"name": "Shoe","slug": "shoe",+ "kind": "normal","has_variants": true,"is_shipping_required": true,"is_digital": false,- "weight": "1.0:kg",- "kind": "normal"+ "weight": "1.0:kg"}},{@@ -403,11 +423,11 @@},"name": "Top (clothing)","slug": "top-clothing",+ "kind": "normal","has_variants": true,"is_shipping_required": true,"is_digital": false,- "weight": "1.0:kg",- "kind": "normal"+ "weight": "1.0:kg"}},{@@ -418,11 +438,41 @@"metadata": {},"name": "Audiobook","slug": "e-book",+ "kind": "normal","has_variants": true,"is_shipping_required": false,"is_digital": true,- "weight": "0.0:kg",- "kind": "normal"+ "weight": "0.0:kg"+ }+ },+ {+ "model": "product.producttype",+ "pk": 16,+ "fields": {+ "private_metadata": {},+ "metadata": {},+ "name": "Gift card",+ "slug": "gift-card",+ "kind": "gift_card",+ "has_variants": true,+ "is_shipping_required": false,+ "is_digital": false,+ "weight": "0.0:kg"+ }+ },+ {+ "model": "product.producttype",+ "pk": 16,+ "fields": {+ "private_metadata": {},+ "metadata": {},+ "name": "Gift card",+ "slug": "gift-card",+ "kind": "gift_card",+ "has_variants": true,+ "is_shipping_required": false,+ "is_digital": false,+ "weight": "0.0:kg"}},{@@ -1600,6 +1650,32 @@"weight": "0.0:kg"}},+ {+ "model": "product.product",+ "pk": 125,+ "fields": {+ "private_metadata": {},+ "metadata": {},+ "seo_title": "",+ "seo_description": "",+ "product_type": 16,+ "name": "Gift card",+ "slug": "gift-card",+ "description": {+ "blocks": [{+ "data": {+ "text": "Gift card to use in the shop."+ },+ "type": "paragraph"+ }]+ },+ "description_plaintext": "",+ "category": 24,+ "updated_at": "2021-09-03T07:42:09.262Z",+ "charge_taxes": false,+ "weight": "0.0:kg"+ }+ },{"model": "product.productchannellisting","pk": 1,@@ -2523,6 +2599,34 @@"currency": "PLN"}},+ {+ "model": "product.productchannellisting",+ "pk": 72,+ "fields": {+ "publication_date": "2020-01-01",+ "is_published": true,+ "product": 125,+ "channel": 2,+ "visible_in_listings": true,+ "available_for_purchase": "2020-08-31",+ "currency": "PLN",+ "discounted_price_amount": "100.000"+ }+ },+ {+ "model": "product.productchannellisting",+ "pk": 73,+ "fields": {+ "publication_date": "2020-01-01",+ "is_published": true,+ "product": 125,+ "channel": 1,+ "visible_in_listings": true,+ "available_for_purchase": "2020-08-31",+ "currency": "USD",+ "discounted_price_amount": "100.000"+ }+ },{"model": "product.productvariant","pk": 171,@@ -4271,6 +4375,20 @@"preorder_global_threshold": 10}},+ {+ "model": "product.productvariant",+ "pk": 323,+ "fields": {+ "private_metadata": {},+ "metadata": {},+ "sku": "324546",+ "name": "100 PLN",+ "product": 125,+ "track_inventory": false,+ "weight": null,+ "default": true+ }+ },{"model": "product.productvariantchannellisting","pk": 1,@@ -6704,6 +6822,28 @@"preorder_quantity_threshold": 2}},+ {+ "model": "product.productvariantchannellisting",+ "pk": 222,+ "fields": {+ "variant": 323,+ "channel": 2,+ "currency": "PLN",+ "price_amount": "100.000",+ "cost_price_amount": null+ }+ },+ {+ "model": "product.productvariantchannellisting",+ "pk": 223,+ "fields": {+ "variant": 323,+ "channel": 1,+ "currency": "USD",+ "price_amount": "100.000",+ "cost_price_amount": null+ }+ },{"model": "attribute.assignedproductattribute","pk": 1,diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex 29797b7da1..b1bd6988d9 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -59,7 +59,7 @@ from ..discount.models import (VoucherTranslation,)from ..giftcard import GiftCardEvents-from ..giftcard.models import GiftCard, GiftCardEvent+from ..giftcard.models import GiftCard, GiftCardEvent, GiftCardTagfrom ..menu.models import Menu, MenuItem, MenuItemTranslationfrom ..order import OrderOrigin, OrderStatusfrom ..order.actions import cancel_fulfillment, fulfill_order_lines@@ -3301,16 +3301,24 @@ def checkout_line_with_reserved_preorder_item(return checkout_line+def gift_card_tag_list(db):+ tags = [GiftCardTag(name=f"test-tag-{i}") for i in range(5)]+ return GiftCardTag.objects.bulk_create(tags)++@pytest.fixturedef gift_card(customer_user):- return GiftCard.objects.create(+ gift_card = GiftCard.objects.create(code="never_expiry",created_by=customer_user,created_by_email=customer_user.email,initial_balance=Money(10, "USD"),current_balance=Money(10, "USD"),- tag="test-tag",)+ tag, _ = GiftCardTag.objects.get_or_create(name="test-tag")+ gift_card.tags.add(tag)+ return gift_card@pytest.fixture@@ -3327,20 +3335,22 @@ def gift_card_with_metadata(customer_user):@pytest.fixturedef gift_card_expiry_date(customer_user):- return GiftCard.objects.create(+ gift_card = GiftCard.objects.create(code="expiry_date",created_by=customer_user,created_by_email=customer_user.email,initial_balance=Money(20, "USD"),current_balance=Money(20, "USD"),expiry_date=datetime.date.today() + datetime.timedelta(days=100),- tag="another-tag",)+ tag = GiftCardTag.objects.create(name="another-tag")+ gift_card.tags.add(tag)+ return gift_card@pytest.fixturedef gift_card_used(staff_user, customer_user):- return GiftCard.objects.create(+ gift_card = GiftCard.objects.create(code="giftcard_used",created_by=staff_user,used_by=customer_user,@@ -3348,20 +3358,24 @@ def gift_card_used(staff_user, customer_user):used_by_email=customer_user.email,initial_balance=Money(100, "USD"),current_balance=Money(80, "USD"),- tag="tag",)+ tag = GiftCardTag.objects.create(name="tag")+ gift_card.tags.add(tag)+ return gift_card@pytest.fixturedef gift_card_created_by_staff(staff_user):- return GiftCard.objects.create(+ gift_card = GiftCard.objects.create(code="created_by_staff",created_by=staff_user,created_by_email=staff_user.email,initial_balance=Money(10, "USD"),current_balance=Money(10, "USD"),- tag="test-tag",)+ tag, _ = GiftCardTag.objects.get_or_create(name="test-tag")+ gift_card.tags.add(tag)+ return gift_card@pytest.fixture@@ -3370,8 +3384,8 @@ def gift_card_event(gift_card, order, app, staff_user):"message": "test message","email": "[email protected]","order_id": order.pk,- "tag": "test tag",- "old_tag": "test old tag",+ "tags": ["test tag"],+ "old_tags": ["test old tag"],"balance": {"currency": "USD","initial_balance": 10,diff --git a/templates/invoices/invoice.html b/templates/invoices/invoice.htmlindex f2336a4057..5259710430 100644--- a/templates/invoices/invoice.html+++ b/templates/invoices/invoice.html@@ -158,12 +158,12 @@}.cell-total-price {- width: 15%;+ width: 20%;text-align: right;}.cell-summary {- width: 80%;+ width: 70%;text-align: right;padding-right: 30px;}@@ -319,7 +319,7 @@{% if product_set|length > 11 %}<div class="page-break"></div>{% endif %}- {% include "invoices/invoice_summary_table.html" with order=order %}+ {% include "invoices/invoice_summary_table.html" with order=order gift_cards_payment=gift_cards_payment %}{% endif %}{% endfor %}{% endif %}diff --git a/templates/invoices/invoice_summary_table.html b/templates/invoices/invoice_summary_table.htmlindex 6e8205fd33..1048e55bb3 100644--- a/templates/invoices/invoice_summary_table.html+++ b/templates/invoices/invoice_summary_table.html@@ -34,6 +34,19 @@</span></td></tr>+ {% if gift_cards_payment.amount > 0 %}+ <tr class="summary-row">+ <td class="cell-summary">+ <span class="normal-text-table">Gift cards</span>+ </td>+ <td class="cell-quantity"></td>+ <td class="cell-total-price">+ <span class="header-item">+ -{% price gift_cards_payment %}+ </span>+ </td>+ </tr>+ {% endif %}<tr class="summary-row"><td class="cell-summary"><span class="normal-text-table"><b>Grand Total</b></span>