Skip to content

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

feat(data-warehouse): implement clockodo import source (#66743)

Tom Owers814e1eb504c3
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 83f4c5e2edb6..ad7598147554 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -109,6 +109,7 @@ the row lists both.
| clickhouse | DB protocol (HTTP-based) | clickhouse-connect / clickhouse-driver | ➖ |
| clickup | HTTP | requests | ✅ |
| clockify | HTTP | requests | ✅ |
+| clockodo | HTTP | requests | ✅ |
| close | HTTP | requests + `rest_source.RESTClient` | ✅ |
| convertkit | HTTP | requests | ✅ |
| convex | HTTP | requests | ✅ |
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clockodo/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clockodo/canonical_descriptions.py
new file mode 100644
index 000000000000..818767f6677d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clockodo/canonical_descriptions.py
@@ -0,0 +1,101 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Descriptions sourced from the official Clockodo API documentation
+# (https://www.clockodo.com/en/api/). Partial coverage is fine — anything not listed falls back
+# to LLM enrichment, which is given the docs_url and column data types.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "customers": {
+ "description": "Customers (companies/clients) that work is tracked against.",
+ "docs_url": "https://www.clockodo.com/en/api/customers/",
+ "columns": {
+ "id": "Unique identifier of the customer.",
+ "name": "Name of the customer.",
+ "number": "Free-text customer number.",
+ "active": "Whether the customer is active.",
+ "billable_default": "Default billability for new projects of this customer.",
+ "note": "Free-text note on the customer.",
+ },
+ },
+ "projects": {
+ "description": "Projects belonging to customers; the unit time entries are booked to.",
+ "docs_url": "https://www.clockodo.com/en/api/projects/",
+ "columns": {
+ "id": "Unique identifier of the project.",
+ "name": "Name of the project.",
+ "number": "Free-text project number.",
+ "customers_id": "Identifier of the customer this project belongs to.",
+ "active": "Whether the project is active.",
+ "billable_default": "Default billability for new entries of this project.",
+ "budget_money": "Money budget for the project.",
+ "completed": "Whether the project has been marked completed.",
+ },
+ },
+ "services": {
+ "description": "Services (types of work) that can be booked on time entries.",
+ "docs_url": "https://www.clockodo.com/en/api/services/",
+ "columns": {
+ "id": "Unique identifier of the service.",
+ "name": "Name of the service.",
+ "number": "Free-text service number.",
+ "active": "Whether the service is active.",
+ },
+ },
+ "lumpsum_services": {
+ "description": "Lump-sum (flat-rate) services that can be booked as fixed-price entries.",
+ "docs_url": "https://www.clockodo.com/en/api/lumpsum-services/",
+ "columns": {
+ "id": "Unique identifier of the lump-sum service.",
+ "name": "Name of the lump-sum service.",
+ "price": "Flat-rate price of the service.",
+ "active": "Whether the lump-sum service is active.",
+ },
+ },
+ "users": {
+ "description": "Co-workers (users) in the Clockodo account.",
+ "docs_url": "https://www.clockodo.com/en/api/users/",
+ "columns": {
+ "id": "Unique identifier of the user.",
+ "name": "Display name of the user.",
+ "email": "Email address of the user.",
+ "role": "Role of the user in the account.",
+ "active": "Whether the user is active.",
+ "number": "Free-text personnel number.",
+ },
+ },
+ "teams": {
+ "description": "Teams that users are grouped into.",
+ "docs_url": "https://www.clockodo.com/en/api/teams/",
+ "columns": {
+ "id": "Unique identifier of the team.",
+ "name": "Name of the team.",
+ },
+ },
+ "surcharges": {
+ "description": "Surcharge rules (e.g. night/weekend premiums) configured in the account.",
+ "docs_url": "https://www.clockodo.com/en/api/surcharges/",
+ "columns": {
+ "id": "Unique identifier of the surcharge rule.",
+ "name": "Name of the surcharge rule.",
+ },
+ },
+ "entries": {
+ "description": "Time and lump-sum entries — the individual tracked records of work.",
+ "docs_url": "https://www.clockodo.com/en/api/entries/",
+ "columns": {
+ "id": "Unique identifier of the entry.",
+ "customers_id": "Identifier of the customer the entry is booked to.",
+ "projects_id": "Identifier of the project the entry is booked to.",
+ "services_id": "Identifier of the service the entry is booked to.",
+ "users_id": "Identifier of the user who created the entry.",
+ "billable": "Billability of the entry.",
+ "text": "Free-text description of the entry.",
+ "time_since": "Start time of the entry (ISO 8601).",
+ "time_until": "End time of the entry (ISO 8601).",
+ "duration": "Duration of the entry in seconds.",
+ "time_insert": "Time the entry was created (ISO 8601).",
+ "time_last_change": "Time the entry was last modified (ISO 8601).",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clockodo/clockodo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clockodo/clockodo.py
new file mode 100644
index 000000000000..310f14f2b890
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clockodo/clockodo.py
@@ -0,0 +1,186 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.batcher import Batcher
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.clockodo.settings import (
+ CLOCKODO_ENDPOINTS,
+ ENTRIES_TIME_SINCE,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+# Clockodo's API is hosted at a single fixed host for every account (no per-tenant subdomain).
+CLOCKODO_BASE_URL = "https://my.clockodo.com/api"
+
+# Clockodo identifies the calling application via a mandatory header formatted
+# "[application name];[email address]". We send our app name plus the connecting user's email.
+EXTERNAL_APPLICATION_NAME = "PostHog"
+
+REQUEST_TIMEOUT_SECONDS = 60
+
+
+class ClockodoRetryableError(Exception):
+ pass
+
+
+class ClockodoResumeConfig:
+ # Next 1-indexed page to fetch. Only meaningful for paginated endpoints.
+ next_page: int
+
+
+def _build_headers(api_user: str, api_key: str) -> dict[str, str]:
+ return {
+ "X-ClockodoApiUser": api_user,
+ "X-ClockodoApiKey": api_key,
+ "X-Clockodo-External-Application": f"{EXTERNAL_APPLICATION_NAME};{api_user}",
+ "Accept": "application/json",
+ }
+
+
+def _format_z(dt: datetime) -> str:
+ """ISO 8601 in UTC with a Z suffix, the format the entries endpoint expects."""
+ utc_dt = dt.astimezone(UTC)
+ return utc_dt.strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+@retry(
+ retry=retry_if_exception_type((ClockodoRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session,
+ url: str,
+ headers: dict[str, str],
+ params: dict[str, Any],
+ logger: FilteringBoundLogger,
+) -> dict[str, Any]:
+ response = session.get(url, headers=headers, params=params, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ # 429 (rate limit) and 5xx are transient — back off and retry.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise ClockodoRetryableError(f"Clockodo API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Clockodo API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def _endpoint_params(endpoint: str) -> dict[str, Any]:
+ config = CLOCKODO_ENDPOINTS[endpoint]
+ params: dict[str, Any] = dict(config.extra_params)
+ if endpoint == "entries":
+ # Send a wide window so every entry is in range. time_until is pushed a year past now
+ # to also capture future-dated planned entries.
+ params["time_since"] = ENTRIES_TIME_SINCE
+ params["time_until"] = _format_z(datetime.now(UTC) + timedelta(days=365))
+ return params
+
+
+def get_rows(
+ api_user: str,
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[ClockodoResumeConfig],
+) -> Iterator[Any]:
+ config = CLOCKODO_ENDPOINTS[endpoint]
+ headers = _build_headers(api_user, api_key)
+ params = _endpoint_params(endpoint)
+ url = f"{CLOCKODO_BASE_URL}/{config.path}"
+ # One session reused across every page so urllib3 keeps the connection alive.
+ # Redact the API key from logged URLs and captured samples — it travels in a custom
+ # header the name-based scrubbers don't recognise.
+ session = make_tracked_session(redact_values=(api_key,))
+ batcher = Batcher(logger=logger, chunk_size=5000, chunk_size_bytes=200 * 1024 * 1024)
+
+ if not config.paginated:
+ data = _fetch_page(session, url, headers, params, logger)
+ for item in data.get(config.data_key, []):
+ batcher.batch(item)
+ if batcher.should_yield():
+ yield batcher.get_table()
+ if batcher.should_yield(include_incomplete_chunk=True):
+ yield batcher.get_table()
+ return
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ page = resume.next_page if resume else 1
+
+ # Oldest page whose rows aren't yet in a durably-yielded batch. Resume re-fetches from here so a
+ # page's tail that hasn't been yielded is never skipped; already-yielded rows merge-dedupe on the
+ # primary key. A yield flushes every batched row, so it advances this pointer to the current page.
+ resume_page = page
+
+ while True:
+ params["page"] = page
+ data = _fetch_page(session, url, headers, params, logger)
+ items = data.get(config.data_key, [])
+
+ # The paging block tells us the total page count; missing for unpaginated responses.
+ paging = data.get("paging") or {}
+ count_pages = paging.get("count_pages", page)
+ has_more = page < count_pages and bool(items)
+
+ for item in items:
+ batcher.batch(item)
+ if batcher.should_yield():
+ yield batcher.get_table()
+ resume_page = page
+
+ # Save once per page — even when the page produced no yield — so a crash resumes near where it
+ # stopped instead of from page 1. We can only advance past pages whose rows are durably yielded,
+ # so this points at the oldest still-unflushed page.
+ resumable_source_manager.save_state(ClockodoResumeConfig(next_page=resume_page))
+
+ if not has_more:
+ break
+ page += 1
+
+ if batcher.should_yield(include_incomplete_chunk=True):
+ yield batcher.get_table()
+
+
+def clockodo_source(
+ api_user: str,
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[ClockodoResumeConfig],
+) -> SourceResponse:
+ config = CLOCKODO_ENDPOINTS[endpoint]
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_user=api_user,
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=config.primary_keys,
+ )
+
+
+def validate_credentials(api_user: str, api_key: str) -> bool:
+ """Cheap probe to confirm the API user/key pair is genuine."""
+ try:
+ response = make_tracked_session(redact_values=(api_key,)).get(
+ f"{CLOCKODO_BASE_URL}/v2/users",
+ headers=_build_headers(api_user, api_key),
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+ return response.status_code == 200
+ except Exception:
+ return False
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clockodo/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clockodo/settings.py
new file mode 100644
index 000000000000..c2cbac11c67d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clockodo/settings.py
@@ -0,0 +1,79 @@
+from dataclasses import dataclass, field
+
+from products.warehouse_sources.backend.types import IncrementalField
+
+
+@dataclass
+class ClockodoEndpointConfig:
+ name: str # schema name shown to the user (matches the warehouse table)
+ path: str # API path relative to the base URL, e.g. "v2/customers"
+ data_key: str # key in the JSON response body that holds the list of rows
+ # Clockodo only paginates a subset of resources (entries, entriesTexts, customers,
+ # projects). The rest return the full collection in a single response with no paging block.
+ paginated: bool = False
+ # Static query params required by the endpoint (e.g. the entries time window).
+ extra_params: dict[str, str] = field(default_factory=dict)
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ should_sync_default: bool = True
+ description: str | None = None
+
+
+# The /v2/entries list endpoint rejects requests without a time range, so we send a wide
+# fixed window that covers all historical entries. time_until is widened past "now" at request
+# time to also capture future-dated (planned) entries. ISO 8601 UTC, as the API requires.
+ENTRIES_TIME_SINCE = "2000-01-01T00:00:00Z"
+
+
+CLOCKODO_ENDPOINTS: dict[str, ClockodoEndpointConfig] = {
+ "customers": ClockodoEndpointConfig(
+ name="customers",
+ path="v2/customers",
+ data_key="customers",
+ paginated=True,
+ ),
+ "projects": ClockodoEndpointConfig(
+ name="projects",
+ path="v2/projects",
+ data_key="projects",
+ paginated=True,
+ ),
+ "services": ClockodoEndpointConfig(
+ name="services",
+ path="v2/services",
+ data_key="services",
+ ),
+ "lumpsum_services": ClockodoEndpointConfig(
+ name="lumpsum_services",
+ path="v2/lumpsumservices",
+ data_key="lumpSumServices",
+ ),
+ "users": ClockodoEndpointConfig(
+ name="users",
+ path="v2/users",
+ data_key="users",
+ ),
+ "teams": ClockodoEndpointConfig(
+ name="teams",
+ path="v2/teams",
+ data_key="teams",
+ ),
+ "surcharges": ClockodoEndpointConfig(
+ name="surcharges",
+ path="v2/surcharges",
+ data_key="surcharges",
+ ),
+ "entries": ClockodoEndpointConfig(
+ name="entries",
+ path="v2/entries",
+ data_key="entries",
+ paginated=True,
+ description="Time entries across the full account history. Full refresh only — the API "
+ "has no server-side modified-since filter.",
+ ),
+}
+
+ENDPOINTS = tuple(CLOCKODO_ENDPOINTS.keys())
+
+# Clockodo exposes no server-side "modified since" filter on any resource (time_last_change is
+# returned but not filterable), so every table is full refresh only — no incremental fields.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: [] for name in CLOCKODO_ENDPOINTS}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clockodo/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clockodo/source.py
index 6a9c5bd4eb73..4c4a1664ccc6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clockodo/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clockodo/source.py
@@ -1,30 +1,147 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.clockodo.clockodo import (
+ ClockodoResumeConfig,
+ clockodo_source,
+ validate_credentials as validate_clockodo_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.clockodo.settings import (
+ CLOCKODO_ENDPOINTS,
+ 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
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import ClockodoSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class ClockodoSource(SimpleSource[ClockodoSourceConfig]):
+class ClockodoSource(ResumableSource[ClockodoSourceConfig, ClockodoResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.CLOCKODO
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # Clockodo returns 401 both for a bad API user/key and for a missing identification
+ # header; retrying can never fix either, so stop the sync. Match the stable status text
+ # and base host, not the per-request path.
+ "401 Client Error: Unauthorized for url: https://my.clockodo.com": "Your Clockodo email or API key is invalid. Find your API key under Personal data in Clockodo, then reconnect.",
+ "403 Client Error: Forbidden for url: https://my.clockodo.com": "Your Clockodo user does not have permission to read this data. Clockodo credentials are scoped per co-worker — check the user's permissions, then reconnect.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.clockodo.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: ClockodoSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # Clockodo exposes no server-side modified-since filter, so every table is full refresh only.
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ should_sync_default=CLOCKODO_ENDPOINTS[endpoint].should_sync_default,
+ description=CLOCKODO_ENDPOINTS[endpoint].description,
+ )
+ 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: ClockodoSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_clockodo_credentials(config.api_user, config.api_key):
+ return True, None
+
+ return False, "Invalid Clockodo credentials"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ClockodoResumeConfig]:
+ return ResumableSourceManager[ClockodoResumeConfig](inputs, ClockodoResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: ClockodoSourceConfig,
+ resumable_source_manager: ResumableSourceManager[ClockodoResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return clockodo_source(
+ api_user=config.api_user,
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.CLOCKODO,
category=DataWarehouseSourceCategory.PRODUCTIVITY,
label="Clockodo",
- iconPath="/static/services/clockodo.png",
- fields=cast(list[FieldType], []),
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ caption="""Enter your Clockodo email and API key to pull your Clockodo time-tracking data into the PostHog Data warehouse.
+
+You can find your personal API key under **Personal data** in your Clockodo account. Credentials are scoped to that co-worker's permissions, so connect a user that can see the data you want to sync.""",
+ iconPath="/static/services/clockodo.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/clockodo",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_user",
+ label="Email",
+ type=SourceFieldInputConfigType.EMAIL,
+ required=True,
+ placeholder="[email protected]",
+ secret=False,
+ ),
+ 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/clockodo/tests/test_clockodo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clockodo/tests/test_clockodo.py
new file mode 100644
index 000000000000..87cbe778ae9c
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clockodo/tests/test_clockodo.py
@@ -0,0 +1,216 @@
+from datetime import UTC, datetime
+from typing import Any
+
+from freezegun import freeze_time
+from unittest.mock import MagicMock, patch
+
+import pyarrow as pa
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.batcher import Batcher
+from products.warehouse_sources.backend.temporal.data_imports.sources.clockodo import clockodo
+from products.warehouse_sources.backend.temporal.data_imports.sources.clockodo.clockodo import (
+ EXTERNAL_APPLICATION_NAME,
+ ClockodoResumeConfig,
+ _build_headers,
+ _endpoint_params,
+ _format_z,
+ clockodo_source,
+ get_rows,
+ validate_credentials,
+)
+
+
+def _row_count(tables: list[pa.Table]) -> int:
+ return sum(t.num_rows for t in tables)
+
+
+def _ids(tables: list[pa.Table]) -> list[Any]:
+ ids: list[Any] = []
+ for t in tables:
+ ids.extend(t.column("id").to_pylist())
+ return ids
+
+
+class TestHeaders:
+ def test_includes_mandatory_external_application_header(self) -> None:
+ headers = _build_headers("[email protected]", "key123")
+ assert headers["X-ClockodoApiUser"] == "[email protected]"
+ assert headers["X-ClockodoApiKey"] == "key123"
+ # The API rejects every request without this identification header.
+ assert headers["X-Clockodo-External-Application"] == f"{EXTERNAL_APPLICATION_NAME};[email protected]"
+
+
+class TestFormatZ:
+ @parameterized.expand(
+ [
+ ("utc", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14Z"),
+ ("with_micros_truncated", datetime(2026, 1, 15, 10, 30, 45, 123456, tzinfo=UTC), "2026-01-15T10:30:45Z"),
+ ]
+ )
+ def test_format_z(self, _name: str, value: datetime, expected: str) -> None:
+ assert _format_z(value) == expected
+
+
+class TestEndpointParams:
+ @freeze_time("2026-06-29T12:00:00Z")
+ def test_entries_requires_time_window(self) -> None:
+ params = _endpoint_params("entries")
+ # Listing entries without a time range is rejected by the API.
+ assert params["time_since"] == "2000-01-01T00:00:00Z"
+ # time_until is pushed a year past now to also capture planned (future) entries.
+ assert params["time_until"] == "2027-06-29T12:00:00Z"
+
+ @parameterized.expand([("customers",), ("projects",), ("services",), ("users",)])
+ def test_non_entries_have_no_time_window(self, endpoint: str) -> None:
+ params = _endpoint_params(endpoint)
+ assert "time_since" not in params
+ assert "time_until" not in params
+
+
+# Force a 1-row chunk so every row yields a table — exercises the resume save path.
+def _patch_small_batcher() -> Any:
+ def _factory(*_args: Any, logger: Any = None, **_kwargs: Any) -> Batcher:
+ return Batcher(logger=logger or MagicMock(), chunk_size=1, chunk_size_bytes=10**12)
+
+ return patch.object(clockodo, "Batcher", side_effect=_factory)
+
+
+class TestGetRows:
+ def test_paginated_walks_all_pages_and_saves_state(self) -> None:
+ pages = {
+ 1: {"paging": {"count_pages": 2}, "customers": [{"id": 1}, {"id": 2}]},
+ 2: {"paging": {"count_pages": 2}, "customers": [{"id": 3}]},
+ }
+ seen_pages: list[int] = []
+
+ def fake_fetch(_session: Any, _url: str, _headers: Any, params: dict, _logger: Any) -> dict:
+ seen_pages.append(params["page"])
+ return pages[params["page"]]
+
+ manager = MagicMock()
+ manager.can_resume.return_value = False
+
+ with (
+ patch.object(clockodo, "make_tracked_session", return_value=MagicMock()),
+ patch.object(clockodo, "_fetch_page", side_effect=fake_fetch),
+ _patch_small_batcher(),
+ ):
+ tables = list(get_rows("u", "k", "customers", MagicMock(), manager))
+
+ assert seen_pages == [1, 2]
+ assert _ids(tables) == [1, 2, 3]
+ # State is saved once per page, pointing at the oldest unflushed page (the page being
+ # processed here, since every row yields), so a crash re-fetches it rather than skipping its tail.
+ saved = [c.args[0].next_page for c in manager.save_state.call_args_list]
+ assert saved == [1, 2]
+
+ def test_paginated_saves_state_per_page_even_without_a_yield(self) -> None:
+ # Realistic batcher: pages are far under the chunk threshold, so nothing yields mid-walk.
+ # State must still be saved once per page (pointing at page 1, the oldest unflushed page)
+ # so a crash resumes near where it stopped rather than always from page 1.
+ pages = {
+ 1: {"paging": {"count_pages": 2}, "customers": [{"id": 1}, {"id": 2}]},
+ 2: {"paging": {"count_pages": 2}, "customers": [{"id": 3}]},
+ }
+
+ def fake_fetch(_session: Any, _url: str, _headers: Any, params: dict, _logger: Any) -> dict:
+ return pages[params["page"]]
+
+ manager = MagicMock()
+ manager.can_resume.return_value = False
+
+ with (
+ patch.object(clockodo, "make_tracked_session", return_value=MagicMock()),
+ patch.object(clockodo, "_fetch_page", side_effect=fake_fetch),
+ ):
+ tables = list(get_rows("u", "k", "customers", MagicMock(), manager))
+
+ assert _ids(tables) == [1, 2, 3]
+ saved = [c.args[0].next_page for c in manager.save_state.call_args_list]
+ assert saved == [1, 1]
+
+ def test_resumes_from_saved_page(self) -> None:
+ pages = {2: {"paging": {"count_pages": 2}, "customers": [{"id": 3}]}}
+ seen_pages: list[int] = []
+
+ def fake_fetch(_session: Any, _url: str, _headers: Any, params: dict, _logger: Any) -> dict:
+ seen_pages.append(params["page"])
+ return pages[params["page"]]
+
+ manager = MagicMock()
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = ClockodoResumeConfig(next_page=2)
+
+ with (
+ patch.object(clockodo, "make_tracked_session", return_value=MagicMock()),
+ patch.object(clockodo, "_fetch_page", side_effect=fake_fetch),
+ _patch_small_batcher(),
+ ):
+ tables = list(get_rows("u", "k", "customers", MagicMock(), manager))
+
+ # Picks up at the saved page rather than restarting at page 1.
+ assert seen_pages == [2]
+ assert _ids(tables) == [3]
+
+ def test_non_paginated_single_fetch(self) -> None:
+ seen_params: list[dict] = []
+
+ def fake_fetch(_session: Any, _url: str, _headers: Any, params: dict, _logger: Any) -> dict:
+ seen_params.append(dict(params))
+ return {"services": [{"id": 1}, {"id": 2}]}
+
+ manager = MagicMock()
+ manager.can_resume.return_value = False
+
+ with (
+ patch.object(clockodo, "make_tracked_session", return_value=MagicMock()),
+ patch.object(clockodo, "_fetch_page", side_effect=fake_fetch),
+ _patch_small_batcher(),
+ ):
+ tables = list(get_rows("u", "k", "services", MagicMock(), manager))
+
+ assert len(seen_params) == 1
+ # Non-paginated endpoints never send a page param.
+ assert "page" not in seen_params[0]
+ assert _ids(tables) == [1, 2]
+ manager.save_state.assert_not_called()
+
+ def test_empty_response_yields_nothing(self) -> None:
+ def fake_fetch(_session: Any, _url: str, _headers: Any, params: dict, _logger: Any) -> dict:
+ return {"paging": {"count_pages": 1}, "customers": []}
+
+ manager = MagicMock()
+ manager.can_resume.return_value = False
+
+ with (
+ patch.object(clockodo, "make_tracked_session", return_value=MagicMock()),
+ patch.object(clockodo, "_fetch_page", side_effect=fake_fetch),
+ _patch_small_batcher(),
+ ):
+ tables = list(get_rows("u", "k", "customers", MagicMock(), manager))
+
+ assert _row_count(tables) == 0
+
+
+class TestClockodoSourceResponse:
+ @parameterized.expand([("customers",), ("entries",), ("users",)])
+ def test_primary_keys_default_to_id(self, endpoint: str) -> None:
+ response = clockodo_source("u", "k", endpoint, MagicMock(), MagicMock())
+ assert response.name == endpoint
+ assert response.primary_keys == ["id"]
+
+
+class TestValidateCredentials:
+ @parameterized.expand([("ok", 200, True), ("unauthorized", 401, False), ("forbidden", 403, False)])
+ def test_validate_credentials_status_mapping(self, _name: str, status: int, expected: bool) -> None:
+ session = MagicMock()
+ session.get.return_value = MagicMock(status_code=status)
+ with patch.object(clockodo, "make_tracked_session", return_value=session):
+ assert validate_credentials("u", "k") is expected
+
+ def test_validate_credentials_swallows_transport_errors(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = Exception("boom")
+ with patch.object(clockodo, "make_tracked_session", return_value=session):
+ assert validate_credentials("u", "k") is False
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clockodo/tests/test_clockodo_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clockodo/tests/test_clockodo_source.py
new file mode 100644
index 000000000000..18fd841b86e0
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clockodo/tests/test_clockodo_source.py
@@ -0,0 +1,91 @@
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.schema import DataWarehouseSourceCategory, ReleaseStatus, SourceFieldInputConfig
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.clockodo.clockodo import ClockodoResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.clockodo.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.clockodo.source import ClockodoSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import ClockodoSourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _config() -> ClockodoSourceConfig:
+ return ClockodoSourceConfig(api_user="[email protected]", api_key="secret")
+
+
+class TestClockodoSource:
+ def test_source_type(self) -> None:
+ assert ClockodoSource().source_type == ExternalDataSourceType.CLOCKODO
+
+ def test_source_config_shape(self) -> None:
+ config = ClockodoSource().get_source_config
+ assert config.category == DataWarehouseSourceCategory.PRODUCTIVITY
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/clockodo"
+ field_names = {f.name for f in config.fields}
+ assert field_names == {"api_user", "api_key"}
+
+ def test_api_key_field_is_secret(self) -> None:
+ config = ClockodoSource().get_source_config
+ api_key = next(f for f in config.fields if f.name == "api_key")
+ assert isinstance(api_key, SourceFieldInputConfig)
+ assert api_key.secret is True
+ assert api_key.required is True
+
+ def test_get_schemas_lists_all_endpoints_full_refresh_only(self) -> None:
+ schemas = ClockodoSource().get_schemas(_config(), team_id=1)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ # The Clockodo API has no server-side modified-since filter, so nothing is incremental.
+ assert all(not s.supports_incremental and not s.supports_append for s in schemas)
+
+ def test_get_schemas_filters_by_names(self) -> None:
+ schemas = ClockodoSource().get_schemas(_config(), team_id=1, names=["entries"])
+ assert [s.name for s in schemas] == ["entries"]
+
+ def test_lists_tables_without_credentials_renders_docs(self) -> None:
+ # Static catalog → public docs Supported tables section renders without a live connection.
+ assert ClockodoSource.lists_tables_without_credentials is True
+ tables = ClockodoSource().get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+ assert all(t["sync_methods"] == ["Full refresh"] for t in tables)
+
+ @parameterized.expand([("valid", True, True), ("invalid", False, False)])
+ def test_validate_credentials(self, _name: str, probe_result: bool, expected_ok: bool) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.clockodo.source.validate_clockodo_credentials",
+ return_value=probe_result,
+ ):
+ ok, error = ClockodoSource().validate_credentials(_config(), team_id=1)
+ assert ok is expected_ok
+ assert (error is None) is expected_ok
+
+ def test_non_retryable_errors_cover_auth(self) -> None:
+ errors = ClockodoSource().get_non_retryable_errors()
+ assert any("401" in key for key in errors)
+ assert any("403" in key for key in errors)
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ inputs = MagicMock()
+ inputs.logger = MagicMock()
+ manager = ClockodoSource().get_resumable_source_manager(inputs)
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is ClockodoResumeConfig
+
+ def test_source_for_pipeline_plumbs_arguments(self) -> None:
+ inputs = MagicMock()
+ inputs.schema_name = "customers"
+ inputs.logger = MagicMock()
+ manager = MagicMock()
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.clockodo.source.clockodo_source"
+ ) as mock_source:
+ ClockodoSource().source_for_pipeline(_config(), manager, inputs)
+ mock_source.assert_called_once()
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["api_user"] == "[email protected]"
+ assert kwargs["api_key"] == "secret"
+ assert kwargs["endpoint"] == "customers"
+ assert kwargs["resumable_source_manager"] is manager
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index dd97ed07eb3f..08a95d1c4f80 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
@@ -721,7 +721,8 @@ class ClockifySourceConfig(config.Config):
@config.config
class ClockodoSourceConfig(config.Config):
- pass
+ api_user: str
+ api_key: str
@config.config