Functional Weave
Code in TypeScript

subscriptions.stripe-state@1.0.0

impl/python.py

8,117 bytes · the Python implementation · view raw

from dataclasses import replace
from typing import Any, Optional

from .subscriptions_stripe_state_types import SubscriptionState

_STATUSES = ("incomplete", "incomplete_expired", "trialing", "active", "past_due", "canceled", "unpaid", "paused")
_SUBSCRIPTION_EVENTS = (
    "customer.subscription.created",
    "customer.subscription.updated",
    "customer.subscription.deleted",
    "customer.subscription.paused",
    "customer.subscription.resumed",
    "customer.subscription.trial_will_end",
)
_PAID_EVENTS = ("invoice.paid", "invoice.payment_succeeded")
_FAILED_EVENT = "invoice.payment_failed"


def _field(o: Any, key: str) -> Any:
    return o.get(key) if isinstance(o, dict) else None


def _id_of(v: Any) -> Optional[str]:
    # An id Stripe sends either as a string or, when expanded, as an object with one.
    if isinstance(v, str) and v != "":
        return v
    i = _field(v, "id")
    return i if isinstance(i, str) and i != "" else None


def _is_int(v: Any) -> bool:
    return isinstance(v, int) and not isinstance(v, bool)


def _opt_int(o: Any, key: str) -> Optional[int]:
    v = _field(o, key)
    if v is None:
        return None
    if not _is_int(v):
        raise ValueError("subscription field %s must be a whole number or null" % key)
    return v


def _entitled(status: str) -> bool:
    return status in ("active", "trialing", "past_due")


def _with_invoice_effect(status: str, payment_failed: bool) -> str:
    # Where an invoice event happened after a snapshot was taken, the snapshot
    # does not know about the payment yet: keep the invoice's effect on top.
    if not payment_failed and status in ("incomplete", "past_due", "unpaid"):
        return "active"
    if payment_failed and status == "active":
        return "past_due"
    return status


def _invoice_subscription(invoice: dict) -> Optional[str]:
    direct = _id_of(invoice.get("subscription"))
    if direct is not None:
        return direct
    # API versions from 2025 move it under parent.subscription_details.
    return _id_of(_field(_field(invoice.get("parent"), "subscription_details"), "subscription"))


def apply_stripe_event(state: Optional[SubscriptionState], event: Any) -> Optional[SubscriptionState]:
    """Folds one verified Stripe webhook event into the stored state of one
    subscription. Stripe does not promise delivery order or delivery once, so
    subscription snapshots and invoice events each keep their own clock and an
    older one is ignored, a redelivered event changes nothing, and a cancelled
    subscription stays cancelled."""
    if not isinstance(event, dict):
        raise ValueError("event must be a JSON object")
    event_id = event.get("id")
    event_type = event.get("type")
    created = event.get("created")
    if not isinstance(event_id, str) or event_id == "":
        raise ValueError("event id must be a non-empty string")
    if not isinstance(event_type, str) or event_type == "":
        raise ValueError("event type must be a non-empty string")
    if not _is_int(created) or created < 0:
        raise ValueError("event created must be a whole number of seconds")
    obj = event.get("object")
    if not isinstance(obj, dict):
        raise ValueError("event object must be a JSON object")
    if state is not None and event_id == state.last_event_id:
        return state

    if event_type in _SUBSCRIPTION_EVENTS:
        sid = _id_of(obj.get("id"))
        customer = _id_of(obj.get("customer"))
        raw_status = obj.get("status")
        if sid is None or customer is None or not isinstance(raw_status, str):
            raise ValueError("subscription object needs id, customer and status")
        if raw_status not in _STATUSES:
            raise ValueError('unknown subscription status "%s"' % raw_status)
        if state is not None and sid != state.subscription_id:
            raise ValueError("event is for subscription %s, not %s" % (sid, state.subscription_id))
        snapshot_status = "canceled" if event_type == "customer.subscription.deleted" else raw_status
        # Cancelled is final in Stripe: a late snapshot never revives it.
        if state is not None and state.status == "canceled" and snapshot_status != "canceled":
            return state
        if state is not None and created < state.subscription_event_at:
            return state
        items = _field(obj.get("items"), "data")
        item = items[0] if isinstance(items, list) and items and isinstance(items[0], dict) else {}
        quantity = _opt_int(item, "quantity")
        period_start = _opt_int(obj, "current_period_start")
        if period_start is None:
            period_start = _opt_int(item, "current_period_start")
        period_end = _opt_int(obj, "current_period_end")
        if period_end is None:
            period_end = _opt_int(item, "current_period_end")
        cape = obj.get("cancel_at_period_end")
        if cape is not None and not isinstance(cape, bool):
            raise ValueError("subscription field cancel_at_period_end must be true or false")
        payment_failed = state.payment_failed if state is not None else False
        invoice_event_at = state.invoice_event_at if state is not None else 0
        status = snapshot_status
        if invoice_event_at > created:
            status = _with_invoice_effect(status, payment_failed)
        latest = _id_of(obj.get("latest_invoice"))
        if latest is None and state is not None:
            latest = state.latest_invoice_id
        return SubscriptionState(
            subscription_id=sid,
            customer_id=customer,
            status=status,
            price_id=_id_of(item.get("price")),
            quantity=1 if quantity is None else quantity,
            current_period_start=period_start,
            current_period_end=period_end,
            cancel_at_period_end=cape is True,
            cancel_at=_opt_int(obj, "cancel_at"),
            canceled_at=_opt_int(obj, "canceled_at"),
            ended_at=_opt_int(obj, "ended_at"),
            trial_end=_opt_int(obj, "trial_end"),
            latest_invoice_id=latest,
            payment_failed=payment_failed,
            entitled=_entitled(status),
            subscription_event_at=created,
            invoice_event_at=invoice_event_at,
            last_event_id=event_id,
        )

    paid = event_type in _PAID_EVENTS
    if paid or event_type == _FAILED_EVENT:
        sub = _invoice_subscription(obj)
        if sub is None:
            return state
        invoice_id = _id_of(obj.get("id"))
        if state is None:
            customer = _id_of(obj.get("customer"))
            if customer is None:
                raise ValueError("invoice object needs customer")
            status = "active" if paid else "incomplete"
            return SubscriptionState(
                subscription_id=sub,
                customer_id=customer,
                status=status,
                price_id=None,
                quantity=1,
                current_period_start=None,
                current_period_end=None,
                cancel_at_period_end=False,
                cancel_at=None,
                canceled_at=None,
                ended_at=None,
                trial_end=None,
                latest_invoice_id=invoice_id,
                payment_failed=not paid,
                entitled=_entitled(status),
                subscription_event_at=0,
                invoice_event_at=created,
                last_event_id=event_id,
            )
        if sub != state.subscription_id:
            raise ValueError("event is for subscription %s, not %s" % (sub, state.subscription_id))
        if created < state.invoice_event_at:
            return state
        status = _with_invoice_effect(state.status, not paid)
        return replace(
            state,
            status=status,
            latest_invoice_id=invoice_id if invoice_id is not None else state.latest_invoice_id,
            payment_failed=not paid,
            entitled=_entitled(status),
            invoice_event_at=created,
            last_event_id=event_id,
        )

    return state