: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(clockify): add expense, invoice, time off and custom field tables (#102947)
Tom Owersb64bdfbecc3d
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.mdindex f7b09a003a02..b77df3881ba2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md@@ -1585,15 +1585,15 @@ The chat entry stays open on purpose: those endpoints exist only on ClickUp's v3## Clockify — gaps-Today (7): `clients`, `projects`, `tags`, `tasks`, `time_entries`, `users`, `workspaces`+Today (13): `clients`, `custom_fields`, `expense_categories`, `expenses`, `invoice_payments`, `invoices`, `projects`, `tags`, `tasks`, `time_entries`, `time_off_requests`, `users`, `workspaces`Diffed against: <https://docs.clockify.me/>-- [ ] `GET /v1/workspaces/{workspaceId}/expenses (+ /expenses/categories)` — expense transactions and their category lookup - the cost side of project profitability (high)-- [ ] `GET /v1/workspaces/{workspaceId}/invoices (+ /items, /payments)` — invoice headers, line items and payments, the billing fact tables for revenue reporting (high)-- [ ] `GET /v1/workspaces/{workspaceId}/time-off/requests` — time off requests - required to separate absence from unlogged time in capacity analysis (high)+- [x] `GET /v1/workspaces/{workspaceId}/expenses (+ /expenses/categories)` — expense transactions and their category lookup - the cost side of project profitability (high)+- [x] `GET /v1/workspaces/{workspaceId}/invoices (+ /payments)` — invoice headers and payments, the billing fact tables for revenue reporting (high)+- [x] `POST /v1/workspaces/{workspaceId}/time-off/requests` — time off requests - required to separate absence from unlogged time in capacity analysis (high)- [ ] `GET /v1/workspaces/{workspaceId}/projects/{projectId}/memberships` — project-to-user membership join table; today projects and users cannot be linked (high)-- [ ] `GET /v1/workspaces/{workspaceId}/custom-fields` — custom field definitions resolving the custom field IDs stored on time entries and projects (high)+- [x] `GET /v1/workspaces/{workspaceId}/custom-fields` — custom field definitions resolving the custom field IDs stored on time entries and projects (high)- [ ] `GET /v1/workspaces/{workspaceId}/approval-requests` — timesheet approval state and history per user and period (medium)- [ ] `GET /v1/workspaces/{workspaceId}/user-groups (+ /{userGroupId}/users)` — team grouping and its membership rows for rolling time up by team (medium)- [ ] `GET /v1/workspaces/{workspaceId}/time-off/policies` — policy lookup that resolves the policy IDs on time off requests and balances (medium)@@ -1602,7 +1602,7 @@ Diffed against: <https://docs.clockify.me/>- [ ] `GET /v1/workspaces/{workspaceId}/scheduling/assignments/all` — planned/scheduled assignments to compare planned against tracked time (medium)- [ ] `GET /v1/workspaces/{workspaceId}/audit-log` — workspace audit event stream for admin and compliance reporting (medium)-Note: Also present but below the cut: POST reports (detailed, summary, weekly, attendance), hourly/cost rate endpoints, and /entities/created|updated|deleted change feeds. Webhooks, addons, templates and shared reports excluded as plumbing/config.+Note: Also present but below the cut: POST reports (detailed, summary, weekly, attendance), hourly/cost rate endpoints, and /entities/created|updated|deleted change feeds. Webhooks, addons, templates and shared reports excluded as plumbing/config. Invoice line items have no list endpoint — `/invoices/{invoiceId}/items` serves POST and DELETE only, and the items are embedded in the single-invoice response, so no `invoice_items` table. The time off listing is a POST whose filters travel in the request body, not the GET the diff assumed.## Clockodo — gapsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clockify/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clockify/canonical_descriptions.pyindex 71d42b311c42..4fbbbcf5f2b2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clockify/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clockify/canonical_descriptions.py@@ -99,4 +99,113 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"time_interval_duration": "Duration of the entry as an ISO 8601 duration (flattened from timeInterval.duration).",},},+ "custom_fields": {+ "description": "A custom field definition on a workspace. Resolves the custom field ids carried on time entries, projects and users.",+ "docs_url": "https://docs.clockify.me/#tag/Custom-fields",+ "columns": {+ "id": "Unique identifier for the custom field.",+ "workspace_id": "Identifier of the workspace this custom field belongs to (added during sync).",+ "workspaceId": "Identifier of the workspace this custom field belongs to.",+ "name": "Display name of the custom field.",+ "type": "Value type of the field (e.g. TXT, NUMBER, DROPDOWN_SINGLE, CHECKBOX, LINK).",+ "entityType": "Entity the field applies to (e.g. TIMEENTRY, PROJECT, USER).",+ "status": "Visibility of the field (INACTIVE, VISIBLE, INVISIBLE).",+ "required": "Whether a value must be supplied for the field.",+ "onlyAdminCanEdit": "Whether only admins may change the field's value.",+ "allowedValues": "Permitted values for a dropdown-style field.",+ "placeholder": "Placeholder text shown in the input.",+ "workspaceDefaultValue": "Default value applied across the workspace.",+ "projectDefaultValues": "Per-project default values and their status.",+ },+ },+ "expenses": {+ "description": "An expense recorded against a workspace, and optionally a project and task. Expense tracking is a paid Clockify feature and must be enabled on the workspace.",+ "docs_url": "https://docs.clockify.me/#tag/Expense",+ "columns": {+ "id": "Unique identifier for the expense.",+ "workspace_id": "Identifier of the workspace this expense belongs to (added during sync).",+ "workspaceId": "Identifier of the workspace this expense belongs to.",+ "userId": "Identifier of the user the expense is recorded for.",+ "date": "Date the expense was incurred, in yyyy-MM-dd format.",+ "total": "Total amount of the expense.",+ "quantity": "Quantity booked, for categories priced per unit.",+ "billable": "Whether the expense is billable to the client.",+ "notes": "Free-text note on the expense.",+ "locked": "Whether the expense is locked against further edits.",+ "category": "The expense category, including its name and unit price.",+ "project": "The project the expense is booked against, if any.",+ "task": "The task the expense is booked against, if any.",+ "fileId": "Identifier of the attached receipt file, if any.",+ "fileName": "Name of the attached receipt file, if any.",+ },+ },+ "expense_categories": {+ "description": "An expense category on a workspace, resolving the category an expense is booked under. Only active categories are synced, matching Clockify's default filter.",+ "docs_url": "https://docs.clockify.me/#tag/Expense",+ "columns": {+ "id": "Unique identifier for the expense category.",+ "workspace_id": "Identifier of the workspace this category belongs to (added during sync).",+ "workspaceId": "Identifier of the workspace this category belongs to.",+ "name": "Category name.",+ "unit": "Unit the category is priced in, when it has a unit price.",+ "hasUnitPrice": "Whether the category carries a fixed price per unit.",+ "priceInCents": "Unit price of the category, in cents.",+ "archived": "Whether the category is archived.",+ },+ },+ "invoices": {+ "description": "An invoice header on a workspace. Invoicing is a paid Clockify feature and must be enabled on the workspace.",+ "docs_url": "https://docs.clockify.me/#tag/Invoice",+ "columns": {+ "id": "Unique identifier for the invoice.",+ "workspace_id": "Identifier of the workspace this invoice belongs to (added during sync).",+ "number": "Human-readable invoice number.",+ "clientId": "Identifier of the client the invoice is issued to.",+ "clientName": "Name of the client the invoice is issued to.",+ "amount": "Total amount of the invoice.",+ "balance": "Amount still outstanding on the invoice.",+ "paid": "Amount already paid against the invoice.",+ "currency": "Currency the invoice is denominated in.",+ "issuedDate": "Date the invoice was issued.",+ "dueDate": "Date payment is due.",+ "status": "Invoice status (UNSENT, SENT, PAID, PARTIALLY_PAID, VOID, OVERDUE).",+ },+ },+ "invoice_payments": {+ "description": "A payment recorded against an invoice. Each row is one payment on one invoice (workspace_id + invoice_id + id is unique).",+ "docs_url": "https://docs.clockify.me/#tag/Invoice",+ "columns": {+ "id": "Unique identifier for the payment.",+ "workspace_id": "Identifier of the workspace this payment belongs to (added during sync).",+ "invoice_id": "Identifier of the invoice this payment was made against (added during sync).",+ "amount": "Amount of the payment.",+ "date": "Date the payment was recorded.",+ "author": "The user who recorded the payment.",+ "note": "Free-text note on the payment.",+ },+ },+ "time_off_requests": {+ "description": "A time off request on a workspace, in every status. Separates approved absence from time that was simply never logged. Time off is a paid Clockify feature and must be enabled on the workspace.",+ "docs_url": "https://docs.clockify.me/#tag/Time-Off",+ "columns": {+ "id": "Unique identifier for the time off request.",+ "workspace_id": "Identifier of the workspace this request belongs to (added during sync).",+ "workspaceId": "Identifier of the workspace this request belongs to.",+ "userId": "Identifier of the user the time off is for.",+ "userName": "Display name of the user the time off is for.",+ "userEmail": "Email of the user the time off is for.",+ "userTimeZone": "Time zone the request's period is expressed in.",+ "requesterUserId": "Identifier of the user who submitted the request.",+ "requesterUserName": "Display name of the user who submitted the request.",+ "policyId": "Identifier of the time off policy the request draws from.",+ "policyName": "Name of the time off policy the request draws from.",+ "status": "Request status, including who changed it and when (PENDING, APPROVED, REJECTED).",+ "timeOffPeriod": "The requested period, and whether it covers half a day.",+ "timeUnit": "Unit the balance is measured in (DAYS or HOURS).",+ "balance": "Remaining policy balance for the user.",+ "balanceDiff": "Amount this request draws from the balance.",+ "note": "Free-text note attached to the request.",+ "createdAt": "Timestamp the request was created.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clockify/clockify.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clockify/clockify.pyindex f48fed17f887..a8779ed37e57 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clockify/clockify.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clockify/clockify.py@@ -1,10 +1,14 @@import dataclasses+from collections.abc import Callablefrom datetime import UTC, date, datetime-from typing import Any, Optional+from typing import Any, Optional, cast-from requests import Response+from requests import Request, Response-from products.warehouse_sources.backend.temporal.data_imports.sources.clockify.settings import CLOCKIFY_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.clockify.settings import (+ CLOCKIFY_ENDPOINTS,+ ClockifyEndpointConfig,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (RESTAPIConfig,@@ -14,7 +18,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resrename_parent_fields,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ BasePaginator,PageNumberPaginator,+ ParamLocation,+ SinglePagePaginator,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (@@ -30,9 +37,19 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typ# resolves to the user's region, so a single base URL works for every key.CLOCKIFY_BASE_URL = "https://api.clockify.me/api/v1"-# Single-level fan-out endpoints: one GET per workspace. Two-level ones (tasks, time_entries)-# chain a second parent (projects/users) and are handled explicitly below.-_WORKSPACE_CHILD_ENDPOINTS = ("users", "clients", "projects", "tags")+# Single-level fan-out endpoints: one request per workspace. Two-level ones (tasks,+# time_entries, invoice_payments) chain a second parent and are handled explicitly below.+_WORKSPACE_CHILD_ENDPOINTS = (+ "users",+ "clients",+ "projects",+ "tags",+ "custom_fields",+ "expenses",+ "expense_categories",+ "invoices",+ "time_off_requests",+)class ClockifyPageNumberPaginator(PageNumberPaginator):@@ -43,8 +60,8 @@ class ClockifyPageNumberPaginator(PageNumberPaginator):extra empty-page request the plain ``PageNumberPaginator`` would pay."""- def __init__(self, page_size: int) -> None:- super().__init__(base_page=1, page_param="page")+ def __init__(self, page_size: int, param_location: ParamLocation = "query") -> None:+ super().__init__(base_page=1, page_param="page", param_location=param_location)self._page_size = page_sizedef update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:@@ -53,6 +70,25 @@ class ClockifyPageNumberPaginator(PageNumberPaginator):self._has_next_page = False+class ClockifyTimeOffPaginator(ClockifyPageNumberPaginator):+ """Paging for the time-off listing, whose filters and page fields travel in a POST body.++ A fan-out child request gets no static ``json`` body from the framework, so the whole payload is+ written here. ``statuses`` has to name every state explicitly — Clockify returns only pending+ requests when the filter is left off.+ """++ def __init__(self, page_size: int) -> None:+ super().__init__(page_size, param_location="json")++ def init_request(self, request: Request) -> None:+ if request.json is None:+ request.json = {}+ request.json["pageSize"] = self._page_size+ request.json["statuses"] = ["ALL"]+ super().init_request(request)++@dataclasses.dataclassclass ClockifyResumeConfig:# Opaque paginator/fan-out state handed back by the rest_source framework (paginator page for@@ -126,6 +162,7 @@ def _flatten_time_entry(item: dict[str, Any]) -> dict[str, Any]:_rename_workspace = rename_parent_fields("workspaces", {"id": "workspace_id"})_rename_task_parents = rename_parent_fields("projects", {"workspace_id": "workspace_id", "id": "project_id"})_rename_time_entry_parents = rename_parent_fields("users", {"workspace_id": "workspace_id", "id": "user_id"})+_rename_invoice_parents = rename_parent_fields("invoices", {"workspace_id": "workspace_id", "id": "invoice_id"})def _time_entry_map(row: dict[str, Any]) -> dict[str, Any]:@@ -149,76 +186,75 @@ def _incremental_config(}+def _endpoint_spec(config: ClockifyEndpointConfig, resolve_params: dict[str, Any]) -> Endpoint:+ params: dict[str, Any] = dict(resolve_params)+ paginator: BasePaginator+ if config.method == "POST":+ paginator = ClockifyTimeOffPaginator(config.page_size)+ elif config.paginated:+ params["page-size"] = config.page_size+ paginator = ClockifyPageNumberPaginator(config.page_size)+ else:+ paginator = SinglePagePaginator()++ endpoint: Endpoint = {+ "path": config.path,+ "params": params,+ "paginator": paginator,+ "data_selector_required": config.data_selector_required,+ }+ if config.method != "GET":+ endpoint["method"] = config.method+ if config.data_selector is not None:+ endpoint["data_selector"] = config.data_selector+ return endpoint++def _workspaces_resource() -> EndpointResource:- config = CLOCKIFY_ENDPOINTS["workspaces"]return {"name": "workspaces",- "endpoint": {- "path": config.path,- "params": {"page-size": config.page_size},- "paginator": ClockifyPageNumberPaginator(config.page_size),- "data_selector_required": True,- },+ "endpoint": _endpoint_spec(CLOCKIFY_ENDPOINTS["workspaces"], {}),}def _workspace_child_resource(endpoint: str) -> EndpointResource:- config = CLOCKIFY_ENDPOINTS[endpoint]return {"name": endpoint,"include_from_parent": ["id"],- "endpoint": {- "path": config.path,- "params": {- "workspace_id": {"type": "resolve", "resource": "workspaces", "field": "id"},- "page-size": config.page_size,- },- "paginator": ClockifyPageNumberPaginator(config.page_size),- "data_selector_required": True,- },+ "endpoint": _endpoint_spec(+ CLOCKIFY_ENDPOINTS[endpoint],+ {"workspace_id": {"type": "resolve", "resource": "workspaces", "field": "id"}},+ ),"data_map": _rename_workspace,}-def _tasks_resource() -> EndpointResource:- config = CLOCKIFY_ENDPOINTS["tasks"]+def _chained_resource(endpoint: str, data_map: Callable[[dict[str, Any]], dict[str, Any]]) -> EndpointResource:+ """A resource fanning out over a workspace child, so the path carries two resolved ids."""+ config = CLOCKIFY_ENDPOINTS[endpoint]+ parent = config.fan_out_parent+ placeholder = config.parent_id_placeholder+ if parent is None or placeholder is None:+ raise ValueError(f"Clockify endpoint {endpoint} declares no fan-out parent to resolve its path against")return {- "name": "tasks",+ "name": endpoint,"include_from_parent": ["workspace_id", "id"],- "endpoint": {- "path": config.path,- "params": {- "workspace_id": {"type": "resolve", "resource": "projects", "field": "workspace_id"},- "project_id": {"type": "resolve", "resource": "projects", "field": "id"},- "page-size": config.page_size,+ "endpoint": _endpoint_spec(+ config,+ {+ "workspace_id": {"type": "resolve", "resource": parent, "field": "workspace_id"},+ placeholder: {"type": "resolve", "resource": parent, "field": "id"},},- "paginator": ClockifyPageNumberPaginator(config.page_size),- "data_selector_required": True,- },- "data_map": _rename_task_parents,+ ),+ "data_map": data_map,}def _time_entries_resource(incremental: IncrementalConfig | None) -> EndpointResource:- config = CLOCKIFY_ENDPOINTS["time_entries"]- endpoint: Endpoint = {- "path": config.path,- "params": {- "workspace_id": {"type": "resolve", "resource": "users", "field": "workspace_id"},- "user_id": {"type": "resolve", "resource": "users", "field": "id"},- "page-size": config.page_size,- },- "paginator": ClockifyPageNumberPaginator(config.page_size),- "data_selector_required": True,- }+ resource = _chained_resource("time_entries", _time_entry_map)if incremental is not None:- endpoint["incremental"] = incremental- return {- "name": "time_entries",- "include_from_parent": ["workspace_id", "id"],- "endpoint": endpoint,- "data_map": _time_entry_map,- }+ cast(Endpoint, resource["endpoint"])["incremental"] = incremental+ return resourcedef _resources_for(endpoint: str, incremental: IncrementalConfig | None) -> list[str | EndpointResource]:@@ -227,9 +263,19 @@ def _resources_for(endpoint: str, incremental: IncrementalConfig | None) -> listif endpoint in _WORKSPACE_CHILD_ENDPOINTS:return [_workspaces_resource(), _workspace_child_resource(endpoint)]if endpoint == "tasks":- return [_workspaces_resource(), _workspace_child_resource("projects"), _tasks_resource()]+ return [+ _workspaces_resource(),+ _workspace_child_resource("projects"),+ _chained_resource("tasks", _rename_task_parents),+ ]if endpoint == "time_entries":return [_workspaces_resource(), _workspace_child_resource("users"), _time_entries_resource(incremental)]+ if endpoint == "invoice_payments":+ return [+ _workspaces_resource(),+ _workspace_child_resource("invoices"),+ _chained_resource("invoice_payments", _rename_invoice_parents),+ ]raise ValueError(f"Unknown Clockify endpoint: {endpoint}")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clockify/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clockify/settings.pyindex 2fe1cf3d6b8e..b10e96f03cea 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clockify/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clockify/settings.py@@ -1,10 +1,12 @@-from dataclasses import dataclass, field+from dataclasses import fieldfrom typing import Literal, Optional+from posthog.dataclasses import frozen+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType-@dataclass+@frozenclass ClockifyEndpointConfig:name: str# Path template relative to the API base. Placeholders are filled per fan-out scope:@@ -33,6 +35,18 @@ class ClockifyEndpointConfig:# Query param name for the server-side timestamp filter, when the endpoint exposes one.# Only time-entries does (`start` filters entries that started after the given datetime).incremental_param: Optional[str] = None+ # HTTP method of the list request. Only the time-off listing deviates: Clockify serves it as a+ # POST whose filter criteria travel in the request body.+ method: Literal["GET", "POST"] = "GET"+ # jsonpath to the row list for endpoints that wrap it in an envelope. None means the response+ # body is the bare array.+ data_selector: Optional[str] = None+ # False for endpoints that accept no `page`/`page-size` params and return the whole collection+ # in one response.+ paginated: bool = True+ # Fail loud when `data_selector` matches nothing, rather than syncing zero rows off a changed+ # response shape.+ data_selector_required: bool = True_TIME_ENTRY_INCREMENTAL_FIELDS: list[IncrementalField] = [@@ -99,6 +113,56 @@ CLOCKIFY_ENDPOINTS: dict[str, ClockifyEndpointConfig] = {parent_id_placeholder="user_id",incremental_param="start",),+ # Definitions for the custom field ids that time entries, projects and users carry. The+ # endpoint accepts no paging params and returns the whole collection in one response.+ "custom_fields": ClockifyEndpointConfig(+ name="custom_fields",+ path="/workspaces/{workspace_id}/custom-fields",+ primary_keys=["workspace_id", "id"],+ paginated=False,+ ),+ # Expense transactions. The rows sit two levels down the response envelope, and that envelope+ # is documented as nullable, so a workspace without expense tracking yields no rows rather+ # than a shape error.+ "expenses": ClockifyEndpointConfig(+ name="expenses",+ path="/workspaces/{workspace_id}/expenses",+ primary_keys=["workspace_id", "id"],+ data_selector="expenses.expenses",+ data_selector_required=False,+ ),+ # Category lookup for expenses. Clockify filters on `archived` with a default of false, so this+ # table holds the active categories — the same treatment clients/projects/tags already get.+ "expense_categories": ClockifyEndpointConfig(+ name="expense_categories",+ path="/workspaces/{workspace_id}/expenses/categories",+ primary_keys=["workspace_id", "id"],+ data_selector="categories",+ ),+ "invoices": ClockifyEndpointConfig(+ name="invoices",+ path="/workspaces/{workspace_id}/invoices",+ primary_keys=["workspace_id", "id"],+ data_selector="invoices",+ ),+ # Two-level fan-out: workspace -> invoice -> payments. Payment ids are documented per invoice,+ # so both parent ids are part of the primary key.+ "invoice_payments": ClockifyEndpointConfig(+ name="invoice_payments",+ path="/workspaces/{workspace_id}/invoices/{invoice_id}/payments",+ primary_keys=["workspace_id", "invoice_id", "id"],+ fan_out_parent="invoices",+ parent_id_placeholder="invoice_id",+ ),+ # The only POST listing. Paging travels in the body, where `pageSize` caps at 200.+ "time_off_requests": ClockifyEndpointConfig(+ name="time_off_requests",+ path="/workspaces/{workspace_id}/time-off/requests",+ primary_keys=["workspace_id", "id"],+ method="POST",+ data_selector="requests",+ page_size=200,+ ),}ENDPOINTS = tuple(CLOCKIFY_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clockify/tests/test_clockify.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clockify/tests/test_clockify.pyindex 69fd23c32cfe..0dd0ed161adb 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clockify/tests/test_clockify.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clockify/tests/test_clockify.py@@ -13,6 +13,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.clockify.cCLOCKIFY_BASE_URL,ClockifyPageNumberPaginator,ClockifyResumeConfig,+ _chained_resource,_clamp_future_value_to_now,_flatten_time_entry,_format_datetime_z,@@ -61,6 +62,20 @@ def _wire(session: mock.MagicMock, responses: list[Response]) -> list[tuple[str,return snapshots+def _wire_bodies(session: mock.MagicMock, responses: list[Response]) -> list[tuple[str, str, dict[str, Any]]]:+ """Like ``_wire``, but snapshots the method and JSON body instead of the query params."""+ session.headers = {}+ snapshots: list[tuple[str, str, dict[str, Any]]] = []++ def _prepare(request: Any) -> mock.MagicMock:+ snapshots.append((request.url, request.method, dict(request.json or {})))+ return mock.MagicMock()++ session.prepare_request.side_effect = _prepare+ session.send.side_effect = responses+ return snapshots++def _rows(source_response) -> list[dict[str, Any]]:return [row for page in source_response.items() for row in page]@@ -314,6 +329,121 @@ class TestTwoLevelFanOutTimeEntries:assert "start" not in snapshots[-1][1]+class TestEnvelopedEndpoints:+ """Endpoints whose rows sit inside a response envelope rather than a bare array."""++ @parameterized.expand(+ [+ (+ "expenses",+ {"dailyTotals": None, "weeklyTotals": None, "expenses": {"count": 1, "expenses": [{"id": "E1"}]}},+ ),+ ("expense_categories", {"count": 1, "categories": [{"id": "E1"}]}),+ ("invoices", {"total": 1, "invoices": [{"id": "E1"}]}),+ ]+ )+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_rows_are_read_from_the_envelope(self, endpoint: str, body: Any, MockSession) -> None:+ session = MockSession.return_value+ _wire(session, [_response([{"id": "W1"}]), _response(body)])++ rows = _rows(_source(endpoint, _make_manager()))++ assert rows == [{"id": "E1", "workspace_id": "W1"}]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_null_expense_envelope_yields_no_rows(self, MockSession) -> None:+ session = MockSession.return_value+ # Clockify documents all three keys as nullable; a workspace without expense tracking must+ # sync zero rows rather than fail the schema.+ _wire(+ session,+ [_response([{"id": "W1"}]), _response({"dailyTotals": None, "expenses": None, "weeklyTotals": None})],+ )++ assert _rows(_source("expenses", _make_manager())) == []+++class TestCustomFieldsEndpoint:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_sends_no_paging_params_and_stops_after_one_page(self, MockSession) -> None:+ session = MockSession.return_value+ # The endpoint accepts no page/page-size params, so sending them would be noise and a+ # second request would re-read the same collection forever.+ snapshots = _wire(session, [_response([{"id": "W1"}]), _response([{"id": "CF1"}])])++ rows = _rows(_source("custom_fields", _make_manager()))++ assert rows == [{"id": "CF1", "workspace_id": "W1"}]+ assert snapshots[-1] == (f"{CLOCKIFY_BASE_URL}/workspaces/W1/custom-fields", {})+++class TestTwoLevelFanOutInvoicePayments:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_fans_out_workspace_then_invoice_and_injects_both_ids(self, MockSession) -> None:+ session = MockSession.return_value+ snapshots = _wire(+ session,+ [+ _response([{"id": "W1"}]),+ _response({"total": 2, "invoices": [{"id": "I1"}, {"id": "I2"}]}),+ _response([{"id": "PM1", "amount": 10}]),+ _response([{"id": "PM2", "amount": 20}]),+ ],+ )++ rows = _rows(_source("invoice_payments", _make_manager()))++ assert rows == [+ {"id": "PM1", "amount": 10, "workspace_id": "W1", "invoice_id": "I1"},+ {"id": "PM2", "amount": 20, "workspace_id": "W1", "invoice_id": "I2"},+ ]+ assert [url for url, _ in snapshots] == [+ f"{CLOCKIFY_BASE_URL}/workspaces",+ f"{CLOCKIFY_BASE_URL}/workspaces/W1/invoices",+ f"{CLOCKIFY_BASE_URL}/workspaces/W1/invoices/I1/payments",+ f"{CLOCKIFY_BASE_URL}/workspaces/W1/invoices/I2/payments",+ ]+++class TestTimeOffRequestsEndpoint:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_posts_the_filter_body_and_reads_the_requests_envelope(self, MockSession) -> None:+ session = MockSession.return_value+ snapshots = _wire_bodies(+ session,+ [_response([{"id": "W1"}]), _response({"count": 1, "requests": [{"id": "TO1"}]})],+ )++ rows = _rows(_source("time_off_requests", _make_manager()))++ assert rows == [{"id": "TO1", "workspace_id": "W1"}]+ url, method, body = snapshots[-1]+ assert url == f"{CLOCKIFY_BASE_URL}/workspaces/W1/time-off/requests"+ assert method == "POST"+ # Without an explicit status filter Clockify returns pending requests only.+ assert body == {"page": 1, "pageSize": 200, "statuses": ["ALL"]}++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_paging_advances_in_the_body(self, MockSession) -> None:+ session = MockSession.return_value+ full_page = {"count": 200, "requests": [{"id": str(i)} for i in range(200)]}+ snapshots = _wire_bodies(+ session,+ [_response([{"id": "W1"}]), _response(full_page), _response({"count": 0, "requests": []})],+ )++ _rows(_source("time_off_requests", _make_manager()))++ assert [body.get("page") for _url, _method, body in snapshots[1:]] == [1, 2]+++class TestChainedResource:+ def test_endpoint_without_a_fan_out_parent_is_rejected(self) -> None:+ with pytest.raises(ValueError, match="no fan-out parent"):+ _chained_resource("clients", lambda row: row)++class TestFailLoud:@mock.patch(CLIENT_SESSION_PATCH)def test_non_list_body_raises(self, MockSession) -> None:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clockify/tests/test_clockify_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clockify/tests/test_clockify_source.pyindex 5ca034f1188c..359e9a92eff2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clockify/tests/test_clockify_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clockify/tests/test_clockify_source.py@@ -84,6 +84,7 @@ class TestEndpointConfig:# of the primary key or merges would collapse rows across parents.assert CLOCKIFY_ENDPOINTS["tasks"].primary_keys == ["workspace_id", "project_id", "id"]assert CLOCKIFY_ENDPOINTS["time_entries"].primary_keys == ["workspace_id", "user_id", "id"]+ assert CLOCKIFY_ENDPOINTS["invoice_payments"].primary_keys == ["workspace_id", "invoice_id", "id"]def test_only_time_entries_has_a_server_side_filter(self) -> None:with_filter = [name for name, cfg in CLOCKIFY_ENDPOINTS.items() if cfg.incremental_param]