Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Update code after code review
Mateusz Grzybfec51cebacac
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 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 @kuchichandiff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.pyindex 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.pyindex 768dafa095..45468f1735 100644--- a/saleor/graphql/meta/mutations.py+++ b/saleor/graphql/meta/mutations.py@@ -15,6 +15,7 @@ from ..channel import ChannelContextfrom ..core.mutations import BaseMutationfrom ..core.types.common import MetadataErrorfrom ..core.utils import from_global_id_or_error+from ..payment.utils import metadata_contains_empty_keyfrom .extra_methods import MODEL_EXTRA_METHODS, MODEL_EXTRA_PREFETCHfrom .permissions import PRIVATE_META_PERMISSION_MAP, PUBLIC_META_PERMISSION_MAPfrom .types import ObjectWithMetadata@@ -67,8 +68,7 @@ class BaseMetadataMutation(BaseMutation):@classmethoddef 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.pyindex 77a5396996..25a66f49bf 100644--- a/saleor/graphql/payment/mutations.py+++ b/saleor/graphql/payment/mutations.py@@ -1,3 +1,5 @@+from typing import List+import graphenefrom django.core.exceptions import ValidationError@@ -6,6 +8,7 @@ from ...checkout.calculations import calculate_checkout_total_with_gift_cardsfrom ...checkout.checkout_cleaner import clean_billing_address, clean_checkout_shippingfrom ...checkout.fetch import fetch_checkout_info, fetch_checkout_linesfrom ...checkout.utils import cancel_active_payments+from ...core.error_codes import MetadataErrorCodefrom ...core.permissions import OrderPermissionsfrom ...core.utils import get_client_ipfrom ...core.utils.url import validate_storefront_url@@ -15,14 +18,39 @@ from ...payment.utils import create_payment, is_currency_supportedfrom ..account.i18n import I18nMixinfrom ..checkout.mutations import get_checkout_by_tokenfrom ..checkout.types import Checkout-from ..core.descriptions import DEPRECATED_IN_3X_INPUT+from ..core.descriptions import ADDED_IN_31, DEPRECATED_IN_3X_INPUTfrom ..core.enums import to_enumfrom ..core.mutations import BaseMutationfrom ..core.scalars import UUID, PositiveDecimalfrom ..core.types import common as common_typesfrom ..core.validators import validate_one_of_args_is_in_mutation-from ..meta.mutations import BaseMetadataMutation, MetadataInput+from ..meta.mutations import MetadataInputfrom .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):# DEPRECATEDvalidate_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.pyindex 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(# thencheckout.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,}# whendiff --git a/saleor/graphql/payment/utils.py b/saleor/graphql/payment/utils.pynew file mode 100644index 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.graphqlindex 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): CheckoutLinesAddcheckoutLinesUpdate(checkoutId: ID, lines: [CheckoutLineInput]!, token: UUID): CheckoutLinesUpdatecheckoutRemovePromoCode(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): CheckoutPaymentCreatecheckoutShippingAddressUpdate(checkoutId: ID, shippingAddress: AddressInput!, token: UUID): CheckoutShippingAddressUpdatecheckoutShippingMethodUpdate(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: Stringamount: PositiveDecimalreturnUrl: String+ storePaymentMethod: StorePaymentMethodEnum = none+ metadata: [MetadataInput!]}type PaymentRefund {@@ -6420,7 +6422,7 @@ input StockInput {quantity: Int!}-enum StoreEnum {+enum StorePaymentMethodEnum {ON_SESSIONOFF_SESSIONNONEdiff --git a/saleor/payment/interface.py b/saleor/payment/interface.pyindex 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] = Nonegraphql_customer_id: Optional[str] = None- store: StoreEnum = StoreEnum.NONE+ store_payment_method: StoreEnum = StoreEnum.NONEpayment_metadata: Dict[str, str] = field(default_factory=dict)diff --git a/saleor/payment/utils.py b/saleor/payment/utils.pyindex 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,}