Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add metadata to payments (#7935)
Mateusz Grzyb338427f90be1
diff --git a/saleor/graphql/meta/permissions.py b/saleor/graphql/meta/permissions.pyindex c310b492ee..857843103e 100644--- a/saleor/graphql/meta/permissions.py+++ b/saleor/graphql/meta/permissions.py@@ -15,10 +15,12 @@ from ...core.permissions import (OrderPermissions,PagePermissions,PageTypePermissions,+ PaymentPermissions,ProductPermissions,ProductTypePermissions,ShippingPermissions,)+from ...payment.utils import payment_owned_by_userdef no_permissions(_info, _object_pk: Any) -> List[None]:@@ -103,6 +105,21 @@ def discount_permissions(_info, _object_pk: Any) -> List[BasePermissionEnum]:return [DiscountPermissions.MANAGE_DISCOUNTS]+def public_payment_permissions(info, payment_pk: int) -> List[BasePermissionEnum]:+ context_user = info.context.user+ if info.context.app is not None or context_user.is_staff:+ return [PaymentPermissions.HANDLE_PAYMENTS]+ if payment_owned_by_user(payment_pk, context_user):+ return []+ raise PermissionDenied()+++def private_payment_permissions(info, _object_pk: Any) -> List[BasePermissionEnum]:+ if info.context.app is not None or info.context.user.is_staff:+ return [PaymentPermissions.HANDLE_PAYMENTS]+ raise PermissionDenied()++def gift_card_permissions(_info, _object_pk: Any) -> List[BasePermissionEnum]:return [GiftcardPermissions.MANAGE_GIFT_CARD]@@ -122,6 +139,7 @@ PUBLIC_META_PERMISSION_MAP = {"Order": no_permissions,"Page": page_permissions,"PageType": page_type_permissions,+ "Payment": public_payment_permissions,"Product": product_permissions,"ProductType": product_type_permissions,"ProductVariant": product_permissions,@@ -149,6 +167,7 @@ PRIVATE_META_PERMISSION_MAP = {"Order": order_permissions,"Page": page_permissions,"PageType": page_type_permissions,+ "Payment": private_payment_permissions,"Product": product_permissions,"ProductType": product_type_permissions,"ProductVariant": product_permissions,diff --git a/saleor/graphql/meta/resolvers.py b/saleor/graphql/meta/resolvers.pyindex b3964e1f82..e47b1a35cc 100644--- a/saleor/graphql/meta/resolvers.py+++ b/saleor/graphql/meta/resolvers.py@@ -10,6 +10,7 @@ from ...discount import models as discount_modelsfrom ...giftcard import models as giftcard_modelsfrom ...order import models as order_modelsfrom ...page import models as page_models+from ...payment import models as payment_modelsfrom ...product import models as product_modelsfrom ...shipping import models as shipping_modelsfrom ...warehouse import models as warehouse_models@@ -31,6 +32,7 @@ def resolve_object_with_metadata_type(instance: ModelWithMetadata):from ..menu import types as menu_typesfrom ..order import types as order_typesfrom ..page import types as page_types+ from ..payment import types as payment_typesfrom ..product import types as product_typesfrom ..shipping import types as shipping_typesfrom ..warehouse import types as warehouse_types@@ -48,6 +50,7 @@ def resolve_object_with_metadata_type(instance: ModelWithMetadata):invoice_models.Invoice: invoice_types.Invoice,page_models.Page: page_types.Page,page_models.PageType: page_types.PageType,+ payment_models.Payment: payment_types.Payment,product_models.Product: product_types.Product,product_models.ProductType: product_types.ProductType,product_models.ProductVariant: product_types.ProductVariant,@@ -83,6 +86,7 @@ def resolve_private_metadata(root: ModelWithMetadata, info):raise PermissionDenied()required_permission = get_required_permission(info, root.pk)+if not required_permission:raise PermissionDenied()diff --git a/saleor/graphql/meta/tests/conftest.py b/saleor/graphql/meta/tests/conftest.pynew file mode 100644index 0000000000..6059789a30--- /dev/null+++ b/saleor/graphql/meta/tests/conftest.py@@ -0,0 +1,21 @@+import pytest++PRIVATE_KEY = "private_key"+PRIVATE_VALUE = "private_vale"++PUBLIC_KEY = "key"+PUBLIC_VALUE = "value"+++def payment_with_public_metadata(payment):+ payment.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})+ payment.save(update_fields=["metadata"])+ return payment+++def payment_with_private_metadata(payment):+ payment.store_value_in_private_metadata({PRIVATE_KEY: PRIVATE_VALUE})+ payment.save(update_fields=["private_metadata"])+ return paymentdiff --git a/saleor/graphql/meta/tests/test_meta_mutations.py b/saleor/graphql/meta/tests/test_meta_mutations.pyindex 62692c72c8..283535b371 100644--- a/saleor/graphql/meta/tests/test_meta_mutations.py+++ b/saleor/graphql/meta/tests/test_meta_mutations.py@@ -9,6 +9,7 @@ from django.core.exceptions import ValidationErrorfrom ....core.error_codes import MetadataErrorCodefrom ....core.models import ModelWithMetadatafrom ....invoice.models import Invoice+from ....payment.utils import payment_owned_by_userfrom ...tests.utils import assert_no_permission, get_graphql_contentPRIVATE_KEY = "private_key"@@ -732,6 +733,69 @@ def test_update_public_metadata_for_item_without_meta(api_client, address):assert errors[0]["code"] == MetadataErrorCode.NOT_FOUND.name+def test_update_public_metadata_for_payment_by_logged_user(+ user_api_client, payment_with_public_metadata+):+ # given+ payment_with_public_metadata.order.user = user_api_client.user+ payment_with_public_metadata.order.save()+ payment_id = graphene.Node.to_global_id("Payment", payment_with_public_metadata.pk)++ # when+ response = execute_update_public_metadata_for_item(+ user_api_client, None, payment_id, "Payment", value="NewMetaValue"+ )++ # then+ assert item_contains_proper_public_metadata(+ response["data"]["updateMetadata"]["item"],+ payment_with_public_metadata,+ payment_id,+ value="NewMetaValue",+ )+++def test_update_public_metadata_for_payment_by_different_logged_user(+ user2_api_client, payment_with_public_metadata+):+ # given+ assert not payment_owned_by_user(+ payment_with_public_metadata.pk, user2_api_client.user+ )+ payment_id = graphene.Node.to_global_id("Payment", payment_with_public_metadata.pk)+ variables = {+ "id": payment_id,+ "input": [{"key": PUBLIC_KEY, "value": "NewMetaValue"}],+ }++ # when+ response = user2_api_client.post_graphql(+ UPDATE_PUBLIC_METADATA_MUTATION % "Payment", variables, permissions=None+ )++ # then+ assert_no_permission(response)+++def test_update_public_metadata_for_payment_by_non_logged_user(+ api_client, payment_with_public_metadata+):+ # given+ payment_id = graphene.Node.to_global_id("Payment", payment_with_public_metadata.pk)+ variables = {+ "id": payment_id,+ "input": [{"key": PUBLIC_KEY, "value": "NewMetaValue"}],+ }++ # when+ response = api_client.post_graphql(+ UPDATE_PUBLIC_METADATA_MUTATION % "Payment", variables, permissions=None+ )++ # then+ assert_no_permission(response)++def test_add_public_metadata_for_warehouse(staff_api_client, permission_manage_products, warehouse):@@ -1715,7 +1779,7 @@ def test_staff_update_private_metadata_empty_key(admin_id = graphene.Node.to_global_id("User", admin_user.pk)# when- response = response = execute_update_private_metadata_for_item(+ response = execute_update_private_metadata_for_item(staff_api_client,permission_manage_staff,admin_id,@@ -2171,6 +2235,109 @@ def test_update_private_metadata_for_item_without_meta(api_client, address):assert errors[0]["code"] == MetadataErrorCode.NOT_FOUND.name+def test_update_private_metadata_for_payment_by_staff(+ staff_api_client, permission_manage_payments, payment_with_private_metadata+):+ # given+ payment_id = graphene.Node.to_global_id("Payment", payment_with_private_metadata.pk)++ # when+ response = execute_update_private_metadata_for_item(+ staff_api_client,+ permission_manage_payments,+ payment_id,+ "Payment",+ value="NewMetaValue",+ )++ # then+ assert item_contains_proper_private_metadata(+ response["data"]["updatePrivateMetadata"]["item"],+ payment_with_private_metadata,+ payment_id,+ value="NewMetaValue",+ )+++def test_update_private_metadata_for_payment_by_app(+ app_api_client, permission_manage_payments, payment_with_private_metadata+):+ # given+ payment_id = graphene.Node.to_global_id("Payment", payment_with_private_metadata.pk)++ # when+ response = execute_update_private_metadata_for_item(+ app_api_client,+ permission_manage_payments,+ payment_id,+ "Payment",+ value="NewMetaValue",+ )++ # then+ assert item_contains_proper_private_metadata(+ response["data"]["updatePrivateMetadata"]["item"],+ payment_with_private_metadata,+ payment_id,+ value="NewMetaValue",+ )+++def test_update_private_metadata_for_payment_by_staff_without_permission(+ staff_api_client, payment_with_private_metadata+):+ # given+ payment_id = graphene.Node.to_global_id("Payment", payment_with_private_metadata.pk)+ variables = {+ "id": payment_id,+ "input": [{"key": PRIVATE_KEY, "value": "NewMetaValue"}],+ }++ # when+ response = staff_api_client.post_graphql(+ UPDATE_PRIVATE_METADATA_MUTATION % "Payment", variables, permissions=None+ )++ # then+ assert_no_permission(response)+++def test_update_private_metadata_for_payment_by_app_without_permission(+ app_api_client, payment+):+ # given+ payment_id = graphene.Node.to_global_id("Payment", payment.pk)+ variables = {+ "id": payment_id,+ "input": [{"key": PRIVATE_KEY, "value": "NewMetaValue"}],+ }++ # when+ response = app_api_client.post_graphql(+ UPDATE_PRIVATE_METADATA_MUTATION % "Payment", variables, permissions=None+ )++ # then+ assert_no_permission(response)+++def test_update_private_metadata_by_customer(user_api_client, payment):+ # given+ payment_id = graphene.Node.to_global_id("Payment", payment.pk)+ variables = {+ "id": payment_id,+ "input": [{"key": PRIVATE_KEY, "value": "NewMetaValue"}],+ }++ # when+ response = user_api_client.post_graphql(+ UPDATE_PRIVATE_METADATA_MUTATION % "Payment", variables, permissions=None+ )++ # then+ assert_no_permission(response)++def test_add_private_metadata_for_warehouse(staff_api_client, permission_manage_products, warehouse):diff --git a/saleor/graphql/meta/tests/test_meta_queries.py b/saleor/graphql/meta/tests/test_meta_queries.pyindex 828c964740..0126eaa610 100644--- a/saleor/graphql/meta/tests/test_meta_queries.py+++ b/saleor/graphql/meta/tests/test_meta_queries.py@@ -1,5 +1,14 @@+from typing import List+import graphene+from django.contrib.auth.models import Permission+from django.http import HttpResponse++from saleor.core.models import ModelWithMetadata+from saleor.payment.models import Payment+from saleor.payment.utils import payment_owned_by_user+from ...tests.fixtures import ApiClientfrom ...tests.utils import assert_no_permission, get_graphql_contentPRIVATE_KEY = "private_key"@@ -9,6 +18,35 @@ PUBLIC_KEY = "key"PUBLIC_VALUE = "value"+def execute_query(+ query_str: str,+ client: ApiClient,+ model: ModelWithMetadata,+ model_name: str,+ permissions: List[Permission] = None,+):+ return client.post_graphql(+ query_str,+ variables={"id": graphene.Node.to_global_id(model_name, model.pk)},+ permissions=[] if permissions is None else permissions,+ check_no_permissions=False,+ )+++def assert_model_contains_metadata(response: HttpResponse, model_name: str):+ content = get_graphql_content(response)+ metadata = content["data"][model_name]["metadata"][0]+ assert metadata["key"] == PUBLIC_KEY+ assert metadata["value"] == PUBLIC_VALUE+++def assert_model_contains_private_metadata(response: HttpResponse, model_name: str):+ content = get_graphql_content(response)+ metadata = content["data"][model_name]["privateMetadata"][0]+ assert metadata["key"] == PRIVATE_KEY+ assert metadata["value"] == PRIVATE_VALUE++QUERY_SELF_PUBLIC_META = """{me{@@ -997,6 +1035,125 @@ def test_query_public_meta_for_digital_content_as_app(assert metadata["value"] == PUBLIC_VALUE+QUERY_PAYMENT_PUBLIC_META = """+ query paymentsMeta($id: ID!){+ payment(id: $id){+ metadata{+ key+ value+ }+ }+ }+"""+++def execute_query_public_metadata_for_payment(+ client: ApiClient, payment: Payment, permissions: List[Permission] = None+):+ return execute_query(+ QUERY_PAYMENT_PUBLIC_META, client, payment, "Payment", permissions+ )+++def assert_payment_contains_metadata(response):+ assert_model_contains_metadata(response, "payment")+++def test_query_public_meta_for_payment_as_customer(+ user_api_client, payment_with_public_metadata, permission_manage_orders+):+ # given+ assert payment_owned_by_user(payment_with_public_metadata.pk, user_api_client.user)++ # when+ response = execute_query_public_metadata_for_payment(+ user_api_client,+ payment_with_public_metadata,+ permissions=[permission_manage_orders],+ )++ # then+ assert_payment_contains_metadata(response)+++def test_query_public_meta_for_payment_as_another_customer(+ user2_api_client,+ payment_with_public_metadata,+ permission_manage_orders,+):+ # given+ assert not payment_owned_by_user(+ payment_with_public_metadata.pk, user2_api_client.user+ )+ # when+ response = execute_query_public_metadata_for_payment(+ user2_api_client,+ payment_with_public_metadata,+ permissions=[permission_manage_orders],+ )++ # then+ assert_no_permission(response)+++def test_query_public_meta_for_payment_as_staff_with_permission(+ staff_api_client,+ payment_with_public_metadata,+ permission_manage_orders,+ permission_manage_payments,+):+ # when+ response = execute_query_public_metadata_for_payment(+ staff_api_client,+ payment_with_public_metadata,+ permissions=[permission_manage_orders, permission_manage_payments],+ )++ # then+ assert_payment_contains_metadata(response)+++def test_query_public_meta_for_payment_as_staff_without_permission(+ staff_api_client, payment_with_public_metadata+):+ # when+ response = execute_query_public_metadata_for_payment(+ staff_api_client, payment_with_public_metadata+ )++ # then+ assert_no_permission(response)+++def test_query_public_meta_for_payment_as_app_with_permission(+ app_api_client,+ payment_with_public_metadata,+ permission_manage_orders,+ permission_manage_payments,+):+ # when+ response = execute_query_public_metadata_for_payment(+ app_api_client,+ payment_with_public_metadata,+ permissions=[permission_manage_orders, permission_manage_payments],+ )++ # then+ assert_payment_contains_metadata(response)+++def test_query_public_meta_for_payment_as_app_without_permission(+ app_api_client, payment_with_public_metadata+):+ # when+ response = execute_query_public_metadata_for_payment(+ app_api_client, payment_with_public_metadata+ )++ # then+ assert_no_permission(response)++QUERY_PRODUCT_PUBLIC_META = """query productsMeta($id: ID!, $channel: String){product(id: $id, channel: $channel){@@ -2485,6 +2642,88 @@ def test_query_private_meta_for_digital_content_as_app(assert metadata["value"] == PRIVATE_VALUE+QUERY_PAYMENT_PRIVATE_META = """+ query paymentsMeta($id: ID!){+ payment(id: $id){+ privateMetadata{+ key+ value+ }+ }+ }+"""+++def execute_query_private_metadata_for_payment(+ client: ApiClient, payment: Payment, permissions: List[Permission] = None+):+ return execute_query(+ QUERY_PAYMENT_PRIVATE_META, client, payment, "Payment", permissions+ )+++def assert_payment_contains_private_metadata(response):+ assert_model_contains_private_metadata(response, "payment")+++def test_query_private_meta_for_payment_as_staff_with_permission(+ staff_api_client,+ payment_with_private_metadata,+ permission_manage_orders,+ permission_manage_payments,+):+ # when+ response = execute_query_private_metadata_for_payment(+ staff_api_client,+ payment_with_private_metadata,+ permissions=[permission_manage_orders, permission_manage_payments],+ )++ # then+ assert_payment_contains_private_metadata(response)+++def test_query_private_meta_for_payment_as_staff_without_permission(+ staff_api_client, payment_with_private_metadata+):+ # when+ response = execute_query_private_metadata_for_payment(+ staff_api_client, payment_with_private_metadata+ )++ # then+ assert_no_permission(response)+++def test_query_private_meta_for_payment_as_app_with_permission(+ app_api_client,+ payment_with_private_metadata,+ permission_manage_orders,+ permission_manage_payments,+):+ # when+ response = execute_query_private_metadata_for_payment(+ app_api_client,+ payment_with_private_metadata,+ permissions=[permission_manage_orders, permission_manage_payments],+ )++ # then+ assert_payment_contains_private_metadata(response)+++def test_query_private_meta_for_payment_as_app_without_permission(+ app_api_client, payment_with_private_metadata+):+ # when+ response = execute_query_private_metadata_for_payment(+ app_api_client, payment_with_private_metadata+ )++ # then+ assert_no_permission(response)++QUERY_PRODUCT_PRIVATE_META = """query productsMeta($id: ID!, $channel: String){product(id: $id, channel: $channel){diff --git a/saleor/graphql/payment/types.py b/saleor/graphql/payment/types.pyindex fe1361f1c1..aac7c747f1 100644--- a/saleor/graphql/payment/types.py+++ b/saleor/graphql/payment/types.py@@ -1,10 +1,15 @@import graphenefrom graphene import relay+from ...core.exceptions import PermissionDeniedfrom ...core.tracing import traced_resolverfrom ...payment import modelsfrom ..core.connection import CountableDjangoObjectTypefrom ..core.types import Money+from ..meta.permissions import public_payment_permissions+from ..meta.resolvers import resolve_metadata+from ..meta.types import ObjectWithMetadata+from ..utils import get_user_or_app_from_contextfrom .enums import OrderAction, PaymentChargeStatusEnum@@ -94,7 +99,7 @@ class Payment(CountableDjangoObjectType):class Meta:description = "Represents a payment of a given type."- interfaces = [relay.Node]+ interfaces = [relay.Node, ObjectWithMetadata]model = models.Paymentfilter_fields = ["id"]only_fields = [@@ -161,6 +166,14 @@ class Payment(CountableDjangoObjectType):return Nonereturn CreditCard(**data)+ @staticmethod+ def resolve_metadata(root: models.Payment, info):+ permissions = public_payment_permissions(info, root.pk)+ requester = get_user_or_app_from_context(info.context)+ if not requester.has_perms(permissions):+ raise PermissionDenied()+ return resolve_metadata(root.metadata)+class PaymentInitialized(graphene.ObjectType):class Meta:diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 2309de6243..4d4a6f06a5 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -4689,7 +4689,7 @@ type PasswordChange {errors: [AccountError!]!}-type Payment implements Node {+type Payment implements Node & ObjectWithMetadata {id: ID!gateway: String!isActive: Boolean!@@ -4700,6 +4700,8 @@ type Payment implements Node {order: OrderpaymentMethodType: String!customerIpAddress: String+ privateMetadata: [MetadataItem]!+ metadata: [MetadataItem]!chargeStatus: PaymentChargeStatusEnum!actions: [OrderAction]!total: Moneydiff --git a/saleor/graphql/tests/fixtures.py b/saleor/graphql/tests/fixtures.pyindex 97993abd15..0951c3ae14 100644--- a/saleor/graphql/tests/fixtures.py+++ b/saleor/graphql/tests/fixtures.py@@ -138,6 +138,11 @@ def user_api_client(customer_user):return ApiClient(user=customer_user)+def user2_api_client(customer_user2):+ return ApiClient(user=customer_user2)++@pytest.fixturedef api_client():return ApiClient(user=AnonymousUser())diff --git a/saleor/payment/__init__.py b/saleor/payment/__init__.pyindex 88b0e329ec..713f2d1663 100644--- a/saleor/payment/__init__.py+++ b/saleor/payment/__init__.py@@ -119,3 +119,25 @@ class ChargeStatus:(REFUSED, "Refused"),(CANCELLED, "Cancelled"),]+++class Store:+ """Represents if and how a payment should be stored in a payment gateway.++ The following store types are possible:+ - ON_SESSION - the payment is stored only to be reused when+ the customer is present in the checkout flow+ - OFF_SESSION - the payment is stored to be reused even if+ the customer is absent+ - NONE - the payment is not stored.+ """++ ON_SESSION = "on_session"+ OFF_SESSION = "off_session"+ NONE = "none"++ CHOICES = [+ (ON_SESSION, "On session"),+ (OFF_SESSION, "Off session"),+ (NONE, "None"),+ ]diff --git a/saleor/payment/migrations/0030_auto_20210825_1338.py b/saleor/payment/migrations/0030_auto_20210825_1338.pynew file mode 100644index 0000000000..b04fa675be--- /dev/null+++ b/saleor/payment/migrations/0030_auto_20210825_1338.py@@ -0,0 +1,61 @@+# Generated by Django 3.2.5 on 2021-08-25 13:38++import django.contrib.postgres.indexes+from django.db import migrations, models++import saleor.core.utils.json_serializer+++class Migration(migrations.Migration):++ dependencies = [+ ("payment", "0029_alter_payment_options"),+ ]++ operations = [+ migrations.AddField(+ model_name="payment",+ name="metadata",+ field=models.JSONField(+ blank=True,+ default=dict,+ encoder=saleor.core.utils.json_serializer.CustomJsonEncoder,+ null=True,+ ),+ ),+ migrations.AddField(+ model_name="payment",+ name="private_metadata",+ field=models.JSONField(+ blank=True,+ default=dict,+ encoder=saleor.core.utils.json_serializer.CustomJsonEncoder,+ null=True,+ ),+ ),+ migrations.AddField(+ model_name="payment",+ name="store",+ field=models.CharField(+ choices=[+ ("on_session", "On session"),+ ("off_session", "Off session"),+ ("none", "None"),+ ],+ default="none",+ max_length=11,+ ),+ ),+ migrations.AddIndex(+ model_name="payment",+ index=django.contrib.postgres.indexes.GinIndex(+ fields=["private_metadata"], name="payment_p_meta_idx"+ ),+ ),+ migrations.AddIndex(+ model_name="payment",+ index=django.contrib.postgres.indexes.GinIndex(+ fields=["metadata"], name="payment_meta_idx"+ ),+ ),+ ]diff --git a/saleor/payment/models.py b/saleor/payment/models.pyindex 03b4bf47c6..415047e91e 100644--- a/saleor/payment/models.py+++ b/saleor/payment/models.py@@ -10,12 +10,13 @@ from django.db.models import JSONField # type: ignorefrom prices import Moneyfrom ..checkout.models import Checkout+from ..core.models import ModelWithMetadatafrom ..core.permissions import PaymentPermissionsfrom ..core.taxes import zero_money-from . import ChargeStatus, CustomPaymentChoices, TransactionKind+from . import ChargeStatus, CustomPaymentChoices, Store, TransactionKind-class Payment(models.Model):+class Payment(ModelWithMetadata):"""A model that represents a single payment.This might be a transactable payment information such as credit card@@ -59,6 +60,7 @@ class Payment(models.Model):order = models.ForeignKey("order.Order", null=True, related_name="payments", on_delete=models.PROTECT)+ store = models.CharField(max_length=11, choices=Store.CHOICES, default=Store.NONE)billing_email = models.EmailField(blank=True)billing_first_name = models.CharField(max_length=256, blank=True)@@ -100,6 +102,7 @@ class Payment(models.Model):),)indexes = [+ *ModelWithMetadata.Meta.indexes,# Orders filtering by status indexGinIndex(fields=["order_id", "is_active", "charge_status"]),]diff --git a/saleor/payment/tests/test_payment.py b/saleor/payment/tests/test_payment.pyindex b88cd960cf..e2d0e5f4ca 100644--- a/saleor/payment/tests/test_payment.py+++ b/saleor/payment/tests/test_payment.py@@ -2,11 +2,12 @@ from decimal import Decimalfrom unittest.mock import Mock, patchimport pytest+from django.contrib.auth.models import AnonymousUserfrom ...checkout.calculations import checkout_totalfrom ...checkout.fetch import fetch_checkout_info, fetch_checkout_linesfrom ...plugins.manager import PluginsManager, get_plugins_manager-from .. import ChargeStatus, GatewayError, PaymentError, TransactionKind, gateway+from .. import ChargeStatus, GatewayError, PaymentError, Store, TransactionKind, gatewayfrom ..error_codes import PaymentErrorCodefrom ..interface import GatewayResponse, PaymentMethodInfofrom ..models import Payment@@ -18,6 +19,7 @@ from ..utils import (create_payment_information,create_transaction,is_currency_supported,+ payment_owned_by_user,update_payment,validate_gateway_response,)@@ -111,6 +113,7 @@ def test_create_payment(checkout_with_item, address):}payment = create_payment(**data)assert payment.gateway == "Dummy"+ assert payment.store == Store.NONEsame_payment = create_payment(**data)assert payment == same_payment@@ -550,3 +553,68 @@ def test_update_payment(gateway_response, payment_txn_captured):assert payment.cc_exp_year == gateway_response.payment_method_info.exp_yearassert payment.cc_exp_month == gateway_response.payment_method_info.exp_monthassert payment.payment_method_type == gateway_response.payment_method_info.type+++def test_payment_owned_by_user_from_order(payment, customer_user2):+ # given+ assert payment.checkout is None+ payment.order.user = customer_user2+ payment.order.save()++ # when+ is_owned = payment_owned_by_user(payment.pk, customer_user2)++ # then+ assert is_owned+++def test_payment_owned_by_user_from_checkout(payment, checkout, customer_user2):+ # given+ checkout.user = customer_user2+ checkout.save()+ payment.checkout = checkout+ payment.order = None+ payment.save()++ # when+ is_owned = payment_owned_by_user(payment.pk, customer_user2)++ # then+ assert is_owned+++def test_payment_is_not_owned_by_user_for_order(payment, customer_user2):+ # given+ assert payment.checkout is None+ assert payment.order.user != customer_user2++ # when+ is_owned = payment_owned_by_user(payment.pk, customer_user2)++ # then+ assert not is_owned+++def test_payment_is_not_owned_by_user_for_checkout(payment, checkout, customer_user2):+ # given+ assert checkout.user != customer_user2+ payment.checkout = checkout+ payment.order = None+ payment.save()++ # when+ is_owned = payment_owned_by_user(payment.pk, customer_user2)++ # then+ assert not is_owned+++def test_payment_owned_by_user_anonymous_user(payment):+ # given+ user = AnonymousUser()++ # when+ is_owned = payment_owned_by_user(payment.pk, user)++ # then+ assert not is_owneddiff --git a/saleor/payment/utils.py b/saleor/payment/utils.pyindex c456a92531..8c35dc003f 100644--- a/saleor/payment/utils.py+++ b/saleor/payment/utils.py@@ -6,6 +6,7 @@ from typing import TYPE_CHECKING, Dict, List, Optionalimport graphenefrom babel.numbers import get_currency_precisionfrom django.core.serializers.json import DjangoJSONEncoder+from django.db.models import Qfrom ..account.models import Userfrom ..checkout.models import Checkout@@ -427,3 +428,14 @@ def price_to_minor_unit(value: Decimal, currency: str):number_places = Decimal("10.0") ** precisionvalue_without_comma = value * number_placesreturn str(value_without_comma.quantize(Decimal("1")))+++def payment_owned_by_user(payment_pk: int, user) -> bool:+ if user.is_anonymous:+ return False+ return (+ Payment.objects.filter(+ (Q(order__user=user) | Q(checkout__user=user)) & Q(pk=payment_pk)+ ).first()+ is not None+ )diff --git a/saleor/plugins/webhook/tests/test_payment_webhook.py b/saleor/plugins/webhook/tests/test_payment_webhook.pyindex ca063f0a86..3975a4e783 100644--- a/saleor/plugins/webhook/tests/test_payment_webhook.py+++ b/saleor/plugins/webhook/tests/test_payment_webhook.py@@ -21,15 +21,6 @@ from ..utils import ()-def payment(payment_dummy, payment_app):- gateway_id = "credit-card"- gateway = to_payment_app_id(payment_app, gateway_id)- payment_dummy.gateway = gateway- payment_dummy.save()- return payment_dummy--@pytest.fixturedef payment_invalid_app(payment_dummy):app = App.objects.create(name="Dummy app", is_active=True)diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex f6c7749796..b5a3a4ddf8 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -538,6 +538,22 @@ def customer_user(address): # pylint: disable=W0613return user+def customer_user2(address):+ default_address = address.get_copy()+ user = User.objects.create_user(+ "[email protected]",+ "password",+ default_billing_address=default_address,+ default_shipping_address=default_address,+ first_name="Jane",+ last_name="Doe",+ )+ user.addresses.add(default_address)+ user._password = "password"+ return user++@pytest.fixturedef user_checkout(customer_user, channel_USD):checkout = Checkout.objects.create(@@ -3845,6 +3861,15 @@ def payment_dummy(db, order_with_lines):)+def payment(payment_dummy, payment_app):+ gateway_id = "credit-card"+ gateway = to_payment_app_id(payment_app, gateway_id)+ payment_dummy.gateway = gateway+ payment_dummy.save()+ return payment_dummy++@pytest.fixturedef payment_dummy_fully_charged(payment_dummy):payment_dummy.captured_amount = payment_dummy.total