Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): implement tickettailor import source (#69362)

Tom Owers6f4ce00dd9e5
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index b9501d3f1267..0c1794b272c8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -334,6 +334,7 @@ the row lists both.
| temporalio | gRPC (vendor SDK) | temporalio (`Client`, Rust core via `temporalio.bridge`) | ⚠️ |
| testrail | HTTP | requests | ✅ |
| thinkific | HTTP | requests | ✅ |
+| tickettailor | HTTP | requests | ✅ |
| tiktok_ads | HTTP | requests + `rest_source.RESTClient` | ✅ |
| tmdb | HTTP | requests | ✅ |
| todoist | HTTP | requests | ✅ |
@@ -697,7 +698,6 @@ doesn't conflict with concurrent PRs.
- thinkific_courses
- thrive_learning
- ticketmaster
-- tickettailor
- ticktick
- tile38
- timely
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index 4b4e8ff2d5bb..ef143a4d9acd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
@@ -3319,7 +3319,7 @@ class TickTickSourceConfig(config.Config):
@config.config
class TicketTailorSourceConfig(config.Config):
- pass
+ api_key: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tickettailor/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tickettailor/canonical_descriptions.py
new file mode 100644
index 000000000000..56b726e34c85
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tickettailor/canonical_descriptions.py
@@ -0,0 +1,209 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Descriptions sourced from the Ticket Tailor API docs (https://developers.tickettailor.com).
+# Partial coverage is fine — uncovered columns fall back to LLM enrichment.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "events": {
+ "description": "An event occurrence in your box office. Recurring events are grouped by an event series.",
+ "docs_url": "https://developers.tickettailor.com/docs/api/get-all-events",
+ "columns": {
+ "id": "A unique identifier for the event.",
+ "event_series_id": "The event series this occurrence belongs to.",
+ "name": "Name of the event.",
+ "description": "Description of the event.",
+ "status": "Status of the event.",
+ "created_at": "Timestamp when the event was created.",
+ "start": "When the event starts.",
+ "end": "When the event ends.",
+ "timezone": "TZ format timezone string for the event.",
+ "currency": "The currency the event is configured to use.",
+ "venue": "The venue the event takes place at.",
+ "online_event": "Whether or not the event is online.",
+ "private": "Whether or not the event is private.",
+ "hidden": "True if the event is set to hidden.",
+ "revenue": "Total revenue of the event.",
+ "total_orders": "Total number of orders for the event.",
+ "total_issued_tickets": "Total number of issued tickets for the event.",
+ "ticket_types": "The ticket types available for the event.",
+ "tickets_available": "Whether any ticket types are available.",
+ "url": "Event page URL.",
+ "checkout_url": "Event checkout URL.",
+ },
+ },
+ "event_series": {
+ "description": "An event series grouping one or more event occurrences.",
+ "docs_url": "https://developers.tickettailor.com/docs/api/get-all-event-series",
+ "columns": {
+ "id": "A unique identifier for the event series.",
+ "name": "Name of the event series.",
+ "description": "Description of the event series.",
+ "status": "Status of the event series.",
+ "created_at": "Date and time when the event series was created.",
+ "currency": "The currency the event series is configured to use.",
+ "timezone": "TZ format timezone string for the event series.",
+ "venue": "The venue the event series takes place at.",
+ "online_event": "Whether or not the event series is online.",
+ "private": "Whether or not the event series is private.",
+ "revenue": "Total revenue of the event series.",
+ "total_occurrences": "Total number of times the event series occurs.",
+ "total_issued_tickets": "Total number of issued tickets across the series.",
+ "upcoming_occurrences": "The number of upcoming occurrences of the event series.",
+ "next_occurrence_date": "Date and time when the next event in the series happens.",
+ "default_ticket_types": "Ticket types that are not overridden per occurrence.",
+ "url": "Event series page URL.",
+ },
+ },
+ "orders": {
+ "description": "An order placed in your box office, including buyer details and line items.",
+ "docs_url": "https://developers.tickettailor.com/docs/api/get-all-orders",
+ "columns": {
+ "id": "A unique identifier for the order.",
+ "buyer_details": "Information the buyer provided in the checkout.",
+ "created_at": "Timestamp when the order was created.",
+ "currency": "The currency of the order.",
+ "event_summary": "Summary of the event the order is for.",
+ "issued_tickets": "The tickets issued as part of the order.",
+ "sold_products": "The products sold as part of the order.",
+ "line_items": "The line items making up the order.",
+ "payment_method": "The payment method used for the order.",
+ "refund_amount": "The amount refunded on the order.",
+ "status": "The order status (completed, pending or canceled).",
+ "status_message": "Additional context for the order status.",
+ "subtotal": "Order subtotal, in the smallest currency unit.",
+ "tax": "Tax charged on the order, in the smallest currency unit.",
+ "total": "Order total, in the smallest currency unit.",
+ "total_paid": "The amount actually paid, in the smallest currency unit.",
+ "txn_id": "The payment transaction id.",
+ "referral_tag": "The tag that tracks where the sale originated.",
+ },
+ },
+ "issued_tickets": {
+ "description": "A ticket issued to an attendee, linked to its order, event and ticket type.",
+ "docs_url": "https://developers.tickettailor.com/docs/api/get-all-issued-tickets",
+ "columns": {
+ "id": "A unique identifier for the issued ticket.",
+ "order_id": "The order the ticket was issued on.",
+ "event_id": "The event the issued ticket belongs to.",
+ "event_series_id": "The event series the issued ticket belongs to.",
+ "ticket_type_id": "The ticket type of the issued ticket.",
+ "barcode": "Barcode text value.",
+ "barcode_url": "URL to the barcode image.",
+ "qr_code_url": "URL to the QR code image.",
+ "checked_in": "Whether or not the issued ticket is checked in.",
+ "created_at": "Timestamp when the issued ticket was created.",
+ "updated_at": "Timestamp when the issued ticket was last updated.",
+ "voided_at": "Timestamp when the issued ticket was voided.",
+ "email": "The order email address.",
+ "full_name": "Full name of the attendee.",
+ "first_name": "First name of the attendee.",
+ "last_name": "Last name of the attendee.",
+ "status": "Status of the issued ticket.",
+ "custom_questions": "Buyer-provided answers to custom checkout questions.",
+ "listed_price": "List price of the ticket type at the time of purchase.",
+ "listed_currency": "List currency of the ticket type at the time of purchase.",
+ },
+ },
+ "check_ins": {
+ "description": "A check-in (or check-out) of an issued ticket at an event.",
+ "docs_url": "https://developers.tickettailor.com/docs/api/get-check-in-list",
+ "columns": {
+ "id": "A unique identifier for the check-in.",
+ "check_in_at": "Timestamp of when the ticket was checked in or out.",
+ "created_at": "Check-in creation timestamp.",
+ "event_id": "The event the check-in belongs to.",
+ "issued_ticket_id": "The issued ticket that was checked in or out.",
+ "quantity": "1 for a check-in, -1 for a check-out.",
+ },
+ },
+ "discounts": {
+ "description": "A discount code configured in your box office.",
+ "docs_url": "https://developers.tickettailor.com/docs/api/get-discount-list",
+ "columns": {
+ "id": "A unique identifier for the discount.",
+ "code": "The discount code.",
+ "name": "A descriptive name given to the discount.",
+ "type": "Type of discount — either a fixed amount or a percentage.",
+ "price": "Discounted price in the smallest currency unit. Can be null.",
+ "price_percent": "Percentage discount on the price. Can be null.",
+ "expires": "The discount code's expiry date.",
+ "max_redemptions": "The maximum number of times this discount can be used.",
+ "times_redeemed": "The number of times the discount was used.",
+ "ticket_types": "The ticket types the discount applies to.",
+ "products": "The products the discount applies to.",
+ },
+ },
+ "products": {
+ "description": "A product (add-on) sold alongside tickets in your box office.",
+ "docs_url": "https://developers.tickettailor.com/docs/api/get-product-list",
+ "columns": {
+ "id": "A unique identifier for the product.",
+ "name": "Name of the product.",
+ "description": "Description of the product.",
+ "status": "Status of the product.",
+ "created_at": "Date and time when the product was created.",
+ "updated_at": "Date and time when the product was last updated.",
+ "currency": "The currency the product is configured to use.",
+ "price": "Price in the smallest currency unit. Can be null.",
+ "quantity": "Number available for purchase across all event occurrences.",
+ "issued_count": "Number of sold products.",
+ "event_series_ids": "The event series the product is linked to.",
+ "linked_to_all_event_series": "Whether the product is linked to all event series.",
+ },
+ },
+ "vouchers": {
+ "description": "A voucher (e.g. gift card) configured in your box office.",
+ "docs_url": "https://developers.tickettailor.com/docs/api/get-voucher-list",
+ "columns": {
+ "id": "A unique identifier for the voucher.",
+ "name": "A descriptive name given to the voucher.",
+ "type": "Type of voucher.",
+ "value": "The value of the voucher in the smallest currency unit.",
+ "expiry": "The voucher's expiry date.",
+ "total_codes": "Total number of voucher codes belonging to the voucher.",
+ "available_codes": "The number of unused voucher codes belonging to the voucher.",
+ "partial_redemption": "Whether the voucher can be partially redeemed.",
+ "usable_on_any_event": "Whether the voucher can be used on any event.",
+ "event_series_ids": "The event series the voucher applies to.",
+ },
+ },
+ "issued_memberships": {
+ "description": "A membership issued to a member, with its validity window and redemptions.",
+ "docs_url": "https://developers.tickettailor.com/docs/api/get-all-issued-memberships",
+ "columns": {
+ "id": "A unique identifier for the issued membership.",
+ "code": "Unique membership code for identification and redemption.",
+ "membership_type_id": "The membership type this membership was issued from.",
+ "membership_type_name": "Name of the membership type.",
+ "email": "Email address of the member.",
+ "full_name": "Full name of the member.",
+ "first_name": "First name of the member.",
+ "last_name": "Last name of the member.",
+ "is_valid": "Whether the membership is currently valid (not expired and not voided).",
+ "issue_date": "Date and time when the membership was issued.",
+ "valid_from": "Date and time when the membership becomes valid.",
+ "valid_to": "Date and time when the membership expires.",
+ "voided_at": "Date and time when the membership was voided. Null if not voided.",
+ "redemptions": "Number of times this membership has been redeemed.",
+ "max_redemptions": "Maximum number of redemptions allowed. Null means unlimited.",
+ "benefits": "The benefits associated with this membership.",
+ },
+ },
+ "membership_types": {
+ "description": "A membership type that memberships are issued from.",
+ "docs_url": "https://developers.tickettailor.com/docs/api/get-all-membership-types",
+ "columns": {
+ "id": "A unique identifier for the membership type.",
+ "name": "Name of the membership type.",
+ "conditions_and_benefits": "The conditions and benefits for this membership type.",
+ "max_redemptions": "Maximum number of redemptions allowed per issued membership. Null means unlimited.",
+ "photo_required": "Whether a photo is required when issuing memberships of this type.",
+ "valid_from_type": "Type of valid-from date: 'fixed' uses valid_from_date, 'relative' uses the issue date.",
+ "valid_from_date": "Fixed date when memberships of this type become valid. Null if relative.",
+ "valid_to_type": "Type of valid-to date: 'fixed' uses valid_to_date, 'relative' uses valid_to_relative_days.",
+ "valid_to_date": "Fixed date when memberships of this type expire. Null if relative.",
+ "valid_to_relative_days": "Number of days the membership is valid for from the issue date. Null if fixed.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tickettailor/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tickettailor/settings.py
new file mode 100644
index 000000000000..91e0f29adf8c
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tickettailor/settings.py
@@ -0,0 +1,34 @@
+from dataclasses import dataclass, field
+
+
+@dataclass
+class TicketTailorEndpointConfig:
+ name: str
+ path: str
+ # Ticket Tailor object ids are prefixed and globally unique within a box office
+ # (e.g. "or_123", "it_456"), so `id` is a safe primary key.
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+
+
+# Ticket Tailor v1 top-level list endpoints. All are full refresh only: list endpoints paginate
+# newest-first by object id (`starting_after` cursor), and while some accept a server-side
+# `created_at` filter, created-at windows never re-surface rows that were updated in place
+# (orders and issued tickets mutate after creation). Ticket Tailor documents webhooks — which
+# must be configured manually in its dashboard — as the only mechanism for update delivery, so
+# there is no reliable incremental cursor to advance.
+TICKET_TAILOR_ENDPOINTS: dict[str, TicketTailorEndpointConfig] = {
+ "events": TicketTailorEndpointConfig(name="events", path="/v1/events"),
+ "event_series": TicketTailorEndpointConfig(name="event_series", path="/v1/event_series"),
+ "orders": TicketTailorEndpointConfig(name="orders", path="/v1/orders"),
+ "issued_tickets": TicketTailorEndpointConfig(name="issued_tickets", path="/v1/issued_tickets"),
+ "check_ins": TicketTailorEndpointConfig(name="check_ins", path="/v1/check_ins"),
+ "discounts": TicketTailorEndpointConfig(name="discounts", path="/v1/discounts"),
+ "products": TicketTailorEndpointConfig(name="products", path="/v1/products"),
+ "vouchers": TicketTailorEndpointConfig(name="vouchers", path="/v1/vouchers"),
+ "issued_memberships": TicketTailorEndpointConfig(name="issued_memberships", path="/v1/issued_memberships"),
+ "membership_types": TicketTailorEndpointConfig(name="membership_types", path="/v1/membership_types"),
+}
+
+ENDPOINTS = tuple(TICKET_TAILOR_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[dict[str, str]]] = {}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tickettailor/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tickettailor/source.py
index 276982e5da68..f8ff41cb3703 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tickettailor/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tickettailor/source.py
@@ -1,19 +1,42 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import TicketTailorSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.tickettailor.settings import (
+ ENDPOINTS,
+ TICKET_TAILOR_ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.tickettailor.tickettailor import (
+ TicketTailorResumeConfig,
+ tickettailor_source,
+ validate_credentials,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class TicketTailorSource(SimpleSource[TicketTailorSourceConfig]):
+class TicketTailorSource(ResumableSource[TicketTailorSourceConfig, TicketTailorResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.TICKETTAILOR
@@ -23,8 +46,91 @@ class TicketTailorSource(SimpleSource[TicketTailorSourceConfig]):
return SourceConfig(
name=SchemaExternalDataSourceType.TICKET_TAILOR,
category=DataWarehouseSourceCategory.E_COMMERCE,
- label="TicketTailor",
+ label="Ticket Tailor",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Ticket Tailor API key to pull your event ticketing data into the PostHog Data warehouse.
+
+You can create an API key under **Settings → API** in your [Ticket Tailor](https://www.tickettailor.com) box office. API keys are scoped to a single box office — connect one source per box office you want to sync.
+""",
iconPath="/static/services/tickettailor.png",
- fields=cast(list[FieldType], []),
+ docsUrl="https://posthog.com/docs/cdp/sources/tickettailor",
+ keywords=["tickets", "ticketing", "events", "box office"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
unreleasedSource=True,
)
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.tickettailor.canonical_descriptions import ( # noqa: PLC0415
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ # Ticket Tailor answers invalid or deleted API keys with 403 (it reserves 401 for
+ # malformed auth headers) — both are permanent credential failures.
+ return {
+ "401 Client Error: Unauthorized for url: https://api.tickettailor.com": "Your Ticket Tailor API key is invalid. Generate a new key under Settings → API in your box office, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.tickettailor.com": "Your Ticket Tailor API key is invalid, deleted, or does not have access to this data. Check the key under Settings → API in your box office, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: TicketTailorSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # Every endpoint is full refresh only — see settings.py for why there is no reliable
+ # incremental cursor to advance.
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=[],
+ )
+ for endpoint in ENDPOINTS
+ ]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: TicketTailorSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ # The API key is box-office-wide, so a single probe validates access to every schema.
+ return validate_credentials(config.api_key)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[TicketTailorResumeConfig]:
+ return ResumableSourceManager[TicketTailorResumeConfig](inputs, TicketTailorResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: TicketTailorSourceConfig,
+ resumable_source_manager: ResumableSourceManager[TicketTailorResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ if inputs.schema_name not in TICKET_TAILOR_ENDPOINTS:
+ raise ValueError(f"Unknown Ticket Tailor schema '{inputs.schema_name}'")
+
+ return tickettailor_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tickettailor/tests/test_tickettailor.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tickettailor/tests/test_tickettailor.py
new file mode 100644
index 000000000000..33deee8f35a3
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tickettailor/tests/test_tickettailor.py
@@ -0,0 +1,261 @@
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.tickettailor import tickettailor
+from products.warehouse_sources.backend.temporal.data_imports.sources.tickettailor.settings import (
+ ENDPOINTS,
+ TICKET_TAILOR_ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.tickettailor.tickettailor import (
+ PAGE_SIZE,
+ TicketTailorResumeConfig,
+ TicketTailorRetryableError,
+ _make_session,
+ check_access,
+ get_rows,
+ tickettailor_source,
+ validate_credentials,
+)
+
+# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.
+_fetch_page_unwrapped = tickettailor._fetch_page.__wrapped__ # type: ignore[attr-defined]
+
+
+class _FakeResumableManager:
+ def __init__(self, state: TicketTailorResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[TicketTailorResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> TicketTailorResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: TicketTailorResumeConfig) -> None:
+ self.saved.append(data)
+
+
+class TestMakeSession:
+ @patch(f"{tickettailor.__name__}.make_tracked_session")
+ def test_uses_basic_auth_with_key_as_username(self, mock_make_session: MagicMock) -> None:
+ session = MagicMock()
+ mock_make_session.return_value = session
+ _make_session("tt-key")
+ # Ticket Tailor authenticates via HTTP Basic with the key as the username and no password —
+ # switching to e.g. a Bearer header would break every sync.
+ assert session.auth == ("tt-key", "")
+ assert mock_make_session.call_args.kwargs["redact_values"] == ("tt-key",)
+
+
+class TestGetRows:
+ @staticmethod
+ def _collect(
+ manager: _FakeResumableManager,
+ monkeypatch: Any,
+ pages: dict[str | None, tuple[list[dict], bool]],
+ endpoint: str = "orders",
+ ) -> list[dict]:
+ def fake_fetch(session: Any, path: str, cursor: str | None, limit: int, logger: Any) -> tuple[list[dict], bool]:
+ return pages[cursor]
+
+ monkeypatch.setattr(tickettailor, "_fetch_page", fake_fetch)
+ monkeypatch.setattr(tickettailor, "make_tracked_session", lambda **kwargs: MagicMock())
+
+ rows: list[dict] = []
+ for batch in get_rows(
+ api_key="tt-key",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ ):
+ rows.extend(batch)
+ return rows
+
+ def test_single_page_without_next_link_yields_and_stops(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ rows = self._collect(manager, monkeypatch, {None: ([{"id": "or_1"}, {"id": "or_2"}], False)})
+ assert rows == [{"id": "or_1"}, {"id": "or_2"}]
+ # No next link, so we stop without persisting resume state.
+ assert manager.saved == []
+
+ def test_follows_cursor_pagination_until_no_next_link(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ first_page = [{"id": f"or_{i}"} for i in range(PAGE_SIZE)]
+ pages: dict[str | None, tuple[list[dict], bool]] = {
+ None: (first_page, True),
+ "or_99": ([{"id": "or_100"}], False),
+ }
+ rows = self._collect(manager, monkeypatch, pages)
+ assert len(rows) == PAGE_SIZE + 1
+ # State is saved after the first page (cursor advances to the last id), then we stop.
+ assert [s.cursor for s in manager.saved] == ["or_99"]
+
+ def test_resumes_from_saved_cursor(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager(TicketTailorResumeConfig(cursor="or_50"))
+ # The initial (cursor=None) page must never be fetched on resume.
+ rows = self._collect(manager, monkeypatch, {"or_50": ([{"id": "or_51"}], False)})
+ assert rows == [{"id": "or_51"}]
+
+ def test_empty_first_page_yields_nothing(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ rows = self._collect(manager, monkeypatch, {None: ([], False)})
+ assert rows == []
+ assert manager.saved == []
+
+
+class TestFetchPage:
+ def _session_returning(self, status_code: int, body: Any = None) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.ok = status_code < 400
+ response.json.return_value = body if body is not None else {"data": [], "links": {"next": None}}
+ response.text = ""
+ response.raise_for_status.side_effect = (
+ requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None
+ )
+ session = MagicMock()
+ session.get.return_value = response
+ return session
+
+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])
+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:
+ session = self._session_returning(status)
+ with pytest.raises(TicketTailorRetryableError):
+ _fetch_page_unwrapped(session, "/v1/orders", None, PAGE_SIZE, MagicMock())
+
+ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])
+ def test_client_errors_raise_for_status(self, _name: str, status: int) -> None:
+ session = self._session_returning(status)
+ with pytest.raises(requests.HTTPError):
+ _fetch_page_unwrapped(session, "/v1/orders", None, PAGE_SIZE, MagicMock())
+
+ @parameterized.expand(
+ [
+ ("next_link_present", {"next": "/v1/orders?starting_after=or_120", "previous": None}, True),
+ ("next_link_null", {"next": None, "previous": None}, False),
+ ("links_missing", None, False),
+ ]
+ )
+ def test_has_more_follows_next_link(self, _name: str, links: dict | None, expected_has_more: bool) -> None:
+ body: dict[str, Any] = {"data": [{"id": "or_1"}]}
+ if links is not None:
+ body["links"] = links
+ session = self._session_returning(200, body)
+ items, has_more = _fetch_page_unwrapped(session, "/v1/orders", None, PAGE_SIZE, MagicMock())
+ assert items == [{"id": "or_1"}]
+ assert has_more is expected_has_more
+
+ def test_non_dict_body_is_retryable(self) -> None:
+ session = self._session_returning(200, [{"id": "or_1"}])
+ with pytest.raises(TicketTailorRetryableError):
+ _fetch_page_unwrapped(session, "/v1/orders", None, PAGE_SIZE, MagicMock())
+
+ def test_missing_data_key_is_retryable(self) -> None:
+ session = self._session_returning(200, {"links": {"next": None}})
+ with pytest.raises(TicketTailorRetryableError):
+ _fetch_page_unwrapped(session, "/v1/orders", None, PAGE_SIZE, MagicMock())
+
+ def test_first_page_uses_limit_without_cursor(self) -> None:
+ session = self._session_returning(200)
+ _fetch_page_unwrapped(session, "/v1/events", None, PAGE_SIZE, MagicMock())
+ _, kwargs = session.get.call_args
+ assert kwargs["params"] == {"limit": PAGE_SIZE}
+
+ def test_subsequent_page_sends_starting_after_cursor(self) -> None:
+ session = self._session_returning(200)
+ _fetch_page_unwrapped(session, "/v1/events", "ev_42", PAGE_SIZE, MagicMock())
+ _, kwargs = session.get.call_args
+ assert kwargs["params"] == {"limit": PAGE_SIZE, "starting_after": "ev_42"}
+
+
+class TestCheckAccess:
+ @staticmethod
+ def _session(response: Any) -> MagicMock:
+ session = MagicMock()
+ if isinstance(response, Exception):
+ session.get.side_effect = response
+ else:
+ session.get.return_value = response
+ return session
+
+ @parameterized.expand(
+ [
+ ("ok", 200, True, 200, None),
+ ("unauthorized", 401, False, 401, None),
+ # Ticket Tailor answers invalid/deleted keys with 403, not 401.
+ ("forbidden", 403, False, 403, None),
+ ("server_error", 500, False, 500, "Ticket Tailor returned HTTP 500"),
+ ]
+ )
+ @patch(f"{tickettailor.__name__}.make_tracked_session")
+ def test_status_mapping(
+ self,
+ _name: str,
+ status: int,
+ ok: bool,
+ expected_status: int,
+ expected_message: str | None,
+ mock_session: MagicMock,
+ ) -> None:
+ response = MagicMock()
+ response.status_code = status
+ response.ok = ok
+ mock_session.return_value = self._session(response)
+ assert check_access("tt-key") == (expected_status, expected_message)
+
+ @patch(f"{tickettailor.__name__}.make_tracked_session")
+ def test_connection_error_maps_to_zero(self, mock_session: MagicMock) -> None:
+ mock_session.return_value = self._session(requests.ConnectionError("boom"))
+ status, message = check_access("tt-key")
+ assert status == 0
+ assert message is not None and "boom" in message
+
+ @parameterized.expand(
+ [
+ ("ok", 200, True, None),
+ ("unauthorized", 401, False, "Invalid Ticket Tailor API key"),
+ ("forbidden", 403, False, "Invalid Ticket Tailor API key"),
+ ("server_error", 500, False, "Ticket Tailor returned HTTP 500"),
+ ]
+ )
+ @patch(f"{tickettailor.__name__}.make_tracked_session")
+ def test_validate_credentials(
+ self,
+ _name: str,
+ status: int,
+ expected_valid: bool,
+ expected_message: str | None,
+ mock_session: MagicMock,
+ ) -> None:
+ response = MagicMock()
+ response.status_code = status
+ response.ok = status < 400
+ mock_session.return_value = self._session(response)
+ assert validate_credentials("tt-key") == (expected_valid, expected_message)
+
+
+class TestTicketTailorSourceResponse:
+ @parameterized.expand([(e,) for e in ENDPOINTS])
+ def test_source_response_shape(self, endpoint: str) -> None:
+ response = tickettailor_source(
+ api_key="tt-key",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == ["id"]
+ # Lists come back newest-first; declaring asc would corrupt a future incremental watermark.
+ assert response.sort_mode == "desc"
+ # No stable creation timestamp is guaranteed across every object, so we don't partition.
+ assert response.partition_mode is None
+
+ def test_every_endpoint_uses_id_primary_key(self) -> None:
+ assert all(config.primary_keys == ["id"] for config in TICKET_TAILOR_ENDPOINTS.values())
+ assert set(TICKET_TAILOR_ENDPOINTS) == set(ENDPOINTS)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tickettailor/tests/test_tickettailor_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tickettailor/tests/test_tickettailor_source.py
new file mode 100644
index 000000000000..8dbf675f7a7b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tickettailor/tests/test_tickettailor_source.py
@@ -0,0 +1,138 @@
+import pytest
+from unittest import mock
+
+from parameterized import parameterized
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import TicketTailorSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.tickettailor.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.tickettailor.source import TicketTailorSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.tickettailor.tickettailor import (
+ TicketTailorResumeConfig,
+)
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestTicketTailorSource:
+ def setup_method(self) -> None:
+ self.source = TicketTailorSource()
+ self.team_id = 123
+ self.config = TicketTailorSourceConfig(api_key="tt-key")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.TICKETTAILOR
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+ assert config.name.value == "TicketTailor"
+ assert config.label == "Ticket Tailor"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/tickettailor"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["api_key"]
+
+ def test_api_key_field_is_secret_password(self) -> None:
+ config = self.source.get_source_config
+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+ assert field.secret is True
+ assert field.required is True
+
+ def test_no_connection_host_fields(self) -> None:
+ # The only field is the secret API key; the base URL is hardcoded, so there is no non-secret
+ # field an editor could retarget to reuse a preserved key against another server.
+ assert self.source.connection_host_fields == []
+
+ def test_lists_tables_without_credentials(self) -> None:
+ assert self.source.lists_tables_without_credentials is True
+
+ def test_get_schemas_covers_all_endpoints_as_full_refresh(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ assert all(s.supports_incremental is False for s in schemas)
+ assert all(s.supports_append is False for s in schemas)
+ assert all(s.incremental_fields == [] for s in schemas)
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["orders"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "orders"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ def test_documented_tables_render_for_public_docs(self) -> None:
+ tables = self.source.get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+ assert all("Full refresh" in t["sync_methods"] for t in tables)
+
+ @parameterized.expand(
+ [
+ (
+ "unauthorized",
+ "401 Client Error: Unauthorized for url: https://api.tickettailor.com/v1/orders?limit=100",
+ ),
+ # Ticket Tailor answers invalid/deleted keys with 403.
+ ("forbidden", "403 Client Error: Forbidden for url: https://api.tickettailor.com/v1/events?limit=100"),
+ ]
+ )
+ def test_non_retryable_errors_match_auth_failures(self, _name: str, observed_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable)
+
+ @parameterized.expand(
+ [
+ (
+ "server_error",
+ "500 Server Error: Internal Server Error for url: https://api.tickettailor.com/v1/orders",
+ ),
+ (
+ "rate_limited",
+ "429 Client Error: Too Many Requests for url: https://api.tickettailor.com/v1/events",
+ ),
+ ]
+ )
+ def test_non_retryable_errors_ignore_transient(self, _name: str, unrelated_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert not any(key in unrelated_error for key in non_retryable)
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.tickettailor.source.validate_credentials"
+ )
+ def test_validate_credentials_delegates_with_api_key(self, mock_validate: mock.MagicMock) -> None:
+ # The status-to-message mapping lives in tickettailor.validate_credentials; here we only
+ # assert the source probes with the configured key and returns the delegate's verdict.
+ mock_validate.return_value = (False, "Invalid Ticket Tailor API key")
+ result = self.source.validate_credentials(self.config, self.team_id)
+ mock_validate.assert_called_once_with("tt-key")
+ assert result == (False, "Invalid Ticket Tailor API key")
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is TicketTailorResumeConfig
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.tickettailor.source.tickettailor_source"
+ )
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "orders"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_source.assert_called_once()
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["api_key"] == "tt-key"
+ assert kwargs["endpoint"] == "orders"
+ assert kwargs["resumable_source_manager"] is manager
+
+ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "not_a_table"
+ with pytest.raises(ValueError, match="Unknown Ticket Tailor schema 'not_a_table'"):
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tickettailor/tickettailor.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tickettailor/tickettailor.py
new file mode 100644
index 000000000000..e60e0acdf608
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tickettailor/tickettailor.py
@@ -0,0 +1,177 @@
+import dataclasses
+from collections.abc import Iterator
+from typing import Any, Optional
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.tickettailor.settings import (
+ TICKET_TAILOR_ENDPOINTS,
+)
+
+TICKET_TAILOR_BASE_URL = "https://api.tickettailor.com"
+# List endpoints cap `limit` at 100; the largest page minimises round trips against the
+# 5000 requests / 30 minutes rate limit.
+PAGE_SIZE = 100
+REQUEST_TIMEOUT_SECONDS = 60
+# Cheap endpoint used to confirm an API key is genuine. Keys are scoped to a whole box office,
+# so one probe validates access to every list endpoint.
+DEFAULT_PROBE_PATH = "/v1/events"
+
+
+class TicketTailorRetryableError(Exception):
+ pass
+
+
+class TicketTailorResumeConfig:
+ # Cursor for the next page: Ticket Tailor paginates by passing the last item's object id as
+ # `starting_after` (lists are returned newest-first). A crashed sync resumes from the page
+ # after the last one yielded; merge dedupes on `id`. `None` means start from the first page.
+ cursor: str | None = None
+
+
+def _make_session(api_key: str) -> requests.Session:
+ # Ticket Tailor authenticates via HTTP Basic with the API key as the username and no password.
+ session = make_tracked_session(headers={"Accept": "application/json"}, redact_values=(api_key,))
+ session.auth = (api_key, "")
+ return session
+
+
+@retry(
+ retry=retry_if_exception_type((TicketTailorRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session,
+ path: str,
+ cursor: str | None,
+ limit: int,
+ logger: FilteringBoundLogger,
+) -> tuple[list[dict[str, Any]], bool]:
+ params: dict[str, Any] = {"limit": limit}
+ if cursor is not None:
+ params["starting_after"] = cursor
+
+ response = session.get(
+ f"{TICKET_TAILOR_BASE_URL}{path}",
+ params=params,
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+
+ if response.status_code == 429 or response.status_code >= 500:
+ logger.warning("Ticket Tailor API error (retryable)", status=response.status_code, path=path)
+ raise TicketTailorRetryableError(
+ f"Ticket Tailor API error (retryable): status={response.status_code}, path={path}"
+ )
+
+ if not response.ok:
+ logger.error("Ticket Tailor API error", status=response.status_code, body=response.text, path=path)
+ response.raise_for_status()
+
+ body = response.json()
+ # List endpoints wrap records in {"data": [...], "links": {"next": ..., "previous": ...}},
+ # where `links.next` is null on the last page.
+ if not isinstance(body, dict) or not isinstance(body.get("data"), list):
+ logger.warning("Ticket Tailor returned an unexpected payload", body_type=type(body).__name__, path=path)
+ raise TicketTailorRetryableError(
+ f"Ticket Tailor returned an unexpected payload for {path}: {type(body).__name__}"
+ )
+
+ items: list[dict[str, Any]] = body["data"]
+ links = body.get("links") or {}
+ has_more = bool(links.get("next")) if isinstance(links, dict) else False
+ return items, has_more
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[TicketTailorResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ config = TICKET_TAILOR_ENDPOINTS[endpoint]
+ session = _make_session(api_key)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ cursor = resume.cursor if resume else None
+ if resume and resume.cursor is not None:
+ logger.debug("Ticket Tailor: resuming from saved cursor", endpoint=endpoint, cursor=cursor)
+
+ while True:
+ items, has_more = _fetch_page(session, config.path, cursor, PAGE_SIZE, logger)
+ if items:
+ yield items
+
+ if not has_more or not items:
+ break
+
+ # Cursor pagination advances by the last item's id — there is no numeric offset.
+ cursor = items[-1]["id"]
+ # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages are
+ # persisted); merge dedupes the re-pulled page on the primary key.
+ resumable_source_manager.save_state(TicketTailorResumeConfig(cursor=cursor))
+
+
+def tickettailor_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[TicketTailorResumeConfig],
+) -> SourceResponse:
+ config = TICKET_TAILOR_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=config.primary_keys,
+ # Not every object carries a stable creation timestamp (discounts, vouchers,
+ # membership types), so we don't partition.
+ partition_count=1,
+ partition_size=1,
+ # Lists are returned newest-first by object id. Inert while every endpoint is full
+ # refresh, but declared so a future incremental cursor can't corrupt its watermark.
+ sort_mode="desc",
+ )
+
+
+def check_access(api_key: str, path: str = DEFAULT_PROBE_PATH) -> tuple[int, Optional[str]]:
+ """Probe a single endpoint to validate the API key.
+
+ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a
+ connection problem, other HTTP status otherwise. Ticket Tailor answers unauthenticated and
+ invalid-key requests with 403.
+ """
+ session = _make_session(api_key)
+ try:
+ response = session.get(f"{TICKET_TAILOR_BASE_URL}{path}", params={"limit": 1}, timeout=15)
+ except Exception as e:
+ return 0, f"Could not connect to Ticket Tailor: {e}"
+
+ if response.status_code in (401, 403):
+ return response.status_code, None
+
+ if not response.ok:
+ return response.status_code, f"Ticket Tailor returned HTTP {response.status_code}"
+
+ return 200, None
+
+
+def validate_credentials(api_key: str) -> tuple[bool, str | None]:
+ status, message = check_access(api_key)
+ if status == 200:
+ return True, None
+ if status in (401, 403):
+ return False, "Invalid Ticket Tailor API key"
+ return False, message or "Could not validate Ticket Tailor API key"