Skip to content

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

Update code after code review

Mateusz Grzybfec51cebacac
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 46fc2ca782..c134ae4627 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,7 +4,7 @@ All notable, unreleased changes to this project will be documented in this file.
# 3.1.0 [Unreleased]
- Extend app by `AppExtension` - #7701 by @korycins
-- Deprecate interface field `PaymentData.reuse_source` - #SALEOR-4233 by @mateuszgrzyb
+- Deprecate interface field `PaymentData.reuse_source` - #7956 by @mateuszgrzyb
- Add Click&Collect feature - #7673 by @kuchichan
diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.py
index 46069b5e50..87d2f93e82 100644
--- a/saleor/graphql/checkout/mutations.py
+++ b/saleor/graphql/checkout/mutations.py
@@ -1250,8 +1250,7 @@ class CheckoutComplete(BaseMutation):
default_value=False,
description=(
"Determines whether to store the payment source for future usage. "
- "DEPRECATED: Will be removed in Saleor 4.0. "
- "Use checkoutPaymentCreate for this action."
+ f"{DEPRECATED_IN_3X_INPUT} Use checkoutPaymentCreate for this action."
),
)
redirect_url = graphene.String(
diff --git a/saleor/graphql/meta/mutations.py b/saleor/graphql/meta/mutations.py
index 768dafa095..45468f1735 100644
--- a/saleor/graphql/meta/mutations.py
+++ b/saleor/graphql/meta/mutations.py
@@ -15,6 +15,7 @@ from ..channel import ChannelContext
from ..core.mutations import BaseMutation
from ..core.types.common import MetadataError
from ..core.utils import from_global_id_or_error
+from ..payment.utils import metadata_contains_empty_key
from .extra_methods import MODEL_EXTRA_METHODS, MODEL_EXTRA_PREFETCH
from .permissions import PRIVATE_META_PERMISSION_MAP, PUBLIC_META_PERMISSION_MAP
from .types import ObjectWithMetadata
@@ -67,8 +68,7 @@ class BaseMetadataMutation(BaseMutation):
@classmethod
def validate_metadata_keys(cls, metadata_list: List[dict]):
- # raise an error when any of the key is empty
- if not all([data["key"].strip() for data in metadata_list]):
+ if metadata_contains_empty_key(metadata_list):
raise ValidationError(
{
"input": ValidationError(
diff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.py
index 77a5396996..25a66f49bf 100644
--- a/saleor/graphql/payment/mutations.py
+++ b/saleor/graphql/payment/mutations.py
@@ -1,3 +1,5 @@
+from typing import List
+
import graphene
from django.core.exceptions import ValidationError
@@ -6,6 +8,7 @@ from ...checkout.calculations import calculate_checkout_total_with_gift_cards
from ...checkout.checkout_cleaner import clean_billing_address, clean_checkout_shipping
from ...checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ...checkout.utils import cancel_active_payments
+from ...core.error_codes import MetadataErrorCode
from ...core.permissions import OrderPermissions
from ...core.utils import get_client_ip
from ...core.utils.url import validate_storefront_url
@@ -15,14 +18,39 @@ from ...payment.utils import create_payment, is_currency_supported
from ..account.i18n import I18nMixin
from ..checkout.mutations import get_checkout_by_token
from ..checkout.types import Checkout
-from ..core.descriptions import DEPRECATED_IN_3X_INPUT
+from ..core.descriptions import ADDED_IN_31, DEPRECATED_IN_3X_INPUT
from ..core.enums import to_enum
from ..core.mutations import BaseMutation
from ..core.scalars import UUID, PositiveDecimal
from ..core.types import common as common_types
from ..core.validators import validate_one_of_args_is_in_mutation
-from ..meta.mutations import BaseMetadataMutation, MetadataInput
+from ..meta.mutations import MetadataInput
from .types import Payment, PaymentInitialized
+from .utils import metadata_contains_empty_key
+
+
+def description(enum):
+ if enum is None:
+ return "Enum representing the type of a payment storage in a gateway."
+ elif enum == StorePaymentMethodEnum.NONE:
+ return "Storage is disabled. The payment is not stored."
+ elif enum == StorePaymentMethodEnum.ON_SESSION:
+ return (
+ "On session storage type. "
+ "The payment is stored only to be reused when "
+ "the customer is present in the checkout flow."
+ )
+ elif enum == StorePaymentMethodEnum.OFF_SESSION:
+ return (
+ "Off session storage type. "
+ "The payment is stored to be reused even if the customer is absent."
+ )
+ return None
+
+
+StorePaymentMethodEnum = to_enum(
+ Store, type_name="StorePaymentMethodEnum", description=description
+)
class PaymentInput(graphene.InputObjectType):
@@ -54,9 +82,16 @@ class PaymentInput(graphene.InputObjectType):
"finished if this field is not provided."
),
)
-
-
-StoreEnum = to_enum(Store)
+ store_payment_method = StorePaymentMethodEnum(
+ description=f"{ADDED_IN_31} Payment store type.",
+ required=False,
+ default_value=Store.NONE,
+ )
+ metadata = graphene.List(
+ graphene.NonNull(MetadataInput),
+ description=f"{ADDED_IN_31} User public metadata.",
+ required=False,
+ )
class CheckoutPaymentCreate(BaseMutation, I18nMixin):
@@ -74,16 +109,6 @@ class CheckoutPaymentCreate(BaseMutation, I18nMixin):
input = PaymentInput(
description="Data required to create a new payment.", required=True
)
- store = StoreEnum(
- description="Payment store type.",
- required=False,
- default_value=Store.NONE,
- )
- metadata = graphene.List(
- graphene.NonNull(MetadataInput),
- description="User public metadata.",
- required=False,
- )
class Meta:
description = "Create a new payment for given checkout."
@@ -148,16 +173,23 @@ class CheckoutPaymentCreate(BaseMutation, I18nMixin):
)
@classmethod
- def perform_mutation(
- cls,
- _root,
- info,
- checkout_id=None,
- token=None,
- store=Store.NONE,
- metadata=None,
- **data
- ):
+ def validate_metadata_keys(cls, metadata_list: List[dict]):
+ if metadata_contains_empty_key(metadata_list):
+ raise ValidationError(
+ {
+ "input": ValidationError(
+ {
+ "metadata": ValidationError(
+ "Metadata key cannot be empty.",
+ code=MetadataErrorCode.REQUIRED.value,
+ )
+ }
+ )
+ }
+ )
+
+ @classmethod
+ def perform_mutation(cls, _root, info, checkout_id=None, token=None, **data):
# DEPRECATED
validate_one_of_args_is_in_mutation(
PaymentErrorCode, "checkout_id", checkout_id, "token", token
@@ -207,8 +239,10 @@ class CheckoutPaymentCreate(BaseMutation, I18nMixin):
cancel_active_payments(checkout)
+ metadata = data.get("metadata")
+
if metadata is not None:
- BaseMetadataMutation.validate_metadata_keys(metadata)
+ cls.validate_metadata_keys(metadata)
metadata = {data.key: data.value for data in metadata}
payment = create_payment(
@@ -222,7 +256,7 @@ class CheckoutPaymentCreate(BaseMutation, I18nMixin):
customer_ip_address=get_client_ip(info.context),
checkout=checkout,
return_url=data.get("return_url"),
- store=store,
+ store_payment_method=data.get("store") or Store.NONE,
metadata=metadata,
)
return CheckoutPaymentCreate(payment=payment, checkout=checkout)
diff --git a/saleor/graphql/payment/tests/test_payment.py b/saleor/graphql/payment/tests/test_payment.py
index ddbbdcff97..3c4261e1ea 100644
--- a/saleor/graphql/payment/tests/test_payment.py
+++ b/saleor/graphql/payment/tests/test_payment.py
@@ -17,6 +17,7 @@ from ....payment.interface import (
CustomerSource,
InitializedPaymentResponse,
PaymentMethodInfo,
+ StoreEnum,
TokenConfig,
)
from ....payment.models import ChargeStatus, Payment, TransactionKind
@@ -94,14 +95,10 @@ CREATE_PAYMENT_MUTATION = """
mutation CheckoutPaymentCreate(
$token: UUID,
$input: PaymentInput!,
- $store: StoreEnum,
- $metadata: [MetadataInput!]
) {
checkoutPaymentCreate(
token: $token,
input: $input,
- store: $store,
- metadata: $metadata
) {
payment {
transactions {
@@ -445,7 +442,9 @@ def test_create_payment_for_checkout_with_active_payments(
assert active_payments.first().pk not in previous_active_payments_ids
[email protected]("store", [None, "NONE", "ON_SESSION", "OFF_SESSION"])
+ "store", [None, StoreEnum.NONE, StoreEnum.ON_SESSION, StoreEnum.OFF_SESSION]
+)
def test_create_payment_with_store(
user_api_client, checkout_without_shipping_required, address, store
):
@@ -467,8 +466,8 @@ def test_create_payment_with_store(
"gateway": DUMMY_GATEWAY,
"token": "sample-token",
"amount": total.gross.amount,
+ "store": store,
},
- "store": store,
}
# when
@@ -477,7 +476,7 @@ def test_create_payment_with_store(
# then
checkout.refresh_from_db()
payment = checkout.payments.first()
- assert payment.store == (store or "NONE").lower()
+ assert payment.store == (store or StoreEnum.NONE).lower()
@pytest.mark.parametrize(
@@ -504,8 +503,8 @@ def test_create_payment_with_metadata(
"gateway": DUMMY_GATEWAY,
"token": "sample-token",
"amount": total.gross.amount,
+ "metadata": metadata,
},
- "metadata": metadata,
}
# when
diff --git a/saleor/graphql/payment/utils.py b/saleor/graphql/payment/utils.py
new file mode 100644
index 0000000000..38638e3e88
--- /dev/null
+++ b/saleor/graphql/payment/utils.py
@@ -0,0 +1,5 @@
+from typing import List
+
+
+def metadata_contains_empty_key(metadata_list: List[dict]) -> bool:
+ return not all([data["key"].strip() for data in metadata_list])
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 1d82e3d6eb..85f4a0135e 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -3790,7 +3790,7 @@ type Mutation {
checkoutLinesAdd(checkoutId: ID, lines: [CheckoutLineInput]!, token: UUID): CheckoutLinesAdd
checkoutLinesUpdate(checkoutId: ID, lines: [CheckoutLineInput]!, token: UUID): CheckoutLinesUpdate
checkoutRemovePromoCode(checkoutId: ID, promoCode: String!, token: UUID): CheckoutRemovePromoCode
- checkoutPaymentCreate(checkoutId: ID, input: PaymentInput!, metadata: [MetadataInput!], store: StoreEnum = none, token: UUID): CheckoutPaymentCreate
+ checkoutPaymentCreate(checkoutId: ID, input: PaymentInput!, token: UUID): CheckoutPaymentCreate
checkoutShippingAddressUpdate(checkoutId: ID, shippingAddress: AddressInput!, token: UUID): CheckoutShippingAddressUpdate
checkoutShippingMethodUpdate(checkoutId: ID, shippingMethodId: ID!, token: UUID): CheckoutShippingMethodUpdate @deprecated(reason: "This field will be removed in Saleor 4.0. Use `checkoutDeliveryMethodUpdate` instead.")
checkoutDeliveryMethodUpdate(deliveryMethodId: ID, token: UUID): CheckoutDeliveryMethodUpdate
@@ -4807,6 +4807,8 @@ input PaymentInput {
token: String
amount: PositiveDecimal
returnUrl: String
+ storePaymentMethod: StorePaymentMethodEnum = none
+ metadata: [MetadataInput!]
}
type PaymentRefund {
@@ -6420,7 +6422,7 @@ input StockInput {
quantity: Int!
}
-enum StoreEnum {
+enum StorePaymentMethodEnum {
ON_SESSION
OFF_SESSION
NONE
diff --git a/saleor/payment/interface.py b/saleor/payment/interface.py
index d3e3cf95c0..a95198ec20 100644
--- a/saleor/payment/interface.py
+++ b/saleor/payment/interface.py
@@ -89,7 +89,7 @@ class PaymentData:
reuse_source: bool = False # Note: this field will be removed in 4.0.
data: Optional[dict] = None
graphql_customer_id: Optional[str] = None
- store: StoreEnum = StoreEnum.NONE
+ store_payment_method: StoreEnum = StoreEnum.NONE
payment_metadata: Dict[str, str] = field(default_factory=dict)
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index 8d9e604444..aa63225ad4 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -86,7 +86,7 @@ def create_payment_information(
reuse_source=store_source,
data=additional_data or {},
graphql_customer_id=graphql_customer_id,
- store=StoreEnum[payment.store.upper()],
+ store_payment_method=StoreEnum[payment.store.upper()],
payment_metadata=payment.metadata,
)
@@ -103,7 +103,7 @@ def create_payment(
order: Order = None,
return_url: str = None,
external_reference: Optional[str] = None,
- store: str = Store.NONE,
+ store_payment_method: str = Store.NONE,
metadata: Optional[Dict[str, str]] = None,
) -> Payment:
"""Create a payment instance.
@@ -153,7 +153,7 @@ def create_payment(
"total": total,
"return_url": return_url,
"psp_reference": external_reference or "",
- "store": store,
+ "store": store_payment_method,
"metadata": {} if metadata is None else metadata,
}