Skip to content

Commit

Permalink
server/checkout: allow to pass customer_metadata that'll be copied ov…
Browse files Browse the repository at this point in the history
…er to the created customer
  • Loading branch information
frankie567 committed Dec 17, 2024
1 parent 2d55075 commit 6c8d3e8
Show file tree
Hide file tree
Showing 7 changed files with 148 additions and 16 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
"""Add Checkout.customer_metadata
Revision ID: cb9906114207
Revises: a3e70f4c4e1e
Create Date: 2024-12-17 17:56:12.495724
"""

import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql

# Polar Custom Imports

# revision identifiers, used by Alembic.
revision = "cb9906114207"
down_revision = "a3e70f4c4e1e"
branch_labels: tuple[str] | None = None
depends_on: tuple[str] | None = None


def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.add_column(
"checkouts",
sa.Column(
"customer_metadata", postgresql.JSONB(astext_type=sa.Text()), nullable=True
),
)

op.execute(
"UPDATE checkouts SET customer_metadata = '{}' WHERE customer_metadata IS NULL"
)

op.alter_column("checkouts", "customer_metadata", nullable=False)

# ### end Alembic commands ###


def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column("checkouts", "customer_metadata")
# ### end Alembic commands ###
15 changes: 15 additions & 0 deletions server/polar/checkout/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@
from polar.enums import PaymentProcessor
from polar.kit.address import Address
from polar.kit.metadata import (
METADATA_DESCRIPTION,
MetadataField,
MetadataInputMixin,
MetadataOutputMixin,
OptionalMetadataInputMixin,
Expand Down Expand Up @@ -101,6 +103,12 @@
"If you apply a discount through `discount_id`, it'll still be applied, "
"but the customer won't be able to change it."
)
_customer_metadata_description = METADATA_DESCRIPTION.format(
heading=(
"Key-value object allowing you to store additional information "
"that'll be copied to the created customer."
)
)


class CheckoutCreateBase(CustomFieldDataInputMixin, MetadataInputMixin, Schema):
Expand Down Expand Up @@ -134,6 +142,9 @@ class CheckoutCreateBase(CustomFieldDataInputMixin, MetadataInputMixin, Schema):
customer_ip_address: CustomerIPAddress | None = None
customer_billing_address: CustomerBillingAddress | None = None
customer_tax_id: Annotated[str | None, EmptyStrToNoneValidator] = None
customer_metadata: MetadataField = Field(
default_factory=dict, description=_customer_metadata_description
)
subscription_id: UUID4 | None = Field(
default=None,
description=(
Expand Down Expand Up @@ -217,6 +228,9 @@ class CheckoutUpdate(OptionalMetadataInputMixin, CheckoutUpdateBase):
default=None, description=_allow_discount_codes_description
)
customer_ip_address: CustomerIPAddress | None = None
customer_metadata: MetadataField | None = Field(
default=None, description=_customer_metadata_description
)
success_url: SuccessURL = None
embed_origin: EmbedOrigin = None

Expand Down Expand Up @@ -406,6 +420,7 @@ class Checkout(MetadataOutputMixin, CheckoutBase):
discount: CheckoutDiscount | None
subscription_id: UUID4 | None
attached_custom_fields: list[AttachedCustomField]
customer_metadata: dict[str, str | int | bool]


class CheckoutPublic(CheckoutBase):
Expand Down
5 changes: 5 additions & 0 deletions server/polar/checkout/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -1599,6 +1599,7 @@ async def _create_or_update_customer(
billing_address=checkout.customer_billing_address,
tax_id=checkout.customer_tax_id,
organization=checkout.organization,
user_metadata={},
)

stripe_customer_id = customer.stripe_customer_id
Expand Down Expand Up @@ -1628,6 +1629,10 @@ async def _create_or_update_customer(
**update_params,
)
customer.stripe_customer_id = stripe_customer_id
customer.user_metadata = {
**customer.user_metadata,
**checkout.customer_metadata,
}

session.add(customer)
await session.flush()
Expand Down
36 changes: 21 additions & 15 deletions server/polar/kit/metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import Mapped, mapped_column

MetadataColumn = Annotated[
dict[str, Any], mapped_column(JSONB, nullable=False, default=dict)
]


class MetadataMixin:
user_metadata: Mapped[dict[str, Any]] = mapped_column(
JSONB, nullable=False, default=dict
)
user_metadata: Mapped[MetadataColumn]


_MAXIMUM_KEYS = 50
Expand All @@ -28,9 +30,10 @@ class MetadataMixin:
),
]
_MetadataValue = _MetadataValueString | int | bool
_description = inspect.cleandoc(

METADATA_DESCRIPTION = inspect.cleandoc(
f"""
Key-value object allowing you to store additional information.
{{heading}}
The key must be a string with a maximum length of **{_MAXIMUM_KEY_LENGTH} characters**.
The value must be either:
Expand All @@ -42,23 +45,26 @@ class MetadataMixin:
You can store up to **{_MAXIMUM_KEYS} key-value pairs**.
"""
)
_description = METADATA_DESCRIPTION.format(
heading="Key-value object allowing you to store additional information."
)


MetadataField = Annotated[
dict[_MetadataKey, _MetadataValue],
Field(max_length=_MAXIMUM_KEYS, description=_description),
]


class MetadataInputMixin(BaseModel):
metadata: dict[_MetadataKey, _MetadataValue] = Field(
default_factory=dict,
max_length=_MAXIMUM_KEYS,
description=_description,
serialization_alias="user_metadata",
metadata: MetadataField = Field(
default_factory=dict, serialization_alias="user_metadata"
)


class OptionalMetadataInputMixin(BaseModel):
metadata: dict[_MetadataKey, _MetadataValue] | None = Field(
default=None,
max_length=_MAXIMUM_KEYS,
description=_description,
serialization_alias="user_metadata",
metadata: MetadataField | None = Field(
default=None, serialization_alias="user_metadata"
)


Expand Down
3 changes: 2 additions & 1 deletion server/polar/models/checkout.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
from polar.enums import PaymentProcessor
from polar.kit.address import Address, AddressType
from polar.kit.db.models import RecordModel
from polar.kit.metadata import MetadataMixin
from polar.kit.metadata import MetadataColumn, MetadataMixin
from polar.kit.tax import TaxID, TaxIDType
from polar.kit.utils import utc_now

Expand Down Expand Up @@ -135,6 +135,7 @@ def customer(cls) -> Mapped[Customer | None]:
customer_tax_id: Mapped[TaxID | None] = mapped_column(
TaxIDType, nullable=True, default=None
)
customer_metadata: Mapped[MetadataColumn]

subscription_id: Mapped[UUID | None] = mapped_column(
Uuid, ForeignKey("subscriptions.id", ondelete="set null"), nullable=True
Expand Down
58 changes: 58 additions & 0 deletions server/tests/checkout/test_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -1037,6 +1037,29 @@ async def test_valid_customer(
assert checkout.customer_billing_address == customer.billing_address
assert checkout.customer_tax_id == customer.tax_id

@pytest.mark.auth(
AuthSubjectFixture(subject="user"),
AuthSubjectFixture(subject="organization"),
)
async def test_customer_metadata(
self,
session: AsyncSession,
auth_subject: AuthSubject[User | Organization],
product_one_time: Product,
user_organization: UserOrganization,
) -> None:
checkout = await checkout_service.create(
session,
CheckoutProductCreate(
payment_processor=PaymentProcessor.stripe,
product_id=product_one_time.id,
customer_metadata={"key": "value"},
),
auth_subject,
)

assert checkout.customer_metadata == {"key": "value"}


@pytest.mark.asyncio
@pytest.mark.skip_db_asserts
Expand Down Expand Up @@ -1696,6 +1719,21 @@ async def test_valid_metadata(

assert checkout.user_metadata == {"key": "value"}

async def test_valid_customer_metadata(
self,
session: AsyncSession,
checkout_one_time_free: Checkout,
) -> None:
checkout = await checkout_service.update(
session,
checkout_one_time_free,
CheckoutUpdate(
customer_metadata={"key": "value"},
),
)

assert checkout.customer_metadata == {"key": "value"}

@pytest.mark.parametrize(
"custom_field_data",
(
Expand Down Expand Up @@ -1952,6 +1990,7 @@ async def test_calculate_tax_error(
)
async def test_valid_stripe(
self,
save_fixture: SaveFixture,
customer_billing_address: dict[str, str],
expected_tax_metadata: dict[str, str],
stripe_service_mock: MagicMock,
Expand All @@ -1960,6 +1999,9 @@ async def test_valid_stripe(
auth_subject: AuthSubject[Anonymous],
checkout_one_time_fixed: Checkout,
) -> None:
checkout_one_time_fixed.customer_metadata = {"key": "value"}
await save_fixture(checkout_one_time_fixed)

stripe_service_mock.create_customer.return_value = SimpleNamespace(
id="STRIPE_CUSTOMER_ID"
)
Expand Down Expand Up @@ -1997,6 +2039,9 @@ async def test_valid_stripe(
**expected_tax_metadata,
}

assert checkout.customer is not None
assert checkout.customer.user_metadata == {"key": "value"}

assert checkout.customer_session_token is not None
customer_session = await customer_session_service.get_by_token(
session, checkout.customer_session_token
Expand Down Expand Up @@ -2125,9 +2170,11 @@ async def test_valid_stripe_existing_customer(
save_fixture,
organization=organization,
stripe_customer_id="CHECKOUT_CUSTOMER_ID",
user_metadata={"key": "value"},
)
checkout_one_time_fixed.customer = customer
checkout_one_time_fixed.customer_email = customer.email
checkout_one_time_fixed.customer_metadata = {"key": "updated", "key2": "value2"}
await save_fixture(checkout_one_time_fixed)

stripe_service_mock.create_payment_intent.return_value = SimpleNamespace(
Expand All @@ -2151,15 +2198,24 @@ async def test_valid_stripe_existing_customer(
assert checkout.status == CheckoutStatus.confirmed
stripe_service_mock.update_customer.assert_called_once()

assert checkout.customer is not None
assert checkout.customer.user_metadata == {"key": "updated", "key2": "value2"}

async def test_valid_stripe_existing_customer_email(
self,
save_fixture: SaveFixture,
stripe_service_mock: MagicMock,
session: AsyncSession,
locker: Locker,
auth_subject: AuthSubject[Anonymous],
checkout_one_time_fixed: Checkout,
customer: Customer,
) -> None:
customer.user_metadata = {"key": "value"}
await save_fixture(customer)

checkout_one_time_fixed.customer_metadata = {"key": "updated", "key2": "value2"}

stripe_service_mock.create_payment_intent.return_value = SimpleNamespace(
client_secret="CLIENT_SECRET", status="succeeded"
)
Expand All @@ -2180,7 +2236,9 @@ async def test_valid_stripe_existing_customer_email(
)

assert checkout.status == CheckoutStatus.confirmed
assert checkout.customer is not None
assert checkout.customer == customer
assert checkout.customer.user_metadata == {"key": "updated", "key2": "value2"}
stripe_service_mock.update_customer.assert_called_once()

@pytest.mark.auth(AuthSubjectFixture(subject="user_second"))
Expand Down
4 changes: 4 additions & 0 deletions server/tests/fixtures/random_objects.py
Original file line number Diff line number Diff line change
Expand Up @@ -841,13 +841,15 @@ async def create_customer(
email_verified: bool = False,
name: str = "Customer",
stripe_customer_id: str = "STRIPE_CUSTOMER_ID",
user_metadata: dict[str, Any] = {},
) -> Customer:
customer = Customer(
email=email,
email_verified=email_verified,
name=name,
stripe_customer_id=stripe_customer_id,
organization=organization,
user_metadata=user_metadata,
)
await save_fixture(customer)
return customer
Expand Down Expand Up @@ -1130,6 +1132,7 @@ async def create_checkout(
expires_at: datetime | None = None,
client_secret: str | None = None,
user_metadata: dict[str, Any] = {},
customer_metadata: dict[str, Any] = {},
payment_processor_metadata: dict[str, Any] = {},
amount: int | None = None,
tax_amount: int | None = None,
Expand All @@ -1156,6 +1159,7 @@ async def create_checkout(
"CHECKOUT_CLIENT_SECRET",
),
user_metadata=user_metadata,
customer_metadata=customer_metadata,
payment_processor_metadata=payment_processor_metadata,
amount=amount,
tax_amount=tax_amount,
Expand Down

0 comments on commit 6c8d3e8

Please sign in to comment.