Skip to content

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

Deactivate gift cards when cancel order and block refund operations (#8067)

Iga Karbowiak5744670248e5
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.py
index 20e2377706..8328f6f027 100644
--- a/saleor/checkout/complete_checkout.py
+++ b/saleor/checkout/complete_checkout.py
@@ -197,6 +197,7 @@ def _create_line_for_order(
translated_variant_name=translated_variant_name,
product_sku=variant.sku,
is_shipping_required=variant.is_shipping_required(),
+ is_gift_card=variant.is_gift_card(),
quantity=quantity,
variant=variant,
unit_price=unit_price, # type: ignore
diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.py
index 2376ffa228..0d3df378f2 100644
--- a/saleor/core/utils/random_data.py
+++ b/saleor/core/utils/random_data.py
@@ -600,6 +600,7 @@ def create_order_lines(order, discounts, how_many=10):
variant_name=str(variant),
product_sku=variant.sku,
is_shipping_required=variant.is_shipping_required(),
+ is_gift_card=variant.is_gift_card(),
quantity=quantity,
variant=variant,
unit_price=unit_price,
diff --git a/saleor/giftcard/tests/test_utils.py b/saleor/giftcard/tests/test_utils.py
index d2e32c84fe..8463f21f10 100644
--- a/saleor/giftcard/tests/test_utils.py
+++ b/saleor/giftcard/tests/test_utils.py
@@ -12,16 +12,18 @@ from ...order.models import OrderLine
from ...plugins.manager import get_plugins_manager
from ...site import GiftCardSettingsExpiryType
from ...warehouse.models import Allocation
-from .. import GiftCardEvents
+from .. import GiftCardEvents, events
from ..models import GiftCardEvent
from ..utils import (
add_gift_card_code_to_checkout,
calculate_expiry_date,
+ deactivate_order_gift_cards,
fulfill_gift_card_lines,
fulfill_non_shippable_gift_cards,
get_gift_card_lines,
get_non_shippable_gift_card_lines,
gift_cards_create,
+ order_has_gift_card_lines,
remove_gift_card_code_from_checkout,
)
@@ -585,3 +587,52 @@ def test_fulfill_gift_card_lines_lack_of_stock(
# when
with pytest.raises(ValidationError):
fulfill_gift_card_lines(lines, staff_user, None, order, manager)
+
+
+def test_deactivate_order_gift_cards(
+ gift_card, gift_card_expiry_date, gift_card_created_by_staff, order, staff_user
+):
+ # given
+ bought_cards = [gift_card, gift_card_expiry_date]
+ events.gift_cards_bought_event(bought_cards, order.id, staff_user, None)
+
+ for card in [gift_card, gift_card_expiry_date, gift_card_created_by_staff]:
+ assert card.is_active
+
+ # when
+ deactivate_order_gift_cards(order.id, staff_user, None)
+
+ # then
+ for card in bought_cards:
+ card.refresh_from_db()
+ assert not card.is_active
+ assert card.events.filter(type=GiftCardEvents.DEACTIVATED)
+
+ assert gift_card_created_by_staff.is_active
+ assert not gift_card_created_by_staff.events.filter(type=GiftCardEvents.DEACTIVATED)
+
+
+def test_deactivate_order_gift_cards_no_order_gift_cards(
+ gift_card, gift_card_expiry_date, gift_card_created_by_staff, order, staff_user
+):
+ # given
+ cards = [gift_card, gift_card_expiry_date, gift_card_created_by_staff]
+ for card in cards:
+ assert card.is_active
+
+ # when
+ deactivate_order_gift_cards(order.id, staff_user, None)
+
+ # then
+ for card in cards:
+ card.refresh_from_db()
+ assert card.is_active
+
+
+def test_order_has_gift_card_lines_true(gift_card_shippable_order_line):
+ order = gift_card_shippable_order_line.order
+ assert order_has_gift_card_lines(order) is True
+
+
+def test_order_has_gift_card_lines_false(order):
+ assert order_has_gift_card_lines(order) is False
diff --git a/saleor/giftcard/utils.py b/saleor/giftcard/utils.py
index 7b64c52794..dc077917ff 100644
--- a/saleor/giftcard/utils.py
+++ b/saleor/giftcard/utils.py
@@ -16,8 +16,8 @@ from ..order.models import OrderLine
from ..product import ProductTypeKind
from ..product.models import Product, ProductType, ProductVariant
from ..site import GiftCardSettingsExpiryType
-from . import events
-from .models import GiftCard
+from . import GiftCardEvents, events
+from .models import GiftCard, GiftCardEvent
from .notifications import send_gift_card_notification
if TYPE_CHECKING:
@@ -243,3 +243,22 @@ def send_gift_cards_to_customer(
channel_slug,
resending=False,
)
+
+
+def deactivate_order_gift_cards(
+ order_id: int, user: Optional["User"], app: Optional["App"]
+):
+ gift_card_events = GiftCardEvent.objects.filter(
+ type=GiftCardEvents.BOUGHT, parameters__order_id=order_id
+ )
+ gift_cards = GiftCard.objects.filter(
+ Exists(gift_card_events.filter(gift_card_id=OuterRef("id")))
+ )
+ gift_cards.update(is_active=False)
+ events.gift_cards_deactivated_event(
+ gift_cards.values_list("id", flat=True), user, app
+ )
+
+
+def order_has_gift_card_lines(order):
+ return any(order.lines.filter(is_gift_card=True))
diff --git a/saleor/graphql/order/mutations/fulfillments.py b/saleor/graphql/order/mutations/fulfillments.py
index 04eaa8b23c..efe767a327 100644
--- a/saleor/graphql/order/mutations/fulfillments.py
+++ b/saleor/graphql/order/mutations/fulfillments.py
@@ -7,7 +7,11 @@ from django.template.defaultfilters import pluralize
from ....core.exceptions import InsufficientStock
from ....core.permissions import OrderPermissions
from ....core.tracing import traced_atomic_transaction
-from ....giftcard.utils import get_gift_card_lines, gift_cards_create
+from ....giftcard.utils import (
+ get_gift_card_lines,
+ gift_cards_create,
+ order_has_gift_card_lines,
+)
from ....order import FulfillmentLineData, FulfillmentStatus, OrderLineData
from ....order import models as order_models
from ....order.actions import (
@@ -362,9 +366,24 @@ class FulfillmentCancel(BaseMutation):
}
)
+ @classmethod
+ def validate_order(cls, order):
+ if order_has_gift_card_lines(order):
+ raise ValidationError(
+ {
+ "fulfillment": ValidationError(
+ "Cannot cancel fulfillment with gift card lines.",
+ code=OrderErrorCode.CANNOT_CANCEL_FULFILLMENT.value,
+ )
+ }
+ )
+
@classmethod
def perform_mutation(cls, _root, info, **data):
fulfillment = cls.get_node_or_error(info, data.get("id"), only_type=Fulfillment)
+ order = fulfillment.order
+
+ cls.validate_order(order)
warehouse = None
if fulfillment.status == FulfillmentStatus.WAITING_FOR_APPROVAL:
@@ -376,7 +395,6 @@ class FulfillmentCancel(BaseMutation):
cls.validate_fulfillment(fulfillment, warehouse)
- order = fulfillment.order
if fulfillment.status == FulfillmentStatus.WAITING_FOR_APPROVAL:
fulfillment = cancel_waiting_fulfillment(
fulfillment,
@@ -510,19 +528,32 @@ class FulfillmentRefundAndReturnProductBase(BaseMutation):
cleaned_input["payment"] = payment
@classmethod
- def clean_amount_to_refund(cls, amount_to_refund, payment, cleaned_input):
- if amount_to_refund is not None and amount_to_refund > payment.captured_amount:
- raise ValidationError(
- {
- "amount_to_refund": ValidationError(
- (
- "The amountToRefund is greater than the maximal possible "
- "amount to refund."
+ def clean_amount_to_refund(cls, order, amount_to_refund, payment, cleaned_input):
+ if amount_to_refund is not None:
+ if order_has_gift_card_lines(order):
+ raise ValidationError(
+ {
+ "amount_to_refund": ValidationError(
+ (
+ "Cannot specified amount to refund when order has "
+ "gift card lines."
+ ),
+ code=OrderErrorCode.CANNOT_REFUND.value,
+ )
+ }
+ )
+ if amount_to_refund > payment.captured_amount:
+ raise ValidationError(
+ {
+ "amount_to_refund": ValidationError(
+ (
+ "The amountToRefund is greater than the maximal "
+ "possible amount to refund."
+ ),
+ code=OrderErrorCode.CANNOT_REFUND.value,
),
- code=OrderErrorCode.CANNOT_REFUND.value,
- ),
- }
- )
+ }
+ )
cleaned_input["amount_to_refund"] = amount_to_refund
@classmethod
@@ -556,6 +587,14 @@ class FulfillmentRefundAndReturnProductBase(BaseMutation):
cleaned_fulfillment_lines = []
for line, line_data in zip(fulfillment_lines, fulfillment_lines_data):
quantity = line_data["quantity"]
+ if line.order_line.is_gift_card:
+ cls._raise_error_for_line(
+ "Cannot refund or return gift card line.",
+ "FulfillmentLine",
+ line.pk,
+ "fulfillment_line_id",
+ OrderErrorCode.GIFT_CARD_LINE.value,
+ )
if line.quantity < quantity:
cls._raise_error_for_line(
"Provided quantity is bigger than quantity from "
@@ -605,6 +644,14 @@ class FulfillmentRefundAndReturnProductBase(BaseMutation):
cleaned_order_lines = []
for line, line_data in zip(order_lines, lines_data):
quantity = line_data["quantity"]
+ if line.is_gift_card:
+ cls._raise_error_for_line(
+ "Cannot refund or return gift card line.",
+ "OrderLine",
+ line.pk,
+ "order_line_id",
+ OrderErrorCode.GIFT_CARD_LINE.value,
+ )
if line.quantity < quantity:
cls._raise_error_for_line(
"Provided quantity is bigger than quantity from order line.",
@@ -666,7 +713,7 @@ class FulfillmentRefundProducts(FulfillmentRefundAndReturnProductBase):
)
payment = order.get_last_payment()
cls.clean_order_payment(payment, cleaned_input)
- cls.clean_amount_to_refund(amount_to_refund, payment, cleaned_input)
+ cls.clean_amount_to_refund(order, amount_to_refund, payment, cleaned_input)
cleaned_input.update(
{"include_shipping_costs": include_shipping_costs, "order": order}
@@ -808,7 +855,7 @@ class FulfillmentReturnProducts(FulfillmentRefundAndReturnProductBase):
payment = order.get_last_payment()
if refund:
cls.clean_order_payment(payment, cleaned_input)
- cls.clean_amount_to_refund(amount_to_refund, payment, cleaned_input)
+ cls.clean_amount_to_refund(order, amount_to_refund, payment, cleaned_input)
cleaned_input.update(
{
diff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.py
index 36b3035cf3..c2eeddea6c 100644
--- a/saleor/graphql/order/mutations/orders.py
+++ b/saleor/graphql/order/mutations/orders.py
@@ -6,6 +6,7 @@ from ....core.exceptions import InsufficientStock
from ....core.permissions import OrderPermissions
from ....core.taxes import TaxError, zero_taxed_money
from ....core.tracing import traced_atomic_transaction
+from ....giftcard.utils import deactivate_order_gift_cards, order_has_gift_card_lines
from ....order import FulfillmentStatus, OrderLineData, OrderStatus, events, models
from ....order.actions import (
cancel_order,
@@ -155,6 +156,18 @@ def try_payment_action(order, user, app, payment, func, *args, **kwargs):
)
+def clean_order_refund(order):
+ if order_has_gift_card_lines(order):
+ raise ValidationError(
+ {
+ "id": ValidationError(
+ "Cannot refund order with gift card lines.",
+ code=OrderErrorCode.CANNOT_REFUND.value,
+ )
+ }
+ )
+
+
class OrderUpdateInput(graphene.InputObjectType):
billing_address = AddressInput(description="Billing address of the customer.")
user_email = graphene.String(description="Email address of the customer.")
@@ -432,15 +445,19 @@ class OrderCancel(BaseMutation):
error_type_field = "order_errors"
@classmethod
+ @traced_atomic_transaction()
def perform_mutation(cls, _root, info, **data):
order = cls.get_node_or_error(info, data.get("id"), only_type=Order)
clean_order_cancel(order)
+ user = info.context.user
+ app = info.context.app
cancel_order(
order=order,
- user=info.context.user,
- app=info.context.app,
+ user=user,
+ app=app,
manager=info.context.plugins,
)
+ deactivate_order_gift_cards(order.id, user, app)
return OrderCancel(order=order)
@@ -607,6 +624,8 @@ class OrderRefund(BaseMutation):
)
order = cls.get_node_or_error(info, data.get("id"), only_type=Order)
+ clean_order_refund(order)
+
payment = order.get_last_payment()
clean_refund_payment(payment)
diff --git a/saleor/graphql/order/tests/benchmark/fixtures.py b/saleor/graphql/order/tests/benchmark/fixtures.py
index 716d670e26..df5f3fe149 100644
--- a/saleor/graphql/order/tests/benchmark/fixtures.py
+++ b/saleor/graphql/order/tests/benchmark/fixtures.py
@@ -58,6 +58,7 @@ def _prepare_lines_for_order(order, variant_with_image):
variant=variant_with_image,
quantity=5,
is_shipping_required=True,
+ is_gift_card=False,
unit_price=price,
total_price=price,
)
diff --git a/saleor/graphql/order/tests/test_fulfillment.py b/saleor/graphql/order/tests/test_fulfillment.py
index 5ec4ebe76c..1baad4f297 100644
--- a/saleor/graphql/order/tests/test_fulfillment.py
+++ b/saleor/graphql/order/tests/test_fulfillment.py
@@ -1085,6 +1085,31 @@ def test_cancel_fulfillment(
).exists()
+def test_cancel_fulfillment_for_order_with_gift_card_lines(
+ staff_api_client,
+ fulfillment,
+ gift_card_shippable_order_line,
+ staff_user,
+ permission_manage_orders,
+ warehouse,
+):
+ query = CANCEL_FULFILLMENT_MUTATION
+ order = gift_card_shippable_order_line.order
+ order_fulfillment = order.fulfillments.first()
+ fulfillment_id = graphene.Node.to_global_id("Fulfillment", order_fulfillment.id)
+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.id)
+ variables = {"id": fulfillment_id, "warehouseId": warehouse_id}
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["orderFulfillmentCancel"]
+ assert not data["fulfillment"]
+ assert len(data["errors"]) == 1
+ assert data["errors"][0]["code"] == OrderErrorCode.CANNOT_CANCEL_FULFILLMENT.name
+ assert data["errors"][0]["field"] == "fulfillment"
+
+
def test_cancel_fulfillment_no_warehouse_id(
staff_api_client, fulfillment, permission_manage_orders
):
diff --git a/saleor/graphql/order/tests/test_fulfillment_refund_products.py b/saleor/graphql/order/tests/test_fulfillment_refund_products.py
index 7ccf84c24c..89a5715bf0 100644
--- a/saleor/graphql/order/tests/test_fulfillment_refund_products.py
+++ b/saleor/graphql/order/tests/test_fulfillment_refund_products.py
@@ -77,6 +77,46 @@ def test_fulfillment_refund_products_with_back_in_stock_webhook(
back_in_stock_webhook_trigger.assert_called_once_with(Stock.objects.first())
+def test_fulfillment_refund_gift_card_products(
+ staff_api_client,
+ permission_manage_orders,
+ order_with_lines,
+ payment_dummy,
+):
+ # given
+ Allocation.objects.update(quantity_allocated=5)
+ payment_dummy.total = order_with_lines.total_gross_amount
+ payment_dummy.captured_amount = payment_dummy.total
+ payment_dummy.charge_status = ChargeStatus.FULLY_CHARGED
+ payment_dummy.save()
+ order_with_lines.payments.add(payment_dummy)
+ line_to_refund = order_with_lines.lines.first()
+
+ line_to_refund.is_gift_card = True
+ line_to_refund.save(update_fields=["is_gift_card"])
+
+ order_id = graphene.Node.to_global_id("Order", order_with_lines.pk)
+ line_id = graphene.Node.to_global_id("OrderLine", line_to_refund.pk)
+ variables = {
+ "order": order_id,
+ "input": {"orderLines": [{"orderLineId": line_id, "quantity": 1}]},
+ }
+
+ # when
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ # then
+ response = staff_api_client.post_graphql(ORDER_FULFILL_REFUND_MUTATION, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["orderFulfillmentRefundProducts"]
+ refund_fulfillment = data["fulfillment"]
+ errors = data["errors"]
+ assert not refund_fulfillment
+ assert len(errors) == 1
+ assert errors[0]["field"] == "orderLineId"
+ assert errors[0]["code"] == OrderErrorCode.GIFT_CARD_LINE.name
+
+
def test_fulfillment_refund_products_order_without_payment(
staff_api_client, permission_manage_orders, fulfilled_order
):
@@ -123,6 +163,42 @@ def test_fulfillment_refund_products_amount_and_shipping_costs(
)
+def test_fulfillment_refund_products_amount_costs_for_order_with_gift_card_lines(
+ staff_api_client,
+ permission_manage_orders,
+ fulfilled_order,
+ payment_dummy,
+):
+ # given
+ payment_dummy.captured_amount = payment_dummy.total
+ payment_dummy.charge_status = ChargeStatus.FULLY_CHARGED
+ payment_dummy.save()
+ fulfilled_order.payments.add(payment_dummy)
+
+ line = fulfilled_order.lines.first()
+ line.is_gift_card = True
+ line.save(update_fields=["is_gift_card"])
+
+ order_id = graphene.Node.to_global_id("Order", fulfilled_order.pk)
+ amount_to_refund = Decimal("11.00")
+ variables = {
+ "order": order_id,
+ "input": {"amountToRefund": amount_to_refund, "includeShippingCosts": True},
+ }
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_FULFILL_REFUND_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderFulfillmentRefundProducts"]
+ errors = data["errors"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == OrderErrorCode.CANNOT_REFUND.name
+ assert errors[0]["field"] == "amountToRefund"
+
+
@patch("saleor.order.actions.gateway.refund")
def test_fulfillment_refund_products_refund_raising_payment_error(
mocked_refund,
@@ -344,7 +420,6 @@ def test_fulfillment_refund_products_waiting_fulfillment_lines(
data = content["data"]["orderFulfillmentRefundProducts"]
refund_fulfillment = data["fulfillment"]
errors = data["errors"]
-
assert not errors
assert refund_fulfillment["status"] == FulfillmentStatus.REFUNDED.upper()
assert len(refund_fulfillment["lines"]) == 1
@@ -359,6 +434,48 @@ def test_fulfillment_refund_products_waiting_fulfillment_lines(
)
+def test_fulfillment_refund_products_gift_card_fulfillment_line(
+ staff_api_client,
+ permission_manage_orders,
+ fulfilled_order,
+ payment_dummy,
+):
+ payment_dummy.total = fulfilled_order.total_gross_amount
+ payment_dummy.captured_amount = payment_dummy.total
+ payment_dummy.charge_status = ChargeStatus.FULLY_CHARGED
+ payment_dummy.save()
+ fulfilled_order.payments.add(payment_dummy)
+ fulfillment_line_to_refund = fulfilled_order.fulfillments.first().lines.first()
+
+ order_line = fulfillment_line_to_refund.order_line
+ order_line.is_gift_card = True
+ order_line.save(update_fields=["is_gift_card"])
+
+ order_id = graphene.Node.to_global_id("Order", fulfilled_order.pk)
+ fulfillment_line_id = graphene.Node.to_global_id(
+ "FulfillmentLine", fulfillment_line_to_refund.pk
+ )
+ variables = {
+ "order": order_id,
+ "input": {
+ "fulfillmentLines": [
+ {"fulfillmentLineId": fulfillment_line_id, "quantity": 2}
+ ]
+ },
+ }
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+ response = staff_api_client.post_graphql(ORDER_FULFILL_REFUND_MUTATION, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["orderFulfillmentRefundProducts"]
+ refund_fulfillment = data["fulfillment"]
+ errors = data["errors"]
+ errors = data["errors"]
+ assert not refund_fulfillment
+ assert len(errors) == 1
+ assert errors[0]["code"] == OrderErrorCode.GIFT_CARD_LINE.name
+ assert errors[0]["field"] == "fulfillmentLineId"
+
+
def test_fulfillment_refund_products_fulfillment_lines_quantity_bigger_than_total(
staff_api_client, permission_manage_orders, fulfilled_order, payment_dummy
):
@@ -643,6 +760,7 @@ def test_fulfillment_refund_products_fulfillment_lines_and_order_lines(
variant_name=str(variant),
product_sku=variant.sku,
is_shipping_required=variant.is_shipping_required(),
+ is_gift_card=variant.is_gift_card(),
quantity=quantity,
quantity_fulfilled=2,
variant=variant,
diff --git a/saleor/graphql/order/tests/test_fulfillment_return_products.py b/saleor/graphql/order/tests/test_fulfillment_return_products.py
index a249080b25..580d843ed4 100644
--- a/saleor/graphql/order/tests/test_fulfillment_return_products.py
+++ b/saleor/graphql/order/tests/test_fulfillment_return_products.py
@@ -117,6 +117,48 @@ def test_fulfillment_return_products_amount_and_shipping_costs(
)
+def test_fulfillment_return_products_amount_order_with_gift_card(
+ staff_api_client,
+ permission_manage_orders,
+ fulfilled_order,
+ payment_dummy,
+):
+ # given
+ payment_dummy.captured_amount = payment_dummy.total
+ payment_dummy.charge_status = ChargeStatus.FULLY_CHARGED
+ payment_dummy.save()
+ fulfilled_order.payments.add(payment_dummy)
+
+ line = fulfilled_order.lines.first()
+ line.is_gift_card = True
+ line.save(update_fields=["is_gift_card"])
+
+ order_id = graphene.Node.to_global_id("Order", fulfilled_order.pk)
+ amount_to_refund = Decimal("11.00")
+ variables = {
+ "order": order_id,
+ "input": {
+ "refund": True,
+ "amountToRefund": amount_to_refund,
+ "includeShippingCosts": True,
+ },
+ }
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_FULFILL_RETURN_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderFulfillmentReturnProducts"]
+ fulfillment = data["returnFulfillment"]
+ errors = data["errors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "amountToRefund"
+ assert errors[0]["code"] == OrderErrorCode.CANNOT_REFUND.name
+ assert fulfillment is None
+
+
@patch("saleor.order.actions.gateway.refund")
def test_fulfillment_return_products_refund_raising_payment_error(
mocked_refund,
@@ -261,6 +303,56 @@ def test_fulfillment_return_products_order_lines(
)
+def test_fulfillment_return_products_gift_card_order_line(
+ staff_api_client,
+ permission_manage_orders,
+ order_with_lines,
+ payment_dummy,
+):
+ # given
+ payment_dummy.total = order_with_lines.total_gross_amount
+ payment_dummy.captured_amount = payment_dummy.total
+ payment_dummy.charge_status = ChargeStatus.FULLY_CHARGED
+ payment_dummy.save()
+ order_with_lines.payments.add(payment_dummy)
+ line_to_return = order_with_lines.lines.first()
+ line_to_return.is_gift_card = True
+ line_to_return.save(update_fields=["is_gift_card"])
+ line_quantity_to_return = 2
+
+ order_id = graphene.Node.to_global_id("Order", order_with_lines.pk)
+ line_id = graphene.Node.to_global_id("OrderLine", line_to_return.pk)
+
+ variables = {
+ "order": order_id,
+ "input": {
+ "refund": True,
+ "includeShippingCosts": True,
+ "orderLines": [
+ {
+ "orderLineId": line_id,
+ "quantity": line_quantity_to_return,
+ "replace": False,
+ },
+ ],
+ },
+ }
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_FULFILL_RETURN_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderFulfillmentReturnProducts"]
+ fulfillment = data["returnFulfillment"]
+ errors = data["errors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "orderLineId"
+ assert errors[0]["code"] == OrderErrorCode.GIFT_CARD_LINE.name
+ assert fulfillment is None
+
+
def test_fulfillment_return_products_order_lines_quantity_bigger_than_total(
staff_api_client, permission_manage_orders, order_with_lines, payment_dummy
):
@@ -490,6 +582,63 @@ def test_fulfillment_return_products_fulfillment_lines(
)
+@patch("saleor.order.actions.gateway.refund")
+def test_fulfillment_return_products_gift_card_fulfillment_line(
+ mocked_refund,
+ staff_api_client,
+ permission_manage_orders,
+ fulfilled_order,
+ payment_dummy,
+):
+ # given
+ payment_dummy.total = fulfilled_order.total_gross_amount
+ payment_dummy.captured_amount = payment_dummy.total
+ payment_dummy.charge_status = ChargeStatus.FULLY_CHARGED
+ payment_dummy.save()
+ fulfilled_order.payments.add(payment_dummy)
+ order_fulfillment = fulfilled_order.fulfillments.first()
+
+ fulfillment_line_to_replace = order_fulfillment.lines.last()
+ order_line = fulfillment_line_to_replace.order_line
+ order_line.is_gift_card = True
+ order_line.save(update_fields=["is_gift_card"])
+ quantity_to_replace = 1
+
+ order_id = graphene.Node.to_global_id("Order", fulfilled_order.pk)
+ fulfillment_line_to_replace_id = graphene.Node.to_global_id(
+ "FulfillmentLine", fulfillment_line_to_replace.pk
+ )
+
+ variables = {
+ "order": order_id,
+ "input": {
+ "refund": True,
+ "includeShippingCosts": True,
+ "fulfillmentLines": [
+ {
+ "fulfillmentLineId": fulfillment_line_to_replace_id,
+ "quantity": quantity_to_replace,
+ "replace": True,
+ },
+ ],
+ },
+ }
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ # when
+ response = staff_api_client.post_graphql(ORDER_FULFILL_RETURN_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderFulfillmentReturnProducts"]
+ fulfillment = data["returnFulfillment"]
+ errors = data["errors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "fulfillmentLineId"
+ assert errors[0]["code"] == OrderErrorCode.GIFT_CARD_LINE.name
+ assert fulfillment is None
+
+
def test_fulfillment_return_products_fulfillment_lines_quantity_bigger_than_total(
staff_api_client, permission_manage_orders, fulfilled_order, payment_dummy
):
@@ -683,6 +832,7 @@ def test_fulfillment_return_products_fulfillment_lines_and_order_lines(
variant_name=str(variant),
product_sku=variant.sku,
is_shipping_required=variant.is_shipping_required(),
+ is_gift_card=variant.is_gift_card(),
quantity=quantity,
quantity_fulfilled=2,
variant=variant,
diff --git a/saleor/graphql/order/tests/test_order.py b/saleor/graphql/order/tests/test_order.py
index fe93303611..7fc68fab6e 100644
--- a/saleor/graphql/order/tests/test_order.py
+++ b/saleor/graphql/order/tests/test_order.py
@@ -21,6 +21,8 @@ from ....core.notify_events import NotifyEventType
from ....core.prices import quantize_price
from ....core.taxes import TaxError, zero_taxed_money
from ....discount.models import OrderDiscount
+from ....giftcard import GiftCardEvents
+from ....giftcard.events import gift_cards_bought_event
from ....order import FulfillmentStatus, OrderOrigin, OrderStatus
from ....order import events as order_events
from ....order.error_codes import OrderErrorCode
@@ -4361,6 +4363,38 @@ def test_order_cancel_as_app(
)
+@patch("saleor.graphql.order.mutations.orders.cancel_order")
+@patch("saleor.graphql.order.mutations.orders.clean_order_cancel")
+def test_order_cancel_with_bought_gift_cards(
+ mock_clean_order_cancel,
+ mock_cancel_order,
+ staff_api_client,
+ permission_manage_orders,
+ order_with_lines,
+ gift_card,
+):
+ order = order_with_lines
+ gift_cards_bought_event([gift_card], order.id, staff_api_client.user, None)
+ assert gift_card.is_active is True
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variables = {"id": order_id}
+ response = staff_api_client.post_graphql(
+ MUTATION_ORDER_CANCEL, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["orderCancel"]
+ assert not data["errors"]
+
+ mock_clean_order_cancel.assert_called_once_with(order)
+ mock_cancel_order.assert_called_once_with(
+ order=order, user=staff_api_client.user, app=None, manager=ANY
+ )
+
+ gift_card.refresh_from_db()
+ assert gift_card.is_active is False
+ assert gift_card.events.filter(type=GiftCardEvents.DEACTIVATED)
+
+
@mock.patch("saleor.plugins.manager.PluginsManager.notify")
def test_order_capture(
mocked_notify,
@@ -4610,20 +4644,27 @@ def test_order_void_payment_error(
mock_void_payment.assert_called_once()
-def test_order_refund(staff_api_client, permission_manage_orders, payment_txn_captured):
- order = payment_txn_captured.order
- query = """
- mutation refundOrder($id: ID!, $amount: PositiveDecimal!) {
- orderRefund(id: $id, amount: $amount) {
- order {
- paymentStatus
- paymentStatusDisplay
- isPaid
- status
- }
+ORDER_REFUND_MUTATION = """
+ mutation refundOrder($id: ID!, $amount: PositiveDecimal!) {
+ orderRefund(id: $id, amount: $amount) {
+ order {
+ paymentStatus
+ paymentStatusDisplay
+ isPaid
+ status
+ }
+ errors {
+ code
+ field
}
}
- """
+ }
+"""
+
+
+def test_order_refund(staff_api_client, permission_manage_orders, payment_txn_captured):
+ order = payment_txn_captured.order
+ query = ORDER_REFUND_MUTATION
order_id = graphene.Node.to_global_id("Order", order.id)
amount = float(payment_txn_captured.total)
variables = {"id": order_id, "amount": amount}
@@ -4652,6 +4693,25 @@ def test_order_refund(staff_api_client, permission_manage_orders, payment_txn_ca
assert refunded_fulfillment.shipping_refund_amount is None
+def test_order_refund_with_gift_card_lines(
+ staff_api_client, permission_manage_orders, gift_card_shippable_order_line
+):
+ order = gift_card_shippable_order_line.order
+ query = ORDER_REFUND_MUTATION
+ order_id = graphene.Node.to_global_id("Order", order.id)
+
+ variables = {"id": order_id, "amount": 10.0}
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["orderRefund"]
+ assert not data["order"]
+ assert len(data["errors"]) == 1
+ assert data["errors"][0]["code"] == OrderErrorCode.CANNOT_REFUND.name
+ assert data["errors"][0]["field"] == "id"
+
+
@pytest.mark.parametrize(
"requires_amount, mutation_name",
((True, "orderRefund"), (False, "orderVoid"), (True, "orderCapture")),
@@ -6305,6 +6365,7 @@ def test_orders_query_with_filter_search(
variant_name=str(variant),
product_sku=variant.sku,
is_shipping_required=variant.is_shipping_required(),
+ is_gift_card=variant.is_gift_card(),
quantity=3,
variant=variant,
unit_price=unit_price,
@@ -6472,6 +6533,7 @@ def test_order_query_with_filter_search_by_product_sku_multi_order_lines(
variant_name=str(variants[0]),
product_sku=variants[0].sku,
is_shipping_required=variants[0].is_shipping_required(),
+ is_gift_card=variants[0].is_gift_card(),
quantity=quantity,
variant=variants[0],
unit_price=unit_price,
@@ -6486,6 +6548,7 @@ def test_order_query_with_filter_search_by_product_sku_multi_order_lines(
variant_name=str(variants[1]),
product_sku=variants[1].sku,
is_shipping_required=variants[1].is_shipping_required(),
+ is_gift_card=variants[1].is_gift_card(),
quantity=quantity,
variant=variants[1],
unit_price=unit_price,
diff --git a/saleor/graphql/product/tests/test_bulk_delete.py b/saleor/graphql/product/tests/test_bulk_delete.py
index 5d82556ffd..524d800fe6 100644
--- a/saleor/graphql/product/tests/test_bulk_delete.py
+++ b/saleor/graphql/product/tests/test_bulk_delete.py
@@ -381,6 +381,7 @@ def test_delete_products(
variant_name=str(variant),
product_sku=variant.sku,
is_shipping_required=variant.is_shipping_required(),
+ is_gift_card=variant.is_gift_card(),
unit_price=TaxedMoney(net=net, gross=gross),
total_price=total_price,
quantity=3,
@@ -394,6 +395,7 @@ def test_delete_products(
variant_name=str(variant),
product_sku=variant.sku,
is_shipping_required=variant.is_shipping_required(),
+ is_gift_card=variant.is_gift_card(),
unit_price=TaxedMoney(net=net, gross=gross),
total_price=total_price,
quantity=3,
@@ -1067,6 +1069,7 @@ def test_delete_product_variants_in_draft_orders(
variant_name=str(second_variant_in_draft),
product_sku=second_variant_in_draft.sku,
is_shipping_required=second_variant_in_draft.is_shipping_required(),
+ is_gift_card=second_variant_in_draft.is_gift_card(),
unit_price=TaxedMoney(net=net, gross=gross),
total_price=total_price,
quantity=quantity,
@@ -1088,6 +1091,7 @@ def test_delete_product_variants_in_draft_orders(
variant_name=str(variant),
product_sku=variant.sku,
is_shipping_required=variant.is_shipping_required(),
+ is_gift_card=variant.is_gift_card(),
unit_price=TaxedMoney(net=net, gross=gross),
total_price=total_price,
quantity=quantity,
diff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.py
index cbaf178e7e..6aca5ad8f1 100644
--- a/saleor/graphql/product/tests/test_product.py
+++ b/saleor/graphql/product/tests/test_product.py
@@ -7127,6 +7127,7 @@ def test_delete_product_variant_in_draft_order(
variant_name=str(variant),
product_sku=variant.sku,
is_shipping_required=variant.is_shipping_required(),
+ is_gift_card=variant.is_gift_card(),
unit_price=TaxedMoney(net=net, gross=gross),
total_price=total_price,
quantity=quantity,
@@ -7140,6 +7141,7 @@ def test_delete_product_variant_in_draft_order(
variant_name=str(variant),
product_sku=variant.sku,
is_shipping_required=variant.is_shipping_required(),
+ is_gift_card=variant.is_gift_card(),
unit_price=TaxedMoney(net=net, gross=gross),
total_price=total_price,
quantity=quantity,
@@ -8377,6 +8379,7 @@ def test_product_type_delete_mutation_variants_in_draft_order(
variant_name=str(variant),
product_sku=variant.sku,
is_shipping_required=variant.is_shipping_required(),
+ is_gift_card=variant.is_gift_card(),
unit_price=TaxedMoney(net=net, gross=gross),
total_price=total_price,
quantity=3,
@@ -8389,6 +8392,7 @@ def test_product_type_delete_mutation_variants_in_draft_order(
variant_name=str(variant),
product_sku=variant.sku,
is_shipping_required=variant.is_shipping_required(),
+ is_gift_card=variant.is_gift_card(),
unit_price=TaxedMoney(net=net, gross=gross),
total_price=total_price,
quantity=3,
diff --git a/saleor/graphql/product/tests/test_variant.py b/saleor/graphql/product/tests/test_variant.py
index 0297dcad14..697c93798e 100644
--- a/saleor/graphql/product/tests/test_variant.py
+++ b/saleor/graphql/product/tests/test_variant.py
@@ -2851,6 +2851,7 @@ def test_delete_variant_in_draft_order(
variant_name=str(variant),
product_sku=variant.sku,
is_shipping_required=variant.is_shipping_required(),
+ is_gift_card=variant.is_gift_card(),
unit_price=unit_price,
total_price=unit_price * quantity,
quantity=quantity,
@@ -2866,6 +2867,7 @@ def test_delete_variant_in_draft_order(
variant_name=str(variant),
product_sku=variant.sku,
is_shipping_required=variant.is_shipping_required(),
+ is_gift_card=variant.is_gift_card(),
unit_price=unit_price,
total_price=unit_price * quantity,
quantity=quantity,
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index e69026e75d..a8b893f0a7 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -4180,6 +4180,7 @@ enum OrderErrorCode {
CANNOT_REFUND
CANNOT_FULFILL_UNPAID_ORDER
CAPTURE_INACTIVE_PAYMENT
+ GIFT_CARD_LINE
NOT_EDITABLE
FULFILL_ORDER_LINE
GRAPHQL_ERROR
diff --git a/saleor/order/actions.py b/saleor/order/actions.py
index 79a6a55724..8272a1377d 100644
--- a/saleor/order/actions.py
+++ b/saleor/order/actions.py
@@ -1340,11 +1340,10 @@ def _process_refund(
manager: "PluginsManager",
):
lines_to_refund: Dict[OrderLineIDType, Tuple[QuantityType, OrderLine]] = dict()
- refund_amount = _calculate_refund_amount(
- order_lines_to_refund, fulfillment_lines_to_refund, lines_to_refund
- )
if amount is None:
- amount = refund_amount
+ amount = _calculate_refund_amount(
+ order_lines_to_refund, fulfillment_lines_to_refund, lines_to_refund
+ )
# we take into consideration the shipping costs only when amount is not
# provided.
if refund_shipping_costs:
diff --git a/saleor/order/error_codes.py b/saleor/order/error_codes.py
index 62eebab428..14c6615630 100644
--- a/saleor/order/error_codes.py
+++ b/saleor/order/error_codes.py
@@ -10,6 +10,7 @@ class OrderErrorCode(Enum):
CANNOT_REFUND = "cannot_refund"
CANNOT_FULFILL_UNPAID_ORDER = "cannot_fulfill_unpaid_order"
CAPTURE_INACTIVE_PAYMENT = "capture_inactive_payment"
+ GIFT_CARD_LINE = "gift_card_line"
NOT_EDITABLE = "not_editable"
FULFILL_ORDER_LINE = "fulfill_order_line"
GRAPHQL_ERROR = "graphql_error"
diff --git a/saleor/order/migrations/0119_orderline_is_gift_card.py b/saleor/order/migrations/0119_orderline_is_gift_card.py
new file mode 100644
index 0000000000..97d3d5062a
--- /dev/null
+++ b/saleor/order/migrations/0119_orderline_is_gift_card.py
@@ -0,0 +1,31 @@
+# Generated by Django 3.2.6 on 2021-09-09 12:58
+
+from django.db import migrations, models
+
+
+def set_is_gift_card_field(apps, schema_editor):
+ OrderLine = apps.get_model("order", "OrderLine")
+ for line in OrderLine.objects.iterator():
+ line.is_gift_card = line.variant.product_type.kind == "gift_card"
+ line.save()
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("order", "0118_auto_20210913_0731"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="orderline",
+ name="is_gift_card",
+ field=models.BooleanField(null=True),
+ ),
+ migrations.RunPython(set_is_gift_card_field, migrations.RunPython.noop),
+ migrations.AlterField(
+ model_name="orderline",
+ name="is_gift_card",
+ field=models.BooleanField(),
+ ),
+ ]
diff --git a/saleor/order/models.py b/saleor/order/models.py
index a11f78b6f8..dce6343c4f 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -420,6 +420,7 @@ class OrderLine(models.Model):
translated_variant_name = models.CharField(max_length=255, default="", blank=True)
product_sku = models.CharField(max_length=255)
is_shipping_required = models.BooleanField()
+ is_gift_card = models.BooleanField()
quantity = models.IntegerField(validators=[MinValueValidator(1)])
quantity_fulfilled = models.IntegerField(
validators=[MinValueValidator(0)], default=0
diff --git a/saleor/order/tests/test_order_actions.py b/saleor/order/tests/test_order_actions.py
index ee6532d18e..1348c42d95 100644
--- a/saleor/order/tests/test_order_actions.py
+++ b/saleor/order/tests/test_order_actions.py
@@ -55,6 +55,7 @@ def order_with_digital_line(order, digital_content, stock, site_settings):
variant_name=str(variant),
product_sku=variant.sku,
is_shipping_required=variant.is_shipping_required(),
+ is_gift_card=variant.is_gift_card(),
quantity=quantity,
variant=variant,
unit_price=unit_price,
diff --git a/saleor/order/tests/test_order_actions_create_fulfillments_for_returned_products.py b/saleor/order/tests/test_order_actions_create_fulfillments_for_returned_products.py
index 7493267336..1f136ff1c7 100644
--- a/saleor/order/tests/test_order_actions_create_fulfillments_for_returned_products.py
+++ b/saleor/order/tests/test_order_actions_create_fulfillments_for_returned_products.py
@@ -557,6 +557,7 @@ def test_create_return_fulfillment_with_lines_already_refunded(
variant_name=str(variant),
product_sku=variant.sku,
is_shipping_required=variant.is_shipping_required(),
+ is_gift_card=variant.is_gift_card(),
quantity=quantity,
quantity_fulfilled=2,
variant=variant,
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index 9f12318a8f..dd255641e2 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -358,6 +358,7 @@ def add_variant_to_order(
translated_variant_name=translated_variant_name,
product_sku=variant.sku,
is_shipping_required=variant.is_shipping_required(),
+ is_gift_card=variant.is_gift_card(),
quantity=quantity,
unit_price=unit_price,
total_price=total_price,
diff --git a/saleor/product/models.py b/saleor/product/models.py
index b9b599e6f9..6484d10c6a 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -585,6 +585,9 @@ class ProductVariant(SortableModel, ModelWithMetadata):
def is_shipping_required(self) -> bool:
return self.product.product_type.is_shipping_required
+ def is_gift_card(self) -> bool:
+ return self.product.product_type.kind == ProductTypeKind.GIFT_CARD
+
def is_digital(self) -> bool:
is_digital = self.product.product_type.is_digital
return not self.is_shipping_required() and is_digital
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 444af3a3ac..a503c0660c 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -2704,6 +2704,7 @@ def order_line(order, variant):
variant_name=str(variant),
product_sku=variant.sku,
is_shipping_required=variant.is_shipping_required(),
+ is_gift_card=variant.is_gift_card(),
quantity=quantity,
variant=variant,
unit_price=unit_price,
@@ -2730,6 +2731,7 @@ def gift_card_non_shippable_order_line(order, gift_card_non_shippable_variant):
variant_name=str(variant),
product_sku=variant.sku,
is_shipping_required=variant.is_shipping_required(),
+ is_gift_card=variant.is_gift_card(),
quantity=quantity,
variant=variant,
unit_price=unit_price,
@@ -2756,6 +2758,7 @@ def gift_card_shippable_order_line(order, gift_card_shippable_variant):
variant_name=str(variant),
product_sku=variant.sku,
is_shipping_required=variant.is_shipping_required(),
+ is_gift_card=variant.is_gift_card(),
quantity=quantity,
variant=variant,
unit_price=unit_price,
@@ -2794,6 +2797,7 @@ def order_line_with_allocation_in_many_stocks(
variant_name=str(variant),
product_sku=variant.sku,
is_shipping_required=variant.is_shipping_required(),
+ is_gift_card=variant.is_gift_card(),
quantity=quantity,
variant=variant,
unit_price=unit_price,
@@ -2841,6 +2845,7 @@ def order_line_with_one_allocation(
variant_name=str(variant),
product_sku=variant.sku,
is_shipping_required=variant.is_shipping_required(),
+ is_gift_card=variant.is_gift_card(),
quantity=quantity,
variant=variant,
unit_price=unit_price,
@@ -2974,6 +2979,7 @@ def order_with_lines(
variant_name=str(variant),
product_sku=variant.sku,
is_shipping_required=variant.is_shipping_required(),
+ is_gift_card=variant.is_gift_card(),
quantity=quantity,
variant=variant,
unit_price=unit_price,
@@ -3022,6 +3028,7 @@ def order_with_lines(
variant_name=str(variant),
product_sku=variant.sku,
is_shipping_required=variant.is_shipping_required(),
+ is_gift_card=variant.is_gift_card(),
quantity=quantity,
variant=variant,
unit_price=unit_price,
@@ -3173,6 +3180,7 @@ def order_with_lines_channel_PLN(
variant_name=str(variant),
product_sku=variant.sku,
is_shipping_required=variant.is_shipping_required(),
+ is_gift_card=variant.is_gift_card(),
quantity=quantity,
variant=variant,
unit_price=unit_price,
@@ -3220,6 +3228,7 @@ def order_with_lines_channel_PLN(
variant_name=str(variant),
product_sku=variant.sku,
is_shipping_required=variant.is_shipping_required(),
+ is_gift_card=variant.is_gift_card(),
quantity=quantity,
variant=variant,
unit_price=unit_price,
@@ -3270,6 +3279,7 @@ def order_with_line_without_inventory_tracking(
variant_name=str(variant),
product_sku=variant.sku,
is_shipping_required=variant.is_shipping_required(),
+ is_gift_card=variant.is_gift_card(),
quantity=quantity,
variant=variant,
unit_price=unit_price,
@@ -4771,6 +4781,7 @@ def allocations(order_list, stock, channel_USD):
variant_name=str(variant),
product_sku=variant.sku,
is_shipping_required=variant.is_shipping_required(),
+ is_gift_card=variant.is_gift_card(),
unit_price=price,
total_price=price,
tax_rate=Decimal("0.23"),
@@ -4783,6 +4794,7 @@ def allocations(order_list, stock, channel_USD):
variant_name=str(variant),
product_sku=variant.sku,
is_shipping_required=variant.is_shipping_required(),
+ is_gift_card=variant.is_gift_card(),
unit_price=price,
total_price=price,
tax_rate=Decimal("0.23"),
@@ -4795,6 +4807,7 @@ def allocations(order_list, stock, channel_USD):
variant_name=str(variant),
product_sku=variant.sku,
is_shipping_required=variant.is_shipping_required(),
+ is_gift_card=variant.is_gift_card(),
unit_price=price,
total_price=price,
tax_rate=Decimal("0.23"),