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): add Cliniko import source (#84349)

Tom Owers8c93b8558e4d
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cliniko/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cliniko/canonical_descriptions.py
new file mode 100644
index 000000000000..d1381e528519
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cliniko/canonical_descriptions.py
@@ -0,0 +1,218 @@
+"""Canonical, documentation-sourced descriptions for Cliniko endpoints and columns.
+
+Sourced from the official Cliniko API reference (https://docs.api.cliniko.com/openapi). Keyed by
+the resource names in `settings.py` `ENDPOINTS`, which match the `ExternalDataSchema.name` of a
+synced Cliniko table. Columns absent here fall back to LLM enrichment.
+"""
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Fields shared by most Cliniko resources; merged into each entry so we don't repeat them.
+_COMMON_COLUMNS = {
+ "id": "Unique identifier for the record.",
+ "created_at": "Time the record was created, in UTC.",
+ "updated_at": "Time the record was last updated, in UTC.",
+ "archived_at": "Time the record was archived (soft-deleted), or null if still active.",
+}
+
+
+def _columns(**overrides: str) -> dict[str, str]:
+ return {**_COMMON_COLUMNS, **overrides}
+
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "patients": {
+ "description": "A patient (client) record in the practice.",
+ "docs_url": "https://docs.api.cliniko.com/openapi/patient",
+ "columns": _columns(
+ first_name="Patient's first name.",
+ last_name="Patient's last name.",
+ preferred_first_name="Name the patient prefers to be called.",
+ email="Patient's email address.",
+ date_of_birth="Patient's date of birth.",
+ gender="Patient's gender.",
+ sex="Patient's sex.",
+ address_1="First line of the patient's address.",
+ city="City of the patient's address.",
+ state="State or region of the patient's address.",
+ post_code="Postal or zip code of the patient's address.",
+ country="Country of the patient's address.",
+ country_code="ISO 3166-1 country code of the patient's address.",
+ time_zone="Patient's time zone.",
+ accepted_privacy_policy="Whether the patient has accepted the practice's privacy policy.",
+ accepted_email_marketing="Whether the patient has opted in to email marketing.",
+ accepted_sms_marketing="Whether the patient has opted in to SMS marketing.",
+ deleted_at="Time the record was deleted, or null if not deleted.",
+ merged_at="Time this patient record was merged into another, or null if not merged.",
+ notes="Free-text notes about the patient.",
+ ),
+ },
+ "individual_appointments": {
+ "description": "A one-on-one appointment between a patient and a practitioner.",
+ "docs_url": "https://docs.api.cliniko.com/openapi/individual-appointment",
+ "columns": _columns(
+ starts_at="Time the appointment starts, in UTC.",
+ ends_at="Time the appointment ends, in UTC.",
+ cancelled_at="Time the appointment was cancelled, or null if not cancelled.",
+ cancellation_reason="Reason the appointment was cancelled.",
+ cancellation_note="Free-text note about the cancellation.",
+ did_not_arrive="Whether the patient failed to arrive for the appointment.",
+ patient_arrived="Whether the patient has arrived for the appointment.",
+ notes="Free-text notes about the appointment.",
+ invoice_status="Billing status of the appointment's invoice.",
+ deleted_at="Time the record was deleted, or null if not deleted.",
+ telehealth_url="URL for the telehealth video call, if the appointment is a telehealth appointment.",
+ ),
+ },
+ "group_appointments": {
+ "description": "An appointment with multiple patient attendees, run by one practitioner.",
+ "docs_url": "https://docs.api.cliniko.com/openapi/group-appointment",
+ "columns": _columns(
+ starts_at="Time the appointment starts, in UTC.",
+ ends_at="Time the appointment ends, in UTC.",
+ max_attendees="Maximum number of patients that can attend the appointment.",
+ notes="Free-text notes about the appointment.",
+ deleted_at="Time the record was deleted, or null if not deleted.",
+ telehealth_url="URL for the telehealth video call, if the appointment is a telehealth appointment.",
+ ),
+ },
+ "attendees": {
+ "description": "A patient's attendance record for one appointment, including arrival and cancellation status.",
+ "docs_url": "https://docs.api.cliniko.com/openapi/attendee",
+ "columns": _columns(
+ arrived="Whether the patient arrived for the appointment.",
+ cancelled_at="Time the attendance was cancelled, or null if not cancelled.",
+ cancellation_reason="Reason the attendance was cancelled.",
+ cancellation_note="Free-text note about the cancellation.",
+ invoice_status="Billing status of the attendee's invoice.",
+ sent_email_reminders_count="Number of email reminders sent for this appointment.",
+ sent_sms_reminders_count="Number of SMS reminders sent for this appointment.",
+ treatment_note_status="Status of the treatment note for this attendance (draft or final).",
+ deleted_at="Time the record was deleted, or null if not deleted.",
+ ),
+ },
+ "practitioners": {
+ "description": "A practitioner (allied health provider) who delivers appointments.",
+ "docs_url": "https://docs.api.cliniko.com/openapi/practitioner",
+ "columns": _columns(
+ first_name="Practitioner's first name.",
+ last_name="Practitioner's last name.",
+ display_name="Practitioner's display name.",
+ label="Practitioner's full label, typically title and name.",
+ title="Practitioner's title (e.g. Dr).",
+ designation="Practitioner's professional designation.",
+ active="Whether the practitioner is currently active.",
+ show_in_online_bookings="Whether the practitioner is shown for online bookings.",
+ description="Free-text description of the practitioner, shown for online bookings.",
+ ),
+ },
+ "businesses": {
+ "description": "A business location (clinic site) within the practice.",
+ "docs_url": "https://docs.api.cliniko.com/openapi/business",
+ "columns": _columns(
+ business_name="Legal or trading name of the business.",
+ display_name="Display name of the business.",
+ address_1="First line of the business address.",
+ city="City of the business address.",
+ state="State or region of the business address.",
+ post_code="Postal or zip code of the business address.",
+ country="Country of the business address.",
+ country_code="ISO 3166-1 country code of the business address.",
+ time_zone="Human-readable time zone label for the business.",
+ time_zone_identifier="IANA time zone identifier for the business.",
+ website_address="Business website URL.",
+ ),
+ },
+ "invoices": {
+ "description": "A billing invoice raised for a patient's appointment.",
+ "docs_url": "https://docs.api.cliniko.com/openapi/invoice",
+ "columns": _columns(
+ number="Invoice number.",
+ issue_date="Date the invoice was issued.",
+ status="Billing status of the invoice (open, paid, closed, or open credit).",
+ status_description="Human-readable description of the invoice status.",
+ total_amount="Total invoice amount, including tax.",
+ tax_amount="Total tax amount on the invoice.",
+ discounted_amount="Total discount applied to the invoice.",
+ net_amount="Net invoice amount, excluding tax.",
+ closed_at="Time the invoice was closed, or null if still open.",
+ deleted_at="Time the record was deleted, or null if not deleted.",
+ notes="Free-text notes about the invoice.",
+ online_payment_url="URL where the patient can pay the invoice online.",
+ ),
+ },
+ "invoice_items": {
+ "description": "A single line item (service or product) on an invoice.",
+ "docs_url": "https://docs.api.cliniko.com/openapi/invoice-item",
+ "columns": _columns(
+ name="Name of the line item.",
+ code="Billing code for the line item.",
+ quantity="Quantity of the line item.",
+ unit_price="Price per unit before tax and discounts.",
+ discount_percentage="Discount percentage applied to the line item.",
+ discounted_amount="Discount amount applied to the line item.",
+ net_price="Net price of the line item, excluding tax.",
+ tax_name="Name of the tax applied to the line item.",
+ tax_rate="Tax rate applied to the line item.",
+ tax_amount="Tax amount applied to the line item.",
+ total_including_tax="Total price of the line item, including tax.",
+ is_monetary_discount="Whether the discount is a fixed amount rather than a percentage.",
+ deleted_at="Time the record was deleted, or null if not deleted.",
+ ),
+ },
+ "treatment_notes": {
+ "description": "A clinical treatment note recorded for a patient's appointment.",
+ "docs_url": "https://docs.api.cliniko.com/openapi/treatment-note",
+ "columns": _columns(
+ title="Title of the treatment note.",
+ content="Content of the treatment note.",
+ author_name="Name of the person who authored the treatment note.",
+ draft="Whether the treatment note is still a draft.",
+ finalized_at="Time the treatment note was finalized, or null if still a draft.",
+ pinned_at="Time the treatment note was pinned to the patient's record, or null if not pinned.",
+ deleted_at="Time the record was deleted, or null if not deleted.",
+ ),
+ },
+ "appointment_types": {
+ "description": "A configurable type of appointment (e.g. Initial Consultation), with duration and pricing defaults.",
+ "docs_url": "https://docs.api.cliniko.com/openapi/appointment-type",
+ "columns": _columns(
+ name="Name of the appointment type.",
+ description="Description of the appointment type, shown for online bookings.",
+ category="Category the appointment type belongs to.",
+ color="Colour used to represent the appointment type in the calendar.",
+ duration_in_minutes="Default duration of the appointment type, in minutes.",
+ max_attendees="Maximum number of attendees allowed for the appointment type.",
+ show_in_online_bookings="Whether the appointment type is available for online bookings.",
+ telehealth_enabled="Whether the appointment type supports telehealth.",
+ online_payments_enabled="Whether online payment is enabled for the appointment type.",
+ deposit_price="Deposit price required to book the appointment type online.",
+ ),
+ },
+ "referral_sources": {
+ "description": "How a patient was referred to the practice (e.g. a referring doctor or marketing channel).",
+ "docs_url": "https://docs.api.cliniko.com/openapi/referral-source",
+ "columns": _columns(
+ referrer="Name of the referrer.",
+ referrer_type="Type of the referrer.",
+ subcategory="Subcategory of the referral source.",
+ notes="Free-text notes about the referral source.",
+ ),
+ },
+ "products": {
+ "description": "A stock item (e.g. retail product) that can be sold or used in appointments.",
+ "docs_url": "https://docs.api.cliniko.com/openapi/product",
+ "columns": _columns(
+ name="Name of the product.",
+ item_code="Item code for the product.",
+ serial_number="Serial number of the product.",
+ cost_price="Cost price of the product.",
+ price_ex_tax="Sale price of the product, excluding tax.",
+ price_including_tax="Sale price of the product, including tax.",
+ stock_level="Current stock level of the product.",
+ notes="Free-text notes about the product.",
+ ),
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cliniko/cliniko.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cliniko/cliniko.py
new file mode 100644
index 000000000000..0afe1b619148
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cliniko/cliniko.py
@@ -0,0 +1,183 @@
+import re
+import base64
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.cliniko.settings import (
+ PAGE_SIZE,
+ PARTITION_KEY,
+ PRIMARY_KEY,
+)
+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.rest_source import (
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ JSONResponsePaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ ClientConfig,
+ EndpointResource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+
+CLINIKO_API_VERSION = "v1"
+
+# The characters after the last "-" in an API key are the shard it must be called against
+# (https://docs.api.cliniko.com/guides/sharding) — keys minted before sharding existed carry no
+# suffix and default to au1.
+_SHARD_SUFFIX_RE = re.compile(r"-([a-zA-Z]{2}\d{1,2})$")
+_DEFAULT_SHARD = "au1"
+
+# Cliniko blocks requests without a descriptive User-Agent of the form "APP_NAME (email)".
+USER_AGENT = "PostHog Data Warehouse ([email protected])"
+
+# Sentinel lower bound for the `updated_at` filter on the first incremental sync (or full
+# refresh), well before Cliniko existed. Using it unconditionally means the filter is always
+# present when incremental sync is on, instead of special-casing "no watermark yet".
+EPOCH_START = "1970-01-01T00:00:00Z"
+
+
+@frozen
+class ClinikoResumeConfig:
+ next_url: str
+
+
+def shard_from_api_key(api_key: str) -> str:
+ match = _SHARD_SUFFIX_RE.search(api_key)
+ return match.group(1).lower() if match else _DEFAULT_SHARD
+
+
+def base_url(api_key: str) -> str:
+ return f"https://api.{shard_from_api_key(api_key)}.cliniko.com/{CLINIKO_API_VERSION}"
+
+
+def _to_iso8601(value: Any) -> str:
+ if isinstance(value, datetime):
+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)
+ return aware.astimezone(UTC).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 _updated_at_filter() -> dict[str, Any]:
+ return {
+ "type": "incremental",
+ "cursor_path": "updated_at",
+ "initial_value": EPOCH_START,
+ "convert": lambda value: f"updated_at:>{_to_iso8601(value)}",
+ }
+
+
+def get_resource(name: str, should_use_incremental_field: bool) -> EndpointResource:
+ return {
+ "name": name,
+ "table_name": name,
+ "write_disposition": {"disposition": "merge", "strategy": "upsert"}
+ if should_use_incremental_field
+ else "replace",
+ "endpoint": {
+ "data_selector": name,
+ "path": f"/{name}",
+ "params": {
+ "per_page": PAGE_SIZE,
+ "sort": "updated_at:asc" if should_use_incremental_field else "created_at:asc",
+ "q[]": _updated_at_filter() if should_use_incremental_field else None,
+ },
+ },
+ "table_format": "delta",
+ }
+
+
+def _client_config(api_key: str) -> ClientConfig:
+ return {
+ "base_url": base_url(api_key),
+ "headers": {"Accept": "application/json", "User-Agent": USER_AGENT},
+ # Cliniko API keys are used as the basic-auth username with an empty password.
+ "auth": {"type": "http_basic", "username": api_key, "password": ""},
+ # Cliniko's `links.next` is a full, ready-to-follow URL, so a JSON-body next-URL
+ # paginator (rather than manual page counting) fits this and resumes for free.
+ "paginator": JSONResponsePaginator(next_url_path="links.next"),
+ # Pin every request to base_url's host and refuse redirects: the Basic auth header
+ # carries the Cliniko API key, so a spoofed `links.next` target or a cross-origin 3xx
+ # must not carry that credential off-host (SSRF). `allowed_hosts=[]` means "same host
+ # as base_url only" and also pins paginator and resume URLs.
+ "allowed_hosts": [],
+ "allow_redirects": False,
+ # `capture=False`: rows carry clinical PII (patient records, treatment notes, invoices)
+ # the name-based sample scrubbers aren't built to catch, so keep them out of HTTP
+ # diagnostic sample storage entirely, same as the other PII/free-text sources.
+ "session": make_tracked_session(redact_values=(api_key,), capture=False),
+ }
+
+
+def cliniko_source(
+ api_key: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[ClinikoResumeConfig],
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Optional[Any],
+) -> SourceResponse:
+ config: RESTAPIConfig = {
+ "client": _client_config(api_key),
+ "resource_defaults": {
+ "write_disposition": {
+ "disposition": "merge",
+ "strategy": "upsert",
+ }
+ if should_use_incremental_field
+ else "replace",
+ },
+ "resources": [get_resource(endpoint, should_use_incremental_field)],
+ }
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume_config = resumable_source_manager.load_state()
+ if resume_config is not None:
+ initial_paginator_state = {"next_url": resume_config.next_url}
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # Only persist when there's a next page to resume to; the Redis TTL handles cleanup on
+ # completion.
+ if state and state.get("next_url"):
+ resumable_source_manager.save_state(ClinikoResumeConfig(next_url=str(state["next_url"])))
+
+ resource = rest_api_resource(
+ config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+ return SourceResponse(
+ name=resource.name,
+ items=lambda: resource,
+ primary_keys=PRIMARY_KEY,
+ partition_mode="datetime",
+ partition_format="month",
+ partition_keys=[PARTITION_KEY],
+ column_hints=resource.column_hints,
+ )
+
+
+def validate_credentials(api_key: str) -> bool:
+ basic_token = base64.b64encode(f"{api_key}:".encode("ascii")).decode("ascii")
+ res = make_tracked_session(redact_values=(api_key,)).get(
+ f"{base_url(api_key)}/patients?per_page=1",
+ headers={
+ "Authorization": f"Basic {basic_token}",
+ "Accept": "application/json",
+ "User-Agent": USER_AGENT,
+ },
+ )
+ return res.status_code == 200
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cliniko/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cliniko/settings.py
new file mode 100644
index 000000000000..b494e97f9399
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cliniko/settings.py
@@ -0,0 +1,42 @@
+"""Cliniko source settings and constants."""
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# Every endpoint here is a top-level list resource returning `{<name>: [...], total_entries, links}`,
+# with `id` / `created_at` / `updated_at` on every record (per the Cliniko OpenAPI spec at
+# https://docs.api.cliniko.com/openapi). `bookings` (a union of appointments + unavailable blocks) is
+# deliberately left out, since it would just duplicate `individual_appointments`/`group_appointments`.
+ENDPOINTS = (
+ "appointment_types",
+ "attendees",
+ "businesses",
+ "group_appointments",
+ "individual_appointments",
+ "invoice_items",
+ "invoices",
+ "patients",
+ "practitioners",
+ "products",
+ "referral_sources",
+ "treatment_notes",
+)
+
+# Every endpoint's records carry a `created_at` that never changes after creation, so it's a
+# stable partition key even though sync watermarks on `updated_at`.
+PARTITION_KEY = "created_at"
+
+PRIMARY_KEY = ["id"]
+
+PAGE_SIZE = 100
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: [
+ {
+ "label": "updated_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "updated_at",
+ "field_type": IncrementalFieldType.DateTime,
+ }
+ ]
+ for name in ENDPOINTS
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cliniko/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cliniko/source.py
index 3cbb9229ba9c..e827084c239a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cliniko/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cliniko/source.py
@@ -1,13 +1,34 @@
-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.sources.cliniko.cliniko import (
+ ClinikoResumeConfig,
+ cliniko_source,
+ validate_credentials as validate_cliniko_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.cliniko.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+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,
+ build_endpoint_schemas,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.cliniko import (
ClinikoSourceConfig,
)
@@ -15,18 +36,95 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class ClinikoSource(SimpleSource[ClinikoSourceConfig]):
+class ClinikoSource(ResumableSource[ClinikoSourceConfig, ClinikoResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ api_docs_url = "https://docs.api.cliniko.com/"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.CLINIKO
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": "Cliniko authentication failed. Please check your API key.",
+ "403 Client Error": "Cliniko authentication failed. Please check your API key's permissions.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.cliniko.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: ClinikoSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+
+ def validate_credentials(
+ self,
+ config: ClinikoSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ if validate_cliniko_credentials(config.api_key):
+ return True, None
+
+ return False, "Invalid credentials"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ClinikoResumeConfig]:
+ return ResumableSourceManager[ClinikoResumeConfig](inputs, ClinikoResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: ClinikoSourceConfig,
+ resumable_source_manager: ResumableSourceManager[ClinikoResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return cliniko_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ 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,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.CLINIKO,
category=DataWarehouseSourceCategory.PRODUCTIVITY,
+ releaseStatus=ReleaseStatus.ALPHA,
label="Cliniko",
+ caption="Enter your Cliniko API key. You can generate one from your Cliniko account "
+ "under **My Info > API Keys**. The clinic's region (shard) is detected automatically "
+ "from the key.",
+ docsUrl="https://posthog.com/docs/cdp/sources/cliniko",
iconPath="/static/services/cliniko.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ keywords=["clinic", "practice management", "allied health"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cliniko/tests/test_cliniko.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cliniko/tests/test_cliniko.py
new file mode 100644
index 000000000000..11962ad39973
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cliniko/tests/test_cliniko.py
@@ -0,0 +1,239 @@
+import json
+from collections.abc import Iterable
+from datetime import UTC, date, datetime
+from typing import Any, cast
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from requests import Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.cliniko.cliniko import (
+ ClinikoResumeConfig,
+ _to_iso8601,
+ base_url,
+ cliniko_source,
+ get_resource,
+ shard_from_api_key,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import Endpoint
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+
+class TestShardDetection:
+ @pytest.mark.parametrize(
+ ("api_key", "expected_shard"),
+ [
+ ("MS0xLWl4SzYYYYdtR3V2-au1", "au1"),
+ ("MS0xLWl4SzYYYYdtR3V2-uk1", "uk1"),
+ ("MS0xLWl4SzYYYYdtR3V2-ca1", "ca1"),
+ ("MS0xLWl4SzYYYYdtR3V2-us12", "us12"),
+ # Keys minted before sharding existed carry no suffix and default to au1.
+ ("MS0xLWl4SzYYYYdtR3V2", "au1"),
+ # A hyphen that isn't a valid shard suffix (e.g. inside a UUID-like key) is ignored.
+ ("some-key-without-a-shard", "au1"),
+ ],
+ )
+ def test_shard_from_api_key(self, api_key: str, expected_shard: str) -> None:
+ assert shard_from_api_key(api_key) == expected_shard
+
+ def test_base_url_derives_from_shard(self) -> None:
+ assert base_url("test-key-uk1") == "https://api.uk1.cliniko.com/v1"
+ assert base_url("test-key") == "https://api.au1.cliniko.com/v1"
+
+
+class TestToIso8601:
+ def test_naive_datetime_treated_as_utc(self) -> None:
+ assert _to_iso8601(datetime(2024, 1, 2, 3, 4, 5)) == "2024-01-02T03:04:05Z"
+
+ def test_aware_datetime_converted_to_utc(self) -> None:
+ from datetime import timedelta, timezone
+
+ aware = datetime(2024, 1, 2, 13, 0, 0, tzinfo=timezone(timedelta(hours=10)))
+ assert _to_iso8601(aware) == "2024-01-02T03:00:00Z"
+
+ def test_date_becomes_midnight_utc(self) -> None:
+ assert _to_iso8601(date(2024, 1, 2)) == "2024-01-02T00:00:00Z"
+
+ def test_passthrough_string(self) -> None:
+ assert _to_iso8601("2024-01-02T03:04:05Z") == "2024-01-02T03:04:05Z"
+
+
+class TestGetResource:
+ def test_full_refresh_has_no_filter_and_replace_disposition(self) -> None:
+ resource = get_resource("patients", should_use_incremental_field=False)
+
+ assert resource["name"] == "patients"
+ assert resource["write_disposition"] == "replace"
+ # `EndpointResource.endpoint` is typed `str | Endpoint | None`; `get_resource` always sets
+ # a dict, so the cast makes that runtime shape explicit for indexing below.
+ endpoint = cast(Endpoint, resource["endpoint"])
+ assert endpoint["path"] == "/patients"
+ assert endpoint["data_selector"] == "patients"
+ # `endpoint["params"]` is typed `Optional[dict[...]]`; `get_resource` always sets one, so
+ # the cast makes that runtime shape explicit for indexing below.
+ params = cast(dict[str, Any], endpoint["params"])
+ assert params["q[]"] is None
+ assert params["sort"] == "created_at:asc"
+
+ def test_incremental_sets_merge_disposition_and_filter(self) -> None:
+ resource = get_resource("invoices", should_use_incremental_field=True)
+
+ assert resource["write_disposition"] == {"disposition": "merge", "strategy": "upsert"}
+ endpoint = cast(Endpoint, resource["endpoint"])
+ params = cast(dict[str, Any], endpoint["params"])
+ assert params["sort"] == "updated_at:asc"
+ # `params` values are typed as a resolve/incremental/Any union, so the
+ # cast makes the runtime shape (an incremental filter dict, including `convert`) explicit.
+ q_filter = cast(dict[str, Any], params["q[]"])
+ assert q_filter["type"] == "incremental"
+ assert q_filter["convert"](datetime(2024, 1, 1, tzinfo=UTC)) == "updated_at:>2024-01-01T00:00:00Z"
+
+
+def _make_http_response(body: dict[str, Any], status_code: int = 200) -> Response:
+ resp = Response()
+ resp.status_code = status_code
+ resp._content = json.dumps(body).encode()
+ resp.headers["Content-Type"] = "application/json"
+ return resp
+
+
+class TestClinikoSourceResumeBehavior:
+ """End-to-end resume behaviour of ``cliniko_source`` via ``rest_api_resource``."""
+
+ def _drive(
+ self, endpoint: str, manager: MagicMock, responses: list[Response], should_use_incremental_field: bool = False
+ ) -> tuple[list[str], list[dict[str, Any]]]:
+ """Drive ``cliniko_source`` with a mocked HTTP session.
+
+ Returns ``(sent_urls, sent_params)`` captured at send-time — the underlying Request
+ object is mutated in-place by the paginator between pages.
+ """
+ sent_urls: list[str] = []
+ sent_params: list[dict[str, Any]] = []
+ response_iter = iter(responses)
+
+ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:
+ sent_urls.append(request.url)
+ sent_params.append(dict(request.params or {}))
+ return next(response_iter)
+
+ # `_client_config` now passes an explicit `capture=False` session (see the module docstring
+ # on why), so the session comes from cliniko's own `make_tracked_session` import rather than
+ # `RESTClient`'s internal default.
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.cliniko.cliniko.make_tracked_session"
+ ) as MockSession:
+ mock_session = MockSession.return_value
+ mock_session.headers = {}
+ mock_session.prepare_request.side_effect = lambda req: req
+ mock_session.send.side_effect = fake_send
+
+ source_response = cliniko_source(
+ api_key="test-key-au1",
+ endpoint=endpoint,
+ team_id=123,
+ job_id="test_job",
+ resumable_source_manager=manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=None,
+ )
+ list(cast(Iterable[Any], source_response.items()))
+ return sent_urls, sent_params
+
+ def test_fresh_run_follows_links_next_and_saves_state(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [
+ _make_http_response(
+ {
+ "patients": [{"id": "1"}],
+ "links": {"next": "https://api.au1.cliniko.com/v1/patients?page=2"},
+ }
+ ),
+ _make_http_response(
+ {
+ "patients": [{"id": "2"}],
+ "links": {"next": "https://api.au1.cliniko.com/v1/patients?page=3"},
+ }
+ ),
+ _make_http_response({"patients": [{"id": "3"}], "links": {}}),
+ ]
+ sent_urls, sent_params = self._drive("patients", manager, responses)
+
+ # The first request is built from the endpoint config (path + params); the
+ # paginator only takes over the URL once a `links.next` has been seen.
+ assert sent_urls == [
+ "https://api.au1.cliniko.com/v1/patients",
+ "https://api.au1.cliniko.com/v1/patients?page=2",
+ "https://api.au1.cliniko.com/v1/patients?page=3",
+ ]
+ assert sent_params[0] == {"per_page": 100, "sort": "created_at:asc"}
+ # Subsequent requests carry no separate params — the next-page URL is self-contained.
+ assert sent_params[1] == {}
+ assert sent_params[2] == {}
+
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [
+ ClinikoResumeConfig(next_url="https://api.au1.cliniko.com/v1/patients?page=2"),
+ ClinikoResumeConfig(next_url="https://api.au1.cliniko.com/v1/patients?page=3"),
+ ]
+
+ def test_resume_seeds_paginator_with_saved_next_url(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = ClinikoResumeConfig(next_url="https://api.au1.cliniko.com/v1/patients?page=5")
+
+ responses = [_make_http_response({"patients": [{"id": "resumed"}], "links": {}})]
+ sent_urls, _ = self._drive("patients", manager, responses)
+
+ assert sent_urls == ["https://api.au1.cliniko.com/v1/patients?page=5"]
+ manager.load_state.assert_called_once()
+
+ def test_terminal_single_page_does_not_save_state(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [_make_http_response({"patients": [{"id": "only"}], "links": {}})]
+ self._drive("patients", manager, responses)
+
+ manager.save_state.assert_not_called()
+
+ def test_incremental_run_sends_updated_at_filter(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [_make_http_response({"invoices": [{"id": "1"}], "links": {}})]
+ _, sent_params = self._drive("invoices", manager, responses, should_use_incremental_field=True)
+
+ assert sent_params[0]["q[]"] == "updated_at:>1970-01-01T00:00:00Z"
+ assert sent_params[0]["sort"] == "updated_at:asc"
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(("status_code", "expected"), [(200, True), (401, False), (403, False), (429, False)])
+ def test_status_code_maps_to_validity(self, status_code: int, expected: bool) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.cliniko.cliniko.make_tracked_session"
+ ) as mock_make_session:
+ mock_session = mock_make_session.return_value
+ mock_session.get.return_value = MagicMock(status_code=status_code)
+
+ assert validate_credentials("test-key-au1") is expected
+
+ def test_request_carries_required_headers_and_shard_url(self) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.cliniko.cliniko.make_tracked_session"
+ ) as mock_make_session:
+ mock_session = mock_make_session.return_value
+ mock_session.get.return_value = MagicMock(status_code=200)
+
+ validate_credentials("test-key-uk1")
+
+ args, kwargs = mock_session.get.call_args
+ assert args[0] == "https://api.uk1.cliniko.com/v1/patients?per_page=1"
+ assert kwargs["headers"]["Accept"] == "application/json"
+ assert "PostHog" in kwargs["headers"]["User-Agent"]
+ assert kwargs["headers"]["Authorization"].startswith("Basic ")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cliniko/tests/test_cliniko_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cliniko/tests/test_cliniko_source.py
new file mode 100644
index 000000000000..3ec120abc040
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cliniko/tests/test_cliniko_source.py
@@ -0,0 +1,161 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.cliniko.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.cliniko.cliniko import ClinikoResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.cliniko.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.cliniko.source import ClinikoSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.cliniko import (
+ ClinikoSourceConfig,
+)
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestClinikoSource:
+ def setup_method(self) -> None:
+ self.source = ClinikoSource()
+ self.team_id = 123
+ self.config = ClinikoSourceConfig(api_key="test-key-au1")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.CLINIKO
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.name.value == "Cliniko"
+ assert config.label == "Cliniko"
+ assert config.category == DataWarehouseSourceCategory.PRODUCTIVITY
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ # A finished source ships visible — no unreleasedSource flag hiding it.
+ assert config.unreleasedSource is None
+ assert config.iconPath == "/static/services/cliniko.png"
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/cliniko"
+
+ 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
+ api_key_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")
+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key_field.secret is True
+ assert api_key_field.required is True
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.au1.cliniko.com/v1/patients?per_page=1",
+ "403 Client Error: Forbidden for url: https://api.au1.cliniko.com/v1/patients?per_page=1",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ @pytest.mark.parametrize(
+ "other_error",
+ [
+ "429 Client Error: Too Many Requests for url: https://api.au1.cliniko.com/v1/patients",
+ "500 Server Error: Internal Server Error for url: https://api.au1.cliniko.com/v1/patients",
+ "HTTPSConnectionPool(host='api.au1.cliniko.com', port=443): Read timed out.",
+ ],
+ )
+ def test_non_retryable_errors_do_not_match_transient(self, other_error: str) -> None:
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(key in other_error for key in non_retryable_errors)
+
+ def test_get_schemas_match_endpoints_and_support_incremental(self) -> None:
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+
+ assert set(schemas) == set(ENDPOINTS)
+ for name in ENDPOINTS:
+ assert schemas[name].supports_incremental is True
+ assert schemas[name].supports_append is True
+ assert [f["field"] for f in schemas[name].incremental_fields] == ["updated_at"]
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["patients"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "patients"
+
+ 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_lists_tables_without_credentials_publishes_catalog(self) -> None:
+ # Static endpoint catalog (no I/O) — the public docs table list should render.
+ assert self.source.lists_tables_without_credentials is True
+ documented = self.source.get_documented_tables()
+ assert {table["name"] for table in documented} == set(ENDPOINTS)
+
+ def test_canonical_descriptions_cover_every_endpoint(self) -> None:
+ assert self.source.get_canonical_descriptions() is CANONICAL_DESCRIPTIONS
+ assert set(CANONICAL_DESCRIPTIONS) == set(ENDPOINTS)
+
+ @pytest.mark.parametrize(
+ ("mock_return", "expected_valid", "expected_message"),
+ [
+ (True, True, None),
+ (False, False, "Invalid credentials"),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.cliniko.source.validate_cliniko_credentials"
+ )
+ def test_validate_credentials(
+ self, mock_validate: mock.MagicMock, mock_return: bool, expected_valid: bool, expected_message: str | None
+ ) -> None:
+ mock_validate.return_value = mock_return
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is expected_valid
+ assert error_message == expected_message
+ mock_validate.assert_called_once_with("test-key-au1")
+
+ def test_get_resumable_source_manager_bound_to_resume_config(self) -> None:
+ inputs = mock.MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+ assert manager._data_class is ClinikoResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.cliniko.source.cliniko_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_cliniko_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "invoices"
+ inputs.team_id = self.team_id
+ inputs.job_id = "job-1"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_cliniko_source.assert_called_once()
+ kwargs = mock_cliniko_source.call_args.kwargs
+ assert kwargs["api_key"] == "test-key-au1"
+ assert kwargs["endpoint"] == "invoices"
+ assert kwargs["team_id"] == self.team_id
+ assert kwargs["job_id"] == "job-1"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.cliniko.source.cliniko_source")
+ def test_source_for_pipeline_omits_cursor_when_not_incremental(self, mock_cliniko_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "patients"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_cliniko_source.call_args.kwargs["db_incremental_field_last_value"] is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/cliniko.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/cliniko.py
index 8e889fd69cab..27e531d87d2d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/cliniko.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/cliniko.py
@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class ClinikoSourceConfig(config.Config):
- pass
+ api_key: str