: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement pretix import source (#69376)
Tom Owersd8a341a6f485
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 55c8cecea01a..b892815bf6a2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -283,6 +283,7 @@ the row lists both.| plaid | HTTP | requests | ✅ || postgres | DB protocol | psycopg | ➖ || postmark | HTTP | requests | ✅ |+| pretix | HTTP | requests | ✅ || productboard | HTTP | requests | ✅ || pylon | HTTP | requests | ✅ || qualaroo | HTTP | requests | ✅ |@@ -645,7 +646,6 @@ doesn't conflict with concurrent PRs.- polygon- poplar- prestashop-- pretix- primetric- printify- productivediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 7d3653468f25..6fd4b65e2254 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@@ -2721,7 +2721,9 @@ class PrestaShopSourceConfig(config.Config):@config.configclass PretixSourceConfig(config.Config):- pass+ organizer: str+ api_token: str+ base_url: str | None = None@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pretix/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pretix/canonical_descriptions.pynew file mode 100644index 000000000000..1b13d75363a8--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pretix/canonical_descriptions.py@@ -0,0 +1,224 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "events": {+ "description": "An event or event series run by the organizer, such as a conference or a concert.",+ "docs_url": "https://docs.pretix.eu/en/latest/api/resources/events.html",+ "columns": {+ "slug": "A short form of the event name, used in URLs. Unique within the organizer.",+ "name": "The event's full name in every configured language.",+ "live": "Whether the ticket shop is publicly available.",+ "testmode": "Whether the ticket shop is in test mode.",+ "currency": "The currency this event is handled in.",+ "date_from": "The event's start date and time.",+ "date_to": "The event's end date and time, or null.",+ "is_public": "Whether the event shows up in listings.",+ "presale_start": "The date at which the ticket shop opens, or null.",+ "presale_end": "The date at which the ticket shop closes, or null.",+ "location": "The event location in every configured language.",+ "has_subevents": "Whether the event is an event series with sub-events (dates).",+ "timezone": "The event's timezone.",+ "meta_data": "Custom meta data values configured for the event.",+ },+ },+ "orders": {+ "description": "A ticket order placed in one of the organizer's events, including its positions (individual tickets), fees, payments, and refunds.",+ "docs_url": "https://docs.pretix.eu/en/latest/api/resources/orders.html",+ "columns": {+ "code": "The order code, unique within its event.",+ "event": "The slug of the event this order belongs to.",+ "status": "Order status: n (pending), p (paid), e (expired), or c (canceled).",+ "testmode": "Whether the order was created in test mode.",+ "email": "The customer email address.",+ "datetime": "The date and time the order was placed.",+ "expires": "The date and time the order will expire if unpaid.",+ "last_modified": "The last date and time the order changed.",+ "total": "The total value of the order, including fees.",+ "positions": "The individual ticket positions of the order, including item, price, and attendee data.",+ "fees": "Additional fees charged on the order, such as payment or shipping fees.",+ "payments": "The payment processes attached to the order.",+ "refunds": "The refund processes attached to the order.",+ "invoice_address": "The invoice address attached to the order.",+ "sales_channel": "The sales channel the order was created through.",+ "customer": "The identifier of the customer account this order belongs to, or null.",+ },+ },+ "invoices": {+ "description": "An invoice or invoice cancellation issued for an order in one of the organizer's events.",+ "docs_url": "https://docs.pretix.eu/en/latest/api/resources/invoices.html",+ "columns": {+ "number": "The invoice number, with its event-based prefix.",+ "event": "The slug of the event this invoice belongs to.",+ "order": "The code of the order this invoice belongs to.",+ "is_cancellation": "Whether this invoice is the cancellation of another invoice.",+ "refers": "The number of the invoice this invoice refers to (for cancellations), or null.",+ "date": "The invoice date.",+ "locale": "The language the invoice is rendered in.",+ "lines": "The individual line items of the invoice, with descriptions, tax rates, and gross values.",+ "invoice_from_name": "The name of the invoice sender.",+ "invoice_to": "The full address block of the invoice recipient.",+ "foreign_currency_display": "A currency the invoice total is additionally displayed in, or null.",+ },+ },+ "customers": {+ "description": "A customer account registered with the organizer, which orders can be attached to.",+ "docs_url": "https://docs.pretix.eu/en/latest/api/resources/customers.html",+ "columns": {+ "identifier": "Internal ID of the customer, unique within the organizer.",+ "external_identifier": "An external ID for the customer, for example from an SSO provider.",+ "email": "The customer's email address.",+ "name": "The customer's full name.",+ "is_active": "Whether the account is active.",+ "is_verified": "Whether the email address has been verified.",+ "date_joined": "The registration date of the account.",+ "last_modified": "The last date and time the account changed.",+ "last_login": "The date and time of the customer's last login, or null.",+ "locale": "The customer's preferred language.",+ },+ },+ "gift_cards": {+ "description": "A gift card issued by the organizer that can be used to pay for orders.",+ "docs_url": "https://docs.pretix.eu/en/latest/api/resources/giftcards.html",+ "columns": {+ "id": "Internal ID of the gift card.",+ "secret": "The gift card code used to redeem it.",+ "value": "The current remaining value of the gift card.",+ "currency": "The currency of the gift card.",+ "testmode": "Whether the gift card was created in test mode.",+ "expires": "The expiry date of the gift card, or null.",+ "issuer": "The slug of the organizer that issued the gift card.",+ },+ },+ "subevents": {+ "description": "A date in an event series, carrying its own schedule, prices, and quotas.",+ "docs_url": "https://docs.pretix.eu/en/latest/api/resources/subevents.html",+ "columns": {+ "id": "Internal ID of the sub-event.",+ "event_slug": "The slug of the event series this sub-event belongs to (added by PostHog during sync).",+ "name": "The sub-event's full name in every configured language.",+ "active": "Whether tickets for this date can be bought.",+ "date_from": "The sub-event's start date and time.",+ "date_to": "The sub-event's end date and time, or null.",+ "location": "The sub-event location, or null.",+ "item_price_overrides": "Prices that differ from the base event's item prices.",+ },+ },+ "items": {+ "description": "A product that can be sold for an event, such as a ticket type or merchandise, including its variations.",+ "docs_url": "https://docs.pretix.eu/en/latest/api/resources/items.html",+ "columns": {+ "id": "Internal ID of the item.",+ "event_slug": "The slug of the event this item belongs to (added by PostHog during sync).",+ "name": "The item's name in every configured language.",+ "internal_name": "An optional name used only internally.",+ "default_price": "The item price applied if no variation or voucher changes it.",+ "free_price": "Whether customers can pay more than the default price.",+ "tax_rate": "The tax rate applied to the item.",+ "admission": "Whether the item grants admission to the event.",+ "active": "Whether the item is on sale.",+ "category": "The ID of the category this item belongs to, or null.",+ "variations": "The item's variations, each with its own price and availability.",+ },+ },+ "categories": {+ "description": "A product category used to group an event's items in the shop.",+ "docs_url": "https://docs.pretix.eu/en/latest/api/resources/categories.html",+ "columns": {+ "id": "Internal ID of the category.",+ "event_slug": "The slug of the event this category belongs to (added by PostHog during sync).",+ "name": "The category's name in every configured language.",+ "internal_name": "An optional name used only internally.",+ "description": "A public description of the category.",+ "position": "An integer used for sorting categories in the shop.",+ "is_addon": "Whether items in this category are sold only as add-ons to other items.",+ },+ },+ "questions": {+ "description": "A question asked of ticket buyers during checkout, such as dietary requirements or T-shirt size.",+ "docs_url": "https://docs.pretix.eu/en/latest/api/resources/questions.html",+ "columns": {+ "id": "Internal ID of the question.",+ "event_slug": "The slug of the event this question belongs to (added by PostHog during sync).",+ "question": "The question text in every configured language.",+ "type": "The question's field type, for example S (string), N (number), or C (choice).",+ "required": "Whether an answer is required during checkout.",+ "items": "The IDs of the items this question is asked for.",+ "options": "The answer options for choice questions.",+ "identifier": "An arbitrary string that can be used for matching with other sources.",+ },+ },+ "quotas": {+ "description": "A quota limiting how many of an event's items can be sold.",+ "docs_url": "https://docs.pretix.eu/en/latest/api/resources/quotas.html",+ "columns": {+ "id": "Internal ID of the quota.",+ "event_slug": "The slug of the event this quota belongs to (added by PostHog during sync).",+ "name": "The internal name of the quota.",+ "size": "The size of the quota, with null meaning unlimited.",+ "items": "The IDs of the items this quota applies to.",+ "variations": "The IDs of the item variations this quota applies to.",+ "subevent": "The ID of the sub-event this quota applies to, or null.",+ "closed": "Whether the quota is currently closed.",+ },+ },+ "vouchers": {+ "description": "A voucher granting discounted or reserved access to an event's items.",+ "docs_url": "https://docs.pretix.eu/en/latest/api/resources/vouchers.html",+ "columns": {+ "id": "Internal ID of the voucher.",+ "event_slug": "The slug of the event this voucher belongs to (added by PostHog during sync).",+ "code": "The voucher code used to redeem it.",+ "max_usages": "The maximum number of times the voucher can be redeemed.",+ "redeemed": "The number of times the voucher has already been redeemed.",+ "valid_until": "The expiry date of the voucher, or null.",+ "price_mode": "How the voucher changes the price: none, set, subtract, or percent.",+ "value": "The value the price is changed by, interpreted according to price_mode.",+ "item": "The ID of the item the voucher applies to, or null for all items.",+ "tag": "A tag used to group vouchers.",+ },+ },+ "checkin_lists": {+ "description": "A check-in list used to admit attendees at the door, with its position and check-in counters.",+ "docs_url": "https://docs.pretix.eu/en/latest/api/resources/checkinlists.html",+ "columns": {+ "id": "Internal ID of the check-in list.",+ "event_slug": "The slug of the event this check-in list belongs to (added by PostHog during sync).",+ "name": "The internal name of the check-in list.",+ "all_products": "Whether the list includes tickets for all products.",+ "limit_products": "The IDs of the products the list is limited to.",+ "subevent": "The ID of the sub-event the list is limited to, or null.",+ "position_count": "The number of ticket positions on the list.",+ "checkin_count": "The number of check-ins performed on the list.",+ "include_pending": "Whether unpaid (pending) orders are included on the list.",+ },+ },+ "waiting_list_entries": {+ "description": "A waiting list entry from a customer waiting for an event's sold-out item to become available.",+ "docs_url": "https://docs.pretix.eu/en/latest/api/resources/waitinglist.html",+ "columns": {+ "id": "Internal ID of the waiting list entry.",+ "event_slug": "The slug of the event this entry belongs to (added by PostHog during sync).",+ "email": "The email address of the person on the waiting list.",+ "created": "The date and time the entry was created.",+ "item": "The ID of the item the person is waiting for.",+ "variation": "The ID of the item variation the person is waiting for, or null.",+ "voucher": "The ID of the voucher sent to the person once the item became available, or null.",+ "subevent": "The ID of the sub-event the entry is for, or null.",+ },+ },+ "tax_rules": {+ "description": "A tax rule defining how taxes are calculated for an event's products.",+ "docs_url": "https://docs.pretix.eu/en/latest/api/resources/taxrules.html",+ "columns": {+ "id": "Internal ID of the tax rule.",+ "event_slug": "The slug of the event this tax rule belongs to (added by PostHog during sync).",+ "name": "The display name of the tax rule.",+ "rate": "The tax rate as a percentage.",+ "price_includes_tax": "Whether product prices are treated as including this tax.",+ "eu_reverse_charge": "Whether EU reverse charge rules are applied.",+ "home_country": "The country the event organizer is based in for tax purposes.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pretix/pretix.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pretix/pretix.pynew file mode 100644index 000000000000..c5b1a15837a5--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pretix/pretix.py@@ -0,0 +1,402 @@+"""pretix transport layer.++pretix is an open-source event-ticketing platform offered both as the hosted SaaS+(``https://pretix.eu``) and self-hosted (a customer-supplied host), so the API base URL must be+configurable. Auth is a team-level API token in an ``Authorization: Token <token>`` header; a token+is scoped to a single organizer, and every resource lives under+``/api/v1/organizers/{organizer}/...``.++List endpoints are page-number paginated with a ``count``/``next``/``previous``/``results``+envelope (page size defaults to the maximum of 50), where ``next`` is the full URL of the following+page. Orders and invoices use the organizer-level list endpoints spanning all events; the remaining+event-scoped resources fan out over the organizer's events.++Only ``orders`` documents a server-side timestamp filter (``modified_since``) together with a+``last_modified`` ordering key, so it is the only incremental stream. Everything else is full+refresh — pretix's other list endpoints only support ``If-Modified-Since`` conditional fetching+(all-or-nothing 304s), which is not a per-row cursor.+"""++import re+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import quote, urlencode, urlparse++import requests+from structlog.types import FilteringBoundLogger+from tenacity import RetryCallState, 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.mixins import _is_host_safe+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.pretix.settings import (+ EVENT_SLUG_KEY,+ EVENTS_PATH,+ PRETIX_ENDPOINTS,+ EndpointScope,+ PretixEndpointConfig,+)++DEFAULT_API_HOST = "https://pretix.eu"+API_VERSION_PATH = "/api/v1"++REQUEST_TIMEOUT_SECONDS = 60+MAX_RETRIES = 5+# pretix Hosted enforces 360 requests/minute per organizer token and returns 429 + Retry-After.+MAX_RETRY_AFTER_SECONDS = 60++HOST_NOT_ALLOWED_ERROR = "pretix API URL is not allowed"+HTTP_NOT_ALLOWED_ERROR = "pretix API URL must use HTTPS"+INVALID_ORGANIZER_ERROR = "Invalid pretix organizer short name"+++class PretixRetryableError(Exception):+ def __init__(self, message: str, retry_after: float | None = None) -> None:+ super().__init__(message)+ self.retry_after = retry_after+++class PretixHostNotAllowedError(Exception):+ pass+++class PretixResumeConfig:+ # Full URL of the next page to fetch, taken verbatim from the API's ``next`` link (query params,+ # including any `modified_since` filter, are baked into it). Only persisted for organizer-level+ # endpoints — event fan-out endpoints restart from the first event on resume and rely on merge+ # dedupe, since event ordering is not guaranteed stable across runs.+ next_url: str | None = None+++def normalize_base_url(base_url: Optional[str]) -> str:+ """Turn whatever the user typed into a ``<scheme>://<host>/api/v1`` base URL.++ Blank → the hosted pretix SaaS. Accepts bare hosts (``tickets.example.com``), full URLs with or+ without a scheme, and values that already include the ``/api/v1`` suffix.+ """+ raw = (base_url or "").strip()+ if not raw:+ raw = DEFAULT_API_HOST+ if not re.match(r"^https?://", raw, flags=re.IGNORECASE):+ raw = f"https://{raw}"+ raw = raw.rstrip("/")+ # Drop a trailing version segment the user may have pasted in, then re-add the version we target.+ raw = re.sub(r"/api/v\d+$", "", raw)+ return f"{raw}{API_VERSION_PATH}"+++def _host_of(base_url: str) -> str:+ # `urlparse` treats a backslash (and its `%5c` encoding) as userinfo, so+ # `https://127.0.0.1\@example.com` parses as host `example.com` while requests/urllib3 (per the+ # WHATWG URL rules) treat `\` as a path separator and connect to `127.0.0.1`. Normalize to `/`+ # first so the host we validate is the host the request actually reaches (SSRF bypass guard).+ normalized = base_url.replace("\\", "/").replace("%5c", "/").replace("%5C", "/")+ return (urlparse(normalized).hostname or "").lower()+++def _is_https(base_url: str) -> bool:+ # The API token rides in the Authorization header, so refuse plaintext HTTP to keep an on-path+ # attacker from capturing it.+ return urlparse(base_url).scheme == "https"+++def _quote_organizer(organizer: str) -> str:+ """URL-quote the organizer slug so it can't inject path segments into request URLs."""+ cleaned = organizer.strip().strip("/")+ if not cleaned:+ raise ValueError(INVALID_ORGANIZER_ERROR)+ return quote(cleaned, safe="")+++def _get_headers(api_token: str) -> dict[str, str]:+ return {"Authorization": f"Token {api_token}", "Accept": "application/json"}+++def _format_modified_since(value: Any) -> str:+ """Format an incremental value for pretix's ``modified_since`` filter (ISO 8601 UTC, Z suffix)."""+ if isinstance(value, datetime):+ utc_dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ return utc_dt.strftime("%Y-%m-%dT%H:%M:%SZ")+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+ return str(value)+++def _check_host(base_url: str, team_id: int) -> None:+ """Raise unless the (customer-controlled, possibly self-hosted) base URL is safe to call."""+ host = _host_of(base_url)+ host_ok, host_err = _is_host_safe(host, team_id)+ if not host_ok:+ raise PretixHostNotAllowedError(host_err or HOST_NOT_ALLOWED_ERROR)+ if not _is_https(base_url):+ raise PretixHostNotAllowedError(HTTP_NOT_ALLOWED_ERROR)+++def _parse_retry_after(response: requests.Response) -> float | None:+ """Honor a whole-second ``Retry-After`` on 429. HTTP-date forms are ignored."""+ raw = response.headers.get("Retry-After")+ if raw and raw.strip().isdigit():+ return min(float(raw.strip()), MAX_RETRY_AFTER_SECONDS)+ return None+++def _retry_wait(retry_state: RetryCallState) -> float:+ """Use a server-provided Retry-After when present, else exponential backoff."""+ exc = retry_state.outcome.exception() if retry_state.outcome else None+ if isinstance(exc, PretixRetryableError) and exc.retry_after is not None:+ return exc.retry_after+ return wait_exponential_jitter(initial=1, max=30)(retry_state)+++def _origin_of(url: str) -> tuple[str, str, int]:+ # Same backslash normalization as `_host_of`, so the origin we compare is the one requests+ # actually connects to.+ normalized = url.replace("\\", "/").replace("%5c", "/").replace("%5C", "/")+ parsed = urlparse(normalized)+ scheme = parsed.scheme.lower()+ port = parsed.port or (443 if scheme == "https" else 80)+ return scheme, (parsed.hostname or "").lower(), port+++def _ensure_same_origin(url: str, base_url: str) -> None:+ """Refuse pagination/resume URLs that leave the validated pretix origin.++ ``next`` links come from the (possibly self-hosted, customer-controlled) server and resume URLs+ from persisted state, while the session attaches the API token to every request — following an+ off-origin URL would hand the token to an arbitrary host (or reach internal addresses)."""+ if _origin_of(url) != _origin_of(base_url):+ raise PretixHostNotAllowedError(f"pretix pagination URL is not on the configured pretix host: {url}")+++def _fetch_page_impl(+ session: requests.Session,+ url: str,+ logger: FilteringBoundLogger,+) -> tuple[list[dict[str, Any]], Optional[str]]:+ """Fetch one list page. ``url`` is absolute — the initial endpoint URL (params baked in via+ urlencode) or a verbatim ``next`` link, so page params are never re-sent."""+ # Don't follow redirects: an attacker-controlled self-hosted URL could 3xx to an internal+ # address, bypassing the host validation done before the request (SSRF).+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS, allow_redirects=False)++ if response.status_code == 429 or response.status_code >= 500:+ retry_after = _parse_retry_after(response) if response.status_code == 429 else None+ raise PretixRetryableError(+ f"pretix API error (retryable): status={response.status_code}, url={url}", retry_after=retry_after+ )++ # A 3xx isn't an error status (`response.ok` is True), so reject it explicitly rather than+ # silently parsing the redirect body as data.+ if response.is_redirect or response.is_permanent_redirect:+ raise PretixHostNotAllowedError(+ f"pretix API returned an unexpected redirect (status={response.status_code}); refusing to follow it"+ )++ if not response.ok:+ logger.error(f"pretix API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ data = response.json()+ if not isinstance(data, dict) or not isinstance(data.get("results"), list):+ raise PretixRetryableError(f"pretix returned an unexpected payload for {url}: {type(data).__name__}")++ next_url = data.get("next")+ return data["results"], next_url if isinstance(next_url, str) and next_url else None+++_fetch_page = retry(+ retry=retry_if_exception_type((PretixRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRIES),+ wait=_retry_wait,+ reraise=True,+)(_fetch_page_impl)+++def _iter_pages(+ session: requests.Session,+ first_url: str,+ base_url: str,+ logger: FilteringBoundLogger,+) -> Iterator[tuple[list[dict[str, Any]], Optional[str]]]:+ """Yield ``(page_items, next_url)`` across every page starting at ``first_url``.++ Every fetched URL — including a resumed ``first_url`` — and every ``next`` link is pinned to the+ validated base origin before it is fetched or yielded (and thus before it can be persisted)."""+ url: Optional[str] = first_url+ while url:+ _ensure_same_origin(url, base_url)+ items, next_url = _fetch_page(session, url, logger)+ if next_url:+ _ensure_same_origin(next_url, base_url)+ yield items, next_url+ url = next_url+++def _build_url(base_url: str, path: str, params: dict[str, Any]) -> str:+ return f"{base_url}{path}?{urlencode(params)}" if params else f"{base_url}{path}"+++def _iter_event_slugs(+ session: requests.Session, base_url: str, organizer: str, logger: FilteringBoundLogger+) -> Iterator[str]:+ url = _build_url(base_url, EVENTS_PATH.format(organizer=organizer), {})+ for page, _ in _iter_pages(session, url, base_url, logger):+ for event in page:+ # Fail fast on a malformed response rather than silently dropping an event's children.+ yield str(event["slug"])+++def get_rows(+ api_token: str,+ organizer: str,+ base_url: Optional[str],+ endpoint: str,+ team_id: int,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[PretixResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> Iterator[list[dict[str, Any]]]:+ config: PretixEndpointConfig = PRETIX_ENDPOINTS[endpoint]+ resolved_base_url = normalize_base_url(base_url)+ # Re-check at run time (not just at source-create) in case the URL was edited or now resolves+ # to an internal address (SSRF / DNS rebinding). Only enforced on cloud.+ _check_host(resolved_base_url, team_id)+ quoted_organizer = _quote_organizer(organizer)++ # `redact_values` masks the token from captured HTTP samples — it rides in the Authorization+ # header with the non-standard `Token` scheme.+ session = make_tracked_session(headers=_get_headers(api_token), redact_values=(api_token,))++ params: dict[str, Any] = {}+ if config.ordering:+ # An explicit stable sort keeps page boundaries deterministic, and for `orders` it makes the+ # response order match SourceResponse.sort_mode="asc" so the incremental watermark advances+ # correctly (DRF-style `ordering=<field>` is ascending).+ params["ordering"] = config.ordering+ # Only narrow with the server-side `modified_since` filter when the endpoint supports it and the+ # user's chosen cursor is the field that filter targets. Honors inputs.incremental_field rather+ # than assuming it.+ if (+ should_use_incremental_field+ and config.modified_since_field+ and db_incremental_field_last_value+ and incremental_field in (None, config.modified_since_field)+ ):+ params["modified_since"] = _format_modified_since(db_incremental_field_last_value)++ if config.scope == EndpointScope.ORGANIZER:+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume and resume.next_url:+ logger.debug(f"pretix: resuming {endpoint} from saved page URL")+ first_url = resume.next_url+ else:+ first_url = _build_url(resolved_base_url, config.path.format(organizer=quoted_organizer), params)++ for page, next_url in _iter_pages(session, first_url, resolved_base_url, logger):+ if page:+ yield page+ # Save AFTER yielding so a crash re-fetches from the last unpersisted page (merge+ # dedupes the re-pulled page on the primary key).+ if next_url:+ resumable_source_manager.save_state(PretixResumeConfig(next_url=next_url))+ return++ # Event fan-out: paginate the child endpoint per event, stamping each row with its parent event+ # slug so composite primary keys stay unique table-wide. No resume state is persisted here.+ for event_slug in _iter_event_slugs(session, resolved_base_url, quoted_organizer, logger):+ path = config.path.format(organizer=quoted_organizer, event=quote(event_slug, safe=""))+ for page, _ in _iter_pages(session, _build_url(resolved_base_url, path, params), resolved_base_url, logger):+ if page:+ yield [{**row, EVENT_SLUG_KEY: event_slug} for row in page]+++def pretix_source(+ api_token: str,+ organizer: str,+ base_url: Optional[str],+ endpoint: str,+ team_id: int,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[PretixResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ config = PRETIX_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_token=api_token,+ organizer=organizer,+ base_url=base_url,+ endpoint=endpoint,+ team_id=team_id,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ incremental_field=incremental_field,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )+++def validate_credentials(+ api_token: str, organizer: str, base_url: Optional[str], team_id: Optional[int] = None+) -> tuple[bool, str | None]:+ """Probe the organizer's events list to confirm the token is genuine and scoped correctly.++ pretix team tokens carry per-resource permissions, so a single cheap probe only asserts the+ token + organizer pair is valid — per-endpoint 403s at sync time surface through+ ``get_non_retryable_errors``.+ """+ resolved_base_url = normalize_base_url(base_url)++ try:+ quoted_organizer = _quote_organizer(organizer)+ except ValueError:+ return False, INVALID_ORGANIZER_ERROR++ if team_id is not None:+ host_ok, host_err = _is_host_safe(_host_of(resolved_base_url), team_id)+ if not host_ok:+ return False, host_err or HOST_NOT_ALLOWED_ERROR+ if not _is_https(resolved_base_url):+ return False, HTTP_NOT_ALLOWED_ERROR++ url = _build_url(resolved_base_url, EVENTS_PATH.format(organizer=quoted_organizer), {"page_size": 1})+ session = make_tracked_session(headers=_get_headers(api_token), redact_values=(api_token,))+ try:+ response = session.get(url, timeout=15, allow_redirects=False)+ except Exception as e:+ return False, f"Could not connect to pretix: {e}"++ if response.is_redirect or response.is_permanent_redirect:+ return False, HOST_NOT_ALLOWED_ERROR++ if response.status_code == 200:+ return True, None++ if response.status_code == 401:+ return False, "Invalid pretix API token"++ if response.status_code == 403:+ # pretix returns 403 both for an unknown organizer and for a token without access to it.+ return False, (+ "Your pretix API token does not have access to this organizer. "+ "Check the organizer short name and the token's team permissions."+ )++ return False, f"pretix returned HTTP {response.status_code}"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pretix/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pretix/settings.pynew file mode 100644index 000000000000..4cbab2f438f9--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pretix/settings.py@@ -0,0 +1,165 @@+from dataclasses import dataclass, field+from enum import Enum+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+++class EndpointScope(Enum):+ """How an endpoint is reached.++ - ORGANIZER: a single organizer-scoped list endpoint, no fan-out needed.+ - EVENT: fanned out per event (path has an `{event}` placeholder); events are+ discovered from the organizer-level events list first.+ """++ ORGANIZER = "organizer"+ EVENT = "event"+++@dataclass+class PretixEndpointConfig:+ name: str+ path: str+ scope: EndpointScope+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Stable created-style datetime field for partitioning. Never a last-modified field.+ partition_key: Optional[str] = None+ # When set, the endpoint supports pretix's server-side `modified_since` filter targeting+ # this resource field (true incremental sync); otherwise the stream is full refresh only.+ modified_since_field: Optional[str] = None+ # Explicit `ordering` value to request. Only set where the docs list it as a valid+ # ordering field for that endpoint — pretix rejects unknown ordering values.+ ordering: Optional[str] = None+++def _last_modified_incremental_field() -> list[IncrementalField]:+ return [+ {+ "label": "last_modified",+ "type": IncrementalFieldType.DateTime,+ "field": "last_modified",+ "field_type": IncrementalFieldType.DateTime,+ }+ ]+++EVENTS_PATH = "/organizers/{organizer}/events/"++# Column injected into every event-scoped (fan-out) row so composite primary keys stay unique+# across the whole table — pretix docs don't guarantee child ids are unique beyond their event.+EVENT_SLUG_KEY = "event_slug"+++# Stream list cross-referenced against the Airbyte `source-pretix` connector plus the official API+# docs. `orders` is the only stream with a documented server-side timestamp filter+# (`modified_since`, orderable by `last_modified`), so it is the only incremental stream — every+# other list endpoint is full refresh. `orders` and `invoices` use the organizer-level endpoints+# (added in pretix 2023.8) that span all events and stamp each row with its parent `event` slug,+# avoiding a per-event fan-out for the two largest tables. Order positions arrive embedded in each+# order's `positions` array, so they don't need a dedicated stream.+PRETIX_ENDPOINTS: dict[str, PretixEndpointConfig] = {+ "events": PretixEndpointConfig(+ name="events",+ path=EVENTS_PATH,+ scope=EndpointScope.ORGANIZER,+ # Event slugs are unique within an organizer, and a source is scoped to one organizer.+ primary_keys=["slug"],+ ),+ "orders": PretixEndpointConfig(+ name="orders",+ path="/organizers/{organizer}/orders/",+ scope=EndpointScope.ORGANIZER,+ # Order codes are only documented unique within their event; rows carry the event slug.+ primary_keys=["event", "code"],+ incremental_fields=_last_modified_incremental_field(),+ partition_key="datetime",+ modified_since_field="last_modified",+ ordering="last_modified",+ ),+ "invoices": PretixEndpointConfig(+ name="invoices",+ path="/organizers/{organizer}/invoices/",+ scope=EndpointScope.ORGANIZER,+ # Invoice numbers are prefixed per event; rows carry the event slug.+ primary_keys=["event", "number"],+ ),+ "customers": PretixEndpointConfig(+ name="customers",+ path="/organizers/{organizer}/customers/",+ scope=EndpointScope.ORGANIZER,+ primary_keys=["identifier"],+ ),+ "gift_cards": PretixEndpointConfig(+ name="gift_cards",+ path="/organizers/{organizer}/giftcards/",+ scope=EndpointScope.ORGANIZER,+ ),+ "subevents": PretixEndpointConfig(+ name="subevents",+ path="/organizers/{organizer}/events/{event}/subevents/",+ scope=EndpointScope.EVENT,+ primary_keys=[EVENT_SLUG_KEY, "id"],+ ),+ "items": PretixEndpointConfig(+ name="items",+ path="/organizers/{organizer}/events/{event}/items/",+ scope=EndpointScope.EVENT,+ primary_keys=[EVENT_SLUG_KEY, "id"],+ ordering="id",+ ),+ "categories": PretixEndpointConfig(+ name="categories",+ path="/organizers/{organizer}/events/{event}/categories/",+ scope=EndpointScope.EVENT,+ primary_keys=[EVENT_SLUG_KEY, "id"],+ ),+ "questions": PretixEndpointConfig(+ name="questions",+ path="/organizers/{organizer}/events/{event}/questions/",+ scope=EndpointScope.EVENT,+ primary_keys=[EVENT_SLUG_KEY, "id"],+ ),+ "quotas": PretixEndpointConfig(+ name="quotas",+ path="/organizers/{organizer}/events/{event}/quotas/",+ scope=EndpointScope.EVENT,+ primary_keys=[EVENT_SLUG_KEY, "id"],+ ordering="id",+ ),+ "vouchers": PretixEndpointConfig(+ name="vouchers",+ path="/organizers/{organizer}/events/{event}/vouchers/",+ scope=EndpointScope.EVENT,+ primary_keys=[EVENT_SLUG_KEY, "id"],+ ordering="id",+ ),+ "checkin_lists": PretixEndpointConfig(+ name="checkin_lists",+ path="/organizers/{organizer}/events/{event}/checkinlists/",+ scope=EndpointScope.EVENT,+ primary_keys=[EVENT_SLUG_KEY, "id"],+ ordering="id",+ ),+ "waiting_list_entries": PretixEndpointConfig(+ name="waiting_list_entries",+ path="/organizers/{organizer}/events/{event}/waitinglistentries/",+ scope=EndpointScope.EVENT,+ primary_keys=[EVENT_SLUG_KEY, "id"],+ ),+ "tax_rules": PretixEndpointConfig(+ name="tax_rules",+ path="/organizers/{organizer}/events/{event}/taxrules/",+ scope=EndpointScope.EVENT,+ primary_keys=[EVENT_SLUG_KEY, "id"],+ ),+}++ENDPOINTS = tuple(PRETIX_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in PRETIX_ENDPOINTS.items()+}++INCREMENTAL_ENDPOINTS = tuple(name for name, config in PRETIX_ENDPOINTS.items() if config.modified_since_field)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pretix/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pretix/source.pyindex 95a187062f7e..8652dcbf1b8c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/pretix/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pretix/source.py@@ -1,30 +1,167 @@-from typing import cast+from typing import Optional, castfrom 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 SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import PretixSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.pretix.pretix import (+ HOST_NOT_ALLOWED_ERROR,+ HTTP_NOT_ALLOWED_ERROR,+ PretixResumeConfig,+ pretix_source,+ validate_credentials as validate_pretix_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.pretix.settings import (+ ENDPOINTS,+ INCREMENTAL_ENDPOINTS,+ INCREMENTAL_FIELDS,+ PRETIX_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class PretixSource(SimpleSource[PretixSourceConfig]):+class PretixSource(ResumableSource[PretixSourceConfig, PretixResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.PRETIX+ @property+ def connection_host_fields(self) -> list[str]:+ # `base_url` is where the stored API token is sent; retargeting it must re-require the token.+ return ["base_url"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.PRETIX,- category=DataWarehouseSourceCategory.E_COMMERCE,+ category=DataWarehouseSourceCategory.PRODUCTIVITY,label="Pretix",- iconPath="/static/services/pretix.png",- fields=cast(list[FieldType], []),+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,+ keywords=["ticketing", "events", "tickets"],+ caption="""Enter your pretix API token to pull your event ticketing data into the PostHog Data warehouse.++You can create a team API token in pretix under **Organizer settings → Teams → your team → Create API token**. The token is scoped to one organizer; enter that organizer's short name (slug) below. The token's team needs read permission for the resources you want to sync (for example *Can view orders* for orders and invoices, *Can view vouchers* for vouchers).++Self-hosted users should set the API URL to their own pretix host (for example `https://tickets.example.com`). Leave it blank to use the hosted pretix (`https://pretix.eu`).""",+ iconPath="/static/services/pretix.png",+ docsUrl="https://posthog.com/docs/cdp/sources/pretix",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="organizer",+ label="Organizer short name",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="my-organizer",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="api_token",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="base_url",+ label="API URL (self-hosted only)",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="https://pretix.eu",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.pretix.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Your pretix API token is invalid or has been revoked. Create a new team API token in pretix and reconnect.",+ "403 Client Error": "Your pretix API token does not have permission for this data. Check the token's team permissions (for example 'Can view orders') and try again.",+ HOST_NOT_ALLOWED_ERROR: "The pretix API URL is not allowed. Please use a publicly reachable host.",+ HTTP_NOT_ALLOWED_ERROR: "The pretix API URL must use HTTPS. Please update the API URL to use https://.",+ }++ def get_schemas(+ self,+ config: PretixSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=endpoint in INCREMENTAL_ENDPOINTS,+ supports_append=endpoint in INCREMENTAL_ENDPOINTS,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ )+ 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: PretixSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_pretix_credentials(config.api_token, config.organizer, config.base_url, team_id)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[PretixResumeConfig]:+ return ResumableSourceManager[PretixResumeConfig](inputs, PretixResumeConfig)++ def source_for_pipeline(+ self,+ config: PretixSourceConfig,+ resumable_source_manager: ResumableSourceManager[PretixResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ if inputs.schema_name not in PRETIX_ENDPOINTS:+ raise ValueError(f"Unknown pretix schema '{inputs.schema_name}'")++ return pretix_source(+ api_token=config.api_token,+ organizer=config.organizer,+ base_url=config.base_url,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,+ incremental_field=inputs.incremental_field,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pretix/tests/test_pretix.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pretix/tests/test_pretix.pynew file mode 100644index 000000000000..94d369939de1--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pretix/tests/test_pretix.py@@ -0,0 +1,548 @@+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import parse_qs, urlparse++import pytest+from unittest import mock++from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.pretix import pretix as px+from products.warehouse_sources.backend.temporal.data_imports.sources.pretix.pretix import (+ HOST_NOT_ALLOWED_ERROR,+ INVALID_ORGANIZER_ERROR,+ PretixHostNotAllowedError,+ PretixResumeConfig,+ PretixRetryableError,+ _fetch_page_impl,+ _format_modified_since,+ _parse_retry_after,+ _quote_organizer,+ get_rows,+ normalize_base_url,+ pretix_source,+ validate_credentials,+)++LOGGER = mock.MagicMock()+++def _no_resume_manager() -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = False+ return manager+++def _response(+ status_code: int = 200,+ json_data: Any = None,+ headers: dict[str, str] | None = None,+ is_redirect: bool = False,+) -> mock.MagicMock:+ response = mock.MagicMock()+ response.status_code = status_code+ response.headers = headers or {}+ response.is_redirect = is_redirect+ response.is_permanent_redirect = False+ response.ok = status_code < 400+ response.json.return_value = json_data+ return response+++def _page(items: list[dict[str, Any]], next_url: Optional[str]) -> dict[str, Any]:+ return {"count": len(items), "next": next_url, "previous": None, "results": items}+++class TestNormalizeBaseUrl:+ @parameterized.expand(+ [+ (None, "https://pretix.eu/api/v1"),+ ("", "https://pretix.eu/api/v1"),+ (" ", "https://pretix.eu/api/v1"),+ ("tickets.example.com", "https://tickets.example.com/api/v1"),+ ("https://tickets.example.com", "https://tickets.example.com/api/v1"),+ ("https://tickets.example.com/", "https://tickets.example.com/api/v1"),+ ("https://tickets.example.com/api/v1", "https://tickets.example.com/api/v1"),+ ("http://tickets.example.com", "http://tickets.example.com/api/v1"),+ ]+ )+ def test_normalize_base_url(self, raw: Optional[str], expected: str) -> None:+ assert normalize_base_url(raw) == expected+++class TestFormatModifiedSince:+ @parameterized.expand(+ [+ (datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14Z"),+ (datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14Z"),+ (date(2026, 3, 4), "2026-03-04T00:00:00Z"),+ ("2026-03-04T02:58:14Z", "2026-03-04T02:58:14Z"),+ ]+ )+ def test_format_modified_since(self, value: object, expected: str) -> None:+ assert _format_modified_since(value) == expected+++class TestQuoteOrganizer:+ @parameterized.expand(+ [+ ("my-organizer", "my-organizer"),+ (" my-organizer ", "my-organizer"),+ ("/my-organizer/", "my-organizer"),+ ("a/../b", "a%2F..%2Fb"),+ ]+ )+ def test_quotes_path_segments(self, raw: str, expected: str) -> None:+ assert _quote_organizer(raw) == expected++ @parameterized.expand([("",), (" ",), ("/",)])+ def test_rejects_empty(self, raw: str) -> None:+ with pytest.raises(ValueError, match=INVALID_ORGANIZER_ERROR):+ _quote_organizer(raw)+++class TestFetchPage:+ # `_fetch_page_impl` is the undecorated fetch, so failures don't sleep through tenacity retries.++ def test_returns_items_and_next_url(self) -> None:+ session = mock.MagicMock()+ session.get.return_value = _response(json_data=_page([{"id": 1}], "https://pretix.eu/api/v1/x/?page=2"))++ items, next_url = _fetch_page_impl(session, "https://pretix.eu/api/v1/x/", LOGGER)++ assert items == [{"id": 1}]+ assert next_url == "https://pretix.eu/api/v1/x/?page=2"++ def test_null_next_terminates(self) -> None:+ session = mock.MagicMock()+ session.get.return_value = _response(json_data=_page([{"id": 1}], None))++ _, next_url = _fetch_page_impl(session, "https://pretix.eu/api/v1/x/", LOGGER)++ assert next_url is None++ def test_429_raises_retryable_with_retry_after(self) -> None:+ session = mock.MagicMock()+ session.get.return_value = _response(status_code=429, headers={"Retry-After": "7"})++ with pytest.raises(PretixRetryableError) as exc_info:+ _fetch_page_impl(session, "https://pretix.eu/api/v1/x/", LOGGER)++ assert exc_info.value.retry_after == 7.0++ def test_5xx_raises_retryable(self) -> None:+ session = mock.MagicMock()+ session.get.return_value = _response(status_code=503)++ with pytest.raises(PretixRetryableError):+ _fetch_page_impl(session, "https://pretix.eu/api/v1/x/", LOGGER)++ def test_redirect_is_rejected(self) -> None:+ session = mock.MagicMock()+ session.get.return_value = _response(status_code=302, is_redirect=True)++ with pytest.raises(PretixHostNotAllowedError):+ _fetch_page_impl(session, "https://pretix.eu/api/v1/x/", LOGGER)++ def test_unexpected_payload_raises_retryable(self) -> None:+ session = mock.MagicMock()+ session.get.return_value = _response(json_data=[{"id": 1}])++ with pytest.raises(PretixRetryableError):+ _fetch_page_impl(session, "https://pretix.eu/api/v1/x/", LOGGER)++ @parameterized.expand(+ [+ ({"Retry-After": "7"}, 7.0),+ ({"Retry-After": "999"}, 60.0),+ ({"Retry-After": "Wed, 21 Oct 2026 07:28:00 GMT"}, None),+ ({}, None),+ ]+ )+ def test_parse_retry_after(self, headers: dict[str, str], expected: float | None) -> None:+ assert _parse_retry_after(_response(status_code=429, headers=headers)) == expected++[email protected](px, "_is_host_safe", return_value=(True, None))[email protected](px, "make_tracked_session", return_value=mock.MagicMock())+class TestGetRowsOrganizerScope:+ @mock.patch.object(px, "_fetch_page")+ def test_orders_incremental_url_has_filter_and_stable_ordering(+ self, mock_fetch: mock.MagicMock, _session: mock.MagicMock, _host: mock.MagicMock+ ) -> None:+ mock_fetch.return_value = ([{"code": "A1", "event": "conf"}], None)++ list(+ get_rows(+ api_token="tok",+ organizer="acme",+ base_url=None,+ endpoint="orders",+ team_id=1,+ logger=LOGGER,+ resumable_source_manager=_no_resume_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),+ incremental_field="last_modified",+ )+ )++ url = mock_fetch.call_args[0][1]+ parsed = urlparse(url)+ assert parsed.path == "/api/v1/organizers/acme/orders/"+ query = parse_qs(parsed.query)+ assert query["modified_since"] == ["2026-01-01T00:00:00Z"]+ assert query["ordering"] == ["last_modified"]++ @parameterized.expand(+ [+ (False, "last_modified"),+ # A user-selected cursor the server filter doesn't target must not be silently rewritten+ # into a `modified_since` filter.+ (True, "datetime"),+ ]+ )+ @mock.patch.object(px, "_fetch_page")+ def test_no_modified_since_when_not_applicable(+ self,+ should_use: bool,+ incremental_field: str,+ mock_fetch: mock.MagicMock,+ _session: mock.MagicMock,+ _host: mock.MagicMock,+ ) -> None:+ mock_fetch.return_value = ([], None)++ list(+ get_rows(+ api_token="tok",+ organizer="acme",+ base_url=None,+ endpoint="orders",+ team_id=1,+ logger=LOGGER,+ resumable_source_manager=_no_resume_manager(),+ should_use_incremental_field=should_use,+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),+ incremental_field=incremental_field,+ )+ )++ url = mock_fetch.call_args[0][1]+ assert "modified_since" not in url++ @mock.patch.object(px, "_fetch_page")+ def test_state_saved_only_after_page_is_yielded(+ self, mock_fetch: mock.MagicMock, _session: mock.MagicMock, _host: mock.MagicMock+ ) -> None:+ next_url = "https://pretix.eu/api/v1/organizers/acme/orders/?page=2"+ mock_fetch.side_effect = [+ ([{"code": "A1"}], next_url),+ ([{"code": "A2"}], None),+ ]+ manager = _no_resume_manager()++ rows = get_rows(+ api_token="tok",+ organizer="acme",+ base_url=None,+ endpoint="orders",+ team_id=1,+ logger=LOGGER,+ resumable_source_manager=manager,+ )++ assert next(rows) == [{"code": "A1"}]+ # A crash here must re-fetch page 1 (nothing persisted yet), not skip it.+ manager.save_state.assert_not_called()++ assert next(rows) == [{"code": "A2"}]+ manager.save_state.assert_called_once_with(PretixResumeConfig(next_url=next_url))++ @mock.patch.object(px, "_fetch_page")+ def test_off_origin_next_url_is_rejected_before_yield(+ self, mock_fetch: mock.MagicMock, _session: mock.MagicMock, _host: mock.MagicMock+ ) -> None:+ # The session sends the API token on every request, so a malicious server handing out an+ # off-origin `next` link must not be followed — or persisted for a later resume.+ mock_fetch.return_value = ([{"code": "A1"}], "https://evil.example.com/steal?page=2")+ manager = _no_resume_manager()++ with pytest.raises(PretixHostNotAllowedError):+ list(+ get_rows(+ api_token="tok",+ organizer="acme",+ base_url=None,+ endpoint="orders",+ team_id=1,+ logger=LOGGER,+ resumable_source_manager=manager,+ )+ )++ assert mock_fetch.call_count == 1+ manager.save_state.assert_not_called()++ @mock.patch.object(px, "_fetch_page")+ def test_off_origin_resume_url_is_rejected_before_fetch(+ self, mock_fetch: mock.MagicMock, _session: mock.MagicMock, _host: mock.MagicMock+ ) -> None:+ manager = mock.MagicMock()+ manager.can_resume.return_value = True+ manager.load_state.return_value = PretixResumeConfig(next_url="https://evil.example.com/steal?page=5")++ with pytest.raises(PretixHostNotAllowedError):+ list(+ get_rows(+ api_token="tok",+ organizer="acme",+ base_url=None,+ endpoint="orders",+ team_id=1,+ logger=LOGGER,+ resumable_source_manager=manager,+ )+ )++ mock_fetch.assert_not_called()++ @mock.patch.object(px, "_fetch_page")+ def test_resumes_from_saved_next_url(+ self, mock_fetch: mock.MagicMock, _session: mock.MagicMock, _host: mock.MagicMock+ ) -> None:+ saved_url = "https://pretix.eu/api/v1/organizers/acme/orders/?page=5"+ manager = mock.MagicMock()+ manager.can_resume.return_value = True+ manager.load_state.return_value = PretixResumeConfig(next_url=saved_url)+ mock_fetch.return_value = ([{"code": "A9"}], None)++ list(+ get_rows(+ api_token="tok",+ organizer="acme",+ base_url=None,+ endpoint="orders",+ team_id=1,+ logger=LOGGER,+ resumable_source_manager=manager,+ )+ )++ assert mock_fetch.call_args[0][1] == saved_url++ def test_unsafe_host_raises_before_any_request(+ self, session_factory: mock.MagicMock, mock_host: mock.MagicMock+ ) -> None:+ mock_host.return_value = (False, HOST_NOT_ALLOWED_ERROR)++ with pytest.raises(PretixHostNotAllowedError):+ list(+ get_rows(+ api_token="tok",+ organizer="acme",+ base_url="https://internal.example.com",+ endpoint="orders",+ team_id=1,+ logger=LOGGER,+ resumable_source_manager=_no_resume_manager(),+ )+ )++ session_factory.return_value.get.assert_not_called()++ def test_http_base_url_raises(self, session_factory: mock.MagicMock, _host: mock.MagicMock) -> None:+ with pytest.raises(PretixHostNotAllowedError):+ list(+ get_rows(+ api_token="tok",+ organizer="acme",+ base_url="http://tickets.example.com",+ endpoint="orders",+ team_id=1,+ logger=LOGGER,+ resumable_source_manager=_no_resume_manager(),+ )+ )++ session_factory.return_value.get.assert_not_called()++[email protected](px, "_is_host_safe", return_value=(True, None))[email protected](px, "make_tracked_session", return_value=mock.MagicMock())+class TestGetRowsEventFanOut:+ @mock.patch.object(px, "_fetch_page")+ def test_fans_out_per_event_and_stamps_event_slug(+ self, mock_fetch: mock.MagicMock, _session: mock.MagicMock, _host: mock.MagicMock+ ) -> None:+ def router(_session: Any, url: str, _logger: Any) -> tuple[list[dict[str, Any]], Optional[str]]:+ path = urlparse(url).path+ if path == "/api/v1/organizers/acme/events/":+ return [{"slug": "conf-a"}, {"slug": "conf-b"}], None+ if path == "/api/v1/organizers/acme/events/conf-a/items/":+ return [{"id": 1}], None+ if path == "/api/v1/organizers/acme/events/conf-b/items/":+ return [{"id": 1}, {"id": 2}], None+ raise AssertionError(f"unexpected url {url}")++ mock_fetch.side_effect = router+ manager = _no_resume_manager()++ pages = list(+ get_rows(+ api_token="tok",+ organizer="acme",+ base_url=None,+ endpoint="items",+ team_id=1,+ logger=LOGGER,+ resumable_source_manager=manager,+ )+ )++ rows = [row for page in pages for row in page]+ # The composite primary key (event_slug, id) must stay unique even though both events reuse id=1.+ assert [(row["event_slug"], row["id"]) for row in rows] == [("conf-a", 1), ("conf-b", 1), ("conf-b", 2)]+ # Fan-out endpoints restart from the first event on resume; no partial state may be persisted.+ manager.save_state.assert_not_called()++ @mock.patch.object(px, "_fetch_page")+ def test_event_slug_is_url_quoted_in_child_path(+ self, mock_fetch: mock.MagicMock, _session: mock.MagicMock, _host: mock.MagicMock+ ) -> None:+ seen_urls: list[str] = []++ def router(_session: Any, url: str, _logger: Any) -> tuple[list[dict[str, Any]], Optional[str]]:+ seen_urls.append(url)+ if urlparse(url).path == "/api/v1/organizers/acme/events/":+ return [{"slug": "a/b"}], None+ return [], None++ mock_fetch.side_effect = router++ list(+ get_rows(+ api_token="tok",+ organizer="acme",+ base_url=None,+ endpoint="items",+ team_id=1,+ logger=LOGGER,+ resumable_source_manager=_no_resume_manager(),+ )+ )++ assert any("/events/a%2Fb/items/" in url for url in seen_urls)++[email protected](px, "_is_host_safe", return_value=(True, None))+class TestValidateCredentials:+ @parameterized.expand(+ [+ (200, True, None),+ (401, False, "Invalid pretix API token"),+ (403, False, "does not have access to this organizer"),+ (500, False, "HTTP 500"),+ ]+ )+ @mock.patch.object(px, "make_tracked_session")+ def test_status_mapping(+ self,+ status_code: int,+ expected_valid: bool,+ message_fragment: str | None,+ session_factory: mock.MagicMock,+ _host: mock.MagicMock,+ ) -> None:+ session = mock.MagicMock()+ session.get.return_value = _response(status_code=status_code)+ session_factory.return_value = session++ is_valid, message = validate_credentials("tok", "acme", None, team_id=1)++ assert is_valid is expected_valid+ if message_fragment is None:+ assert message is None+ else:+ assert message is not None and message_fragment in message++ @mock.patch.object(px, "make_tracked_session")+ def test_redirect_is_rejected(self, session_factory: mock.MagicMock, _host: mock.MagicMock) -> None:+ session = mock.MagicMock()+ session.get.return_value = _response(status_code=302, is_redirect=True)+ session_factory.return_value = session++ is_valid, message = validate_credentials("tok", "acme", None, team_id=1)++ assert is_valid is False+ assert message == HOST_NOT_ALLOWED_ERROR++ @mock.patch.object(px, "make_tracked_session")+ def test_connection_error_returns_message(self, session_factory: mock.MagicMock, _host: mock.MagicMock) -> None:+ session = mock.MagicMock()+ session.get.side_effect = Exception("network down")+ session_factory.return_value = session++ is_valid, message = validate_credentials("tok", "acme", None, team_id=1)++ assert is_valid is False+ assert message is not None and "Could not connect to pretix" in message++ @mock.patch.object(px, "make_tracked_session")+ def test_invalid_organizer_rejected_without_request(+ self, session_factory: mock.MagicMock, _host: mock.MagicMock+ ) -> None:+ is_valid, message = validate_credentials("tok", " ", None, team_id=1)++ assert is_valid is False+ assert message == INVALID_ORGANIZER_ERROR+ session_factory.assert_not_called()++ @mock.patch.object(px, "make_tracked_session")+ def test_http_base_url_rejected_without_request(+ self, session_factory: mock.MagicMock, _host: mock.MagicMock+ ) -> None:+ is_valid, message = validate_credentials("tok", "acme", "http://tickets.example.com", team_id=1)++ assert is_valid is False+ assert message is not None and "HTTPS" in message+ session_factory.assert_not_called()+++class TestPretixSourceResponse:+ def _source(self, endpoint: str):+ return pretix_source(+ api_token="tok",+ organizer="acme",+ base_url=None,+ endpoint=endpoint,+ team_id=1,+ logger=LOGGER,+ resumable_source_manager=mock.MagicMock(),+ )++ def test_orders_partitioned_on_stable_creation_datetime(self) -> None:+ response = self._source("orders")++ assert response.name == "orders"+ assert response.primary_keys == ["event", "code"]+ assert response.partition_mode == "datetime"+ assert response.partition_format == "month"+ assert response.partition_keys == ["datetime"]+ assert response.sort_mode == "asc"++ @parameterized.expand(+ [+ ("events", ["slug"]),+ ("invoices", ["event", "number"]),+ ("customers", ["identifier"]),+ ("gift_cards", ["id"]),+ ("items", ["event_slug", "id"]),+ ("vouchers", ["event_slug", "id"]),+ ]+ )+ def test_primary_keys_per_endpoint(self, endpoint: str, primary_keys: list[str]) -> None:+ response = self._source(endpoint)++ assert response.primary_keys == primary_keys+ assert response.partition_mode is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pretix/tests/test_pretix_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pretix/tests/test_pretix_source.pynew file mode 100644index 000000000000..b8e87a4da1e4--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pretix/tests/test_pretix_source.py@@ -0,0 +1,162 @@+import pytest+from unittest import mock++from parameterized import parameterized++from posthog.schema import SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import PretixSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.pretix.pretix import PretixResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.pretix.settings import (+ ENDPOINTS,+ INCREMENTAL_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.pretix.source import PretixSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestPretixSource:+ def setup_method(self):+ self.source = PretixSource()+ self.team_id = 123+ self.config = PretixSourceConfig(organizer="acme", api_token="test-token")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.PRETIX++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Pretix"+ assert config.label == "Pretix"+ assert config.releaseStatus == "alpha"+ assert config.iconPath == "/static/services/pretix.png"++ fields = {f.name: f for f in config.fields}+ assert set(fields) == {"organizer", "api_token", "base_url"}++ token_field = fields["api_token"]+ assert isinstance(token_field, SourceFieldInputConfig)+ assert token_field.type == SourceFieldInputConfigType.PASSWORD+ assert token_field.required is True+ assert token_field.secret is True++ organizer_field = fields["organizer"]+ assert isinstance(organizer_field, SourceFieldInputConfig)+ assert organizer_field.required is True++ base_url_field = fields["base_url"]+ assert isinstance(base_url_field, SourceFieldInputConfig)+ assert base_url_field.required is False++ def test_connection_host_fields_covers_base_url(self):+ # Retargeting the API URL must force re-entry of the token, otherwise an editor could point+ # the preserved token at a host they control.+ assert self.source.connection_host_fields == ["base_url"]++ def test_non_retryable_errors_matches_observed_error_message(self):+ observed_error = "401 Client Error: Unauthorized for url: https://pretix.eu/api/v1/organizers/acme/orders/"+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable_errors)++ def test_get_schemas_lists_all_endpoints(self):+ schemas = self.source.get_schemas(self.config, self.team_id)++ assert {schema.name for schema in schemas} == set(ENDPOINTS)++ def test_get_schemas_incremental_flags_match_settings(self):+ schemas = self.source.get_schemas(self.config, self.team_id)++ for schema in schemas:+ expected = schema.name in INCREMENTAL_ENDPOINTS+ assert schema.supports_incremental is expected+ assert schema.supports_append is expected+ if expected:+ assert schema.incremental_fields, f"{schema.name} should advertise incremental fields"+ else:+ assert schema.incremental_fields == []++ def test_orders_is_the_only_incremental_endpoint(self):+ # Only `orders` has a documented server-side `modified_since` filter; advertising incremental+ # on another endpoint would silently full-refresh under an incremental label.+ assert set(INCREMENTAL_ENDPOINTS) == {"orders"}++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["events", "nonexistent"])++ assert [schema.name for schema in schemas] == ["events"]++ @parameterized.expand(+ [+ ((True, None),),+ ((False, "Invalid pretix API token"),),+ ]+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.pretix.source.validate_pretix_credentials"+ )+ def test_validate_credentials_delegates_to_transport(self, validation_result, mock_validate):+ mock_validate.return_value = validation_result++ assert self.source.validate_credentials(self.config, self.team_id) == validation_result+ mock_validate.assert_called_once_with(+ self.config.api_token, self.config.organizer, self.config.base_url, self.team_id+ )++ def test_get_resumable_source_manager_bound_to_resume_config(self):+ inputs = mock.MagicMock()+ inputs.logger = mock.MagicMock()++ manager = self.source.get_resumable_source_manager(inputs)++ assert manager._data_class is PretixResumeConfig++ def test_source_for_pipeline_rejects_unknown_schema(self):+ inputs = mock.MagicMock()+ inputs.schema_name = "nonexistent"++ with pytest.raises(ValueError, match="Unknown pretix schema"):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.pretix.source.pretix_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_pretix_source):+ manager = mock.MagicMock()+ inputs = mock.MagicMock()+ inputs.schema_name = "orders"+ inputs.team_id = self.team_id+ inputs.logger = mock.MagicMock()+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"+ inputs.incremental_field = "last_modified"++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_pretix_source.assert_called_once_with(+ api_token=self.config.api_token,+ organizer=self.config.organizer,+ base_url=self.config.base_url,+ endpoint="orders",+ team_id=self.team_id,+ logger=inputs.logger,+ resumable_source_manager=manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-01-01T00:00:00Z",+ incremental_field="last_modified",+ )++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.pretix.source.pretix_source")+ def test_source_for_pipeline_nulls_last_value_when_not_incremental(self, mock_pretix_source):+ manager = mock.MagicMock()+ inputs = mock.MagicMock()+ inputs.schema_name = "events"+ inputs.team_id = self.team_id+ inputs.logger = mock.MagicMock()+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"+ inputs.incremental_field = None++ self.source.source_for_pipeline(self.config, manager, inputs)++ _, kwargs = mock_pretix_source.call_args+ assert kwargs["db_incremental_field_last_value"] is None+ assert kwargs["should_use_incremental_field"] is False