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(warehouse-sources): add clockify approval requests and user groups (#103345)

Tom Owersacb1c45390ea
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.md
index da57151eefe0..15008c84b93a 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
@@ -1592,7 +1592,7 @@ The chat entry stays open on purpose: those endpoints exist only on ClickUp's v3
## Clockify — gaps
-Today (13): `clients`, `custom_fields`, `expense_categories`, `expenses`, `invoice_payments`, `invoices`, `projects`, `tags`, `tasks`, `time_entries`, `time_off_requests`, `users`, `workspaces`
+Today (15): `approval_requests`, `clients`, `custom_fields`, `expense_categories`, `expenses`, `invoice_payments`, `invoices`, `projects`, `tags`, `tasks`, `time_entries`, `time_off_requests`, `user_groups`, `users`, `workspaces`
Diffed against: <https://docs.clockify.me/>
@@ -1601,14 +1601,16 @@ Diffed against: <https://docs.clockify.me/>
- [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)
- [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)
+- [x] `GET /v1/workspaces/{workspaceId}/approval-requests` — timesheet approval state and history per user and period (medium)
+- [x] `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)
- [ ] `GET /v1/workspaces/{workspaceId}/time-off/balance/user/{userId}` — accrued vs used leave balances per user (medium)
- [ ] `GET /v1/workspaces/{workspaceId}/holidays` — holiday calendar needed to compute working days and utilization denominators (medium)
- [ ] `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: `/projects/{projectId}/memberships` serves POST and PATCH only — there is no GET, so no `project_memberships` table. The project-to-user link is already synced: every `projects` row carries a `memberships` array of user id, membership status and rate. `/user-groups/{userGroupId}/users` is likewise POST and DELETE only, and unnecessary — the group's members arrive as `userIds` on the `user_groups` row. `/audit-log` is a POST report, not a listing: the request body must carry an explicit allow-list of audit action types (so a type Clockify adds later is silently dropped), an author filter, and a bounded date window, the rows carry no identifier to merge on, and nothing is recorded at all unless the workspace turns auditing on per entity type. Left out on the same grounds as the other POST reports below.
+
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 — gaps
diff --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.py
index 4fbbbcf5f2b2..11cea7e99a3c 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
@@ -208,4 +208,39 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"createdAt": "Timestamp the request was created.",
},
},
+ "approval_requests": {
+ "description": "A timesheet approval request on a workspace, with the totals the approver saw. Each row covers one user's submitted period (workspace_id + approval_request_id is unique). Approvals are a paid Clockify feature and must be enabled on the workspace.",
+ "docs_url": "https://docs.clockify.me/#tag/Approval",
+ "columns": {
+ "workspace_id": "Identifier of the workspace this approval belongs to (added during sync).",
+ "approval_request_id": "Unique identifier for the approval request (flattened from approvalRequest.id during sync).",
+ "approval_request_state": "Current approval state (PENDING, APPROVED, WITHDRAWN_SUBMISSION, WITHDRAWN_APPROVAL, REJECTED), flattened from approvalRequest.status.state during sync.",
+ "approval_request_owner_user_id": "Identifier of the user whose timesheet was submitted (flattened from approvalRequest.owner.userId during sync).",
+ "approval_request_start": "Start of the submitted period (flattened from approvalRequest.dateRange.start during sync).",
+ "approval_request_end": "End of the submitted period (flattened from approvalRequest.dateRange.end during sync).",
+ "approvalRequest": "The approval request itself: id, type, owner, creator, submitted period, and status with the note and who last changed it.",
+ "entries": "The time entries covered by the request.",
+ "expenses": "The expenses covered by the request.",
+ "trackedTime": "Total time tracked in the period, as a duration.",
+ "approvedTime": "Total approved time, as a duration.",
+ "pendingTime": "Total time still awaiting approval, as a duration.",
+ "billableTime": "Total billable time in the period, as a duration.",
+ "breakTime": "Total break time in the period, as a duration.",
+ "billableAmount": "Total billable amount for the period.",
+ "costAmount": "Total cost amount for the period.",
+ "expenseTotal": "Total of the expenses covered by the request.",
+ },
+ },
+ "user_groups": {
+ "description": "A user group (team) on a workspace, used to roll time up by team. Each row is one group within one workspace (workspace_id + id is unique) and carries its members inline.",
+ "docs_url": "https://docs.clockify.me/#tag/User-group",
+ "columns": {
+ "id": "Unique identifier for the user group.",
+ "workspace_id": "Identifier of the workspace this group belongs to (added during sync).",
+ "workspaceId": "Identifier of the workspace this group belongs to.",
+ "name": "Name of the user group.",
+ "userIds": "Identifiers of the users who belong to the group.",
+ "teamManagers": "The team managers assigned to the group.",
+ },
+ },
}
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.py
index a8779ed37e57..7058840df50d 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
@@ -49,6 +49,8 @@ _WORKSPACE_CHILD_ENDPOINTS = (
"expense_categories",
"invoices",
"time_off_requests",
+ "approval_requests",
+ "user_groups",
)
@@ -146,6 +148,29 @@ def _clamp_future_value_to_now(value: Any) -> Any:
return value
+def _flatten_approval_request(item: dict[str, Any]) -> dict[str, Any]:
+ """Surface the nested `approvalRequest` object as top-level columns.
+
+ The row's only identifier lives one level down, so without this the table has no primary key —
+ and the owner and approved period, which are what the table is joined and filtered on, would
+ need JSON extraction on every query."""
+ request = item.get("approvalRequest")
+ if not isinstance(request, dict):
+ return item
+ item["approval_request_id"] = request.get("id")
+ status = request.get("status")
+ if isinstance(status, dict):
+ item["approval_request_state"] = status.get("state")
+ owner = request.get("owner")
+ if isinstance(owner, dict):
+ item["approval_request_owner_user_id"] = owner.get("userId")
+ date_range = request.get("dateRange")
+ if isinstance(date_range, dict):
+ item["approval_request_start"] = date_range.get("start")
+ item["approval_request_end"] = date_range.get("end")
+ return item
+
+
def _flatten_time_entry(item: dict[str, Any]) -> dict[str, Any]:
"""Surface the nested `timeInterval` object as top-level columns so the interval start can be
used as the incremental cursor and partition key."""
@@ -169,6 +194,20 @@ def _time_entry_map(row: dict[str, Any]) -> dict[str, Any]:
return _rename_time_entry_parents(_flatten_time_entry(row))
+def _approval_request_map(row: dict[str, Any]) -> dict[str, Any] | list[dict[str, Any]]:
+ # Clockify documents `approvalRequest` as nullable. Such a row carries no id at all, so writing
+ # it would seed a null primary key that every later merge multi-matches; drop it instead.
+ if not isinstance(row.get("approvalRequest"), dict):
+ return []
+ return _rename_workspace(_flatten_approval_request(row))
+
+
+# Workspace children that need more than the parent-id rename.
+_WORKSPACE_CHILD_DATA_MAPS: dict[str, Callable[[dict[str, Any]], dict[str, Any] | list[dict[str, Any]]]] = {
+ "approval_requests": _approval_request_map,
+}
+
+
def _incremental_config(
should_use_incremental_field: bool, db_incremental_field_last_value: Any
) -> IncrementalConfig | None:
@@ -187,7 +226,7 @@ def _incremental_config(
def _endpoint_spec(config: ClockifyEndpointConfig, resolve_params: dict[str, Any]) -> Endpoint:
- params: dict[str, Any] = dict(resolve_params)
+ params: dict[str, Any] = {**resolve_params, **config.extra_params}
paginator: BasePaginator
if config.method == "POST":
paginator = ClockifyTimeOffPaginator(config.page_size)
@@ -225,7 +264,7 @@ def _workspace_child_resource(endpoint: str) -> EndpointResource:
CLOCKIFY_ENDPOINTS[endpoint],
{"workspace_id": {"type": "resolve", "resource": "workspaces", "field": "id"}},
),
- "data_map": _rename_workspace,
+ "data_map": _WORKSPACE_CHILD_DATA_MAPS.get(endpoint, _rename_workspace),
}
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.py
index b10e96f03cea..33299ba3317a 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,5 +1,5 @@
from dataclasses import field
-from typing import Literal, Optional
+from typing import Any, Literal, Optional
from posthog.dataclasses import frozen
@@ -47,6 +47,9 @@ class ClockifyEndpointConfig:
# Fail loud when `data_selector` matches nothing, rather than syncing zero rows off a changed
# response shape.
data_selector_required: bool = True
+ # Static query params sent with every request to this endpoint, on top of paging and the
+ # resolved path ids.
+ extra_params: dict[str, Any] = field(default_factory=dict)
_TIME_ENTRY_INCREMENTAL_FIELDS: list[IncrementalField] = [
@@ -163,6 +166,25 @@ CLOCKIFY_ENDPOINTS: dict[str, ClockifyEndpointConfig] = {
data_selector="requests",
page_size=200,
),
+ # Timesheet approval state per user and period. The row's id sits inside the nested
+ # `approvalRequest` object, flattened during sync. Paginating on an ascending id keeps pages
+ # stable while approvals are submitted mid-sync; the endpoint exposes no timestamp filter, so
+ # there is nothing to sync incrementally on.
+ "approval_requests": ClockifyEndpointConfig(
+ name="approval_requests",
+ path="/workspaces/{workspace_id}/approval-requests",
+ primary_keys=["workspace_id", "approval_request_id"],
+ extra_params={"sort-column": "ID", "sort-order": "ASCENDING"},
+ ),
+ # Team grouping. Each row carries its members as `userIds`, so the group-members sub-resource
+ # is not needed — Clockify serves it as POST/DELETE only. `includeTeamManagers` adds the
+ # managers assigned to the group, which are omitted by default.
+ "user_groups": ClockifyEndpointConfig(
+ name="user_groups",
+ path="/workspaces/{workspace_id}/user-groups",
+ primary_keys=["workspace_id", "id"],
+ extra_params={"sort-column": "ID", "sort-order": "ASCENDING", "includeTeamManagers": "true"},
+ ),
}
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.py
index 0dd0ed161adb..ff6a677881a0 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
@@ -15,6 +15,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.clockify.c
ClockifyResumeConfig,
_chained_resource,
_clamp_future_value_to_now,
+ _flatten_approval_request,
_flatten_time_entry,
_format_datetime_z,
clockify_source,
@@ -134,6 +135,34 @@ class TestFlattenTimeEntry:
assert "time_interval_start" not in row
+class TestFlattenApprovalRequest:
+ def test_flattens_the_nested_request(self) -> None:
+ row = _flatten_approval_request(
+ {
+ "approvalRequest": {
+ "id": "AR1",
+ "status": {"state": "APPROVED", "note": ""},
+ "owner": {"userId": "U1", "userName": "Ada"},
+ "dateRange": {"start": "2026-03-02T00:00:00Z", "end": "2026-03-08T23:59:59Z"},
+ },
+ "trackedTime": "PT40H",
+ }
+ )
+ assert row["approval_request_id"] == "AR1"
+ assert row["approval_request_state"] == "APPROVED"
+ assert row["approval_request_owner_user_id"] == "U1"
+ assert row["approval_request_start"] == "2026-03-02T00:00:00Z"
+ assert row["approval_request_end"] == "2026-03-08T23:59:59Z"
+
+ def test_partial_request_only_flattens_what_is_present(self) -> None:
+ row = _flatten_approval_request({"approvalRequest": {"id": "AR1"}})
+ assert row["approval_request_id"] == "AR1"
+ assert "approval_request_state" not in row
+
+ def test_missing_request_is_noop(self) -> None:
+ assert _flatten_approval_request({"trackedTime": "PT1H"}) == {"trackedTime": "PT1H"}
+
+
class TestPaginator:
def _paginator(self) -> ClockifyPageNumberPaginator:
paginator = ClockifyPageNumberPaginator(page_size=2)
@@ -438,6 +467,69 @@ class TestTimeOffRequestsEndpoint:
assert [body.get("page") for _url, _method, body in snapshots[1:]] == [1, 2]
+class TestApprovalRequestsEndpoint:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_flattens_rows_and_pages_on_a_stable_sort(self, MockSession) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(
+ session,
+ [
+ _response([{"id": "W1"}]),
+ _response([{"approvalRequest": {"id": "AR1", "owner": {"userId": "U1"}}, "trackedTime": "PT40H"}]),
+ ],
+ )
+
+ rows = _rows(_source("approval_requests", _make_manager()))
+
+ assert rows[0]["workspace_id"] == "W1"
+ assert rows[0]["approval_request_id"] == "AR1"
+ assert rows[0]["approval_request_owner_user_id"] == "U1"
+ url, params = snapshots[-1]
+ assert url == f"{CLOCKIFY_BASE_URL}/workspaces/W1/approval-requests"
+ # Approvals are submitted while a sync runs, so an unsorted walk would skip or repeat rows
+ # across page boundaries.
+ assert params == {"page": 1, "page-size": 1000, "sort-column": "ID", "sort-order": "ASCENDING"}
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_row_without_an_approval_request_is_dropped(self, MockSession) -> None:
+ session = MockSession.return_value
+ # Clockify documents the nested request as nullable; such a row has no id, and writing it
+ # would seed a null primary key.
+ _wire(
+ session,
+ [
+ _response([{"id": "W1"}]),
+ _response([{"approvalRequest": None}, {"approvalRequest": {"id": "AR1"}}]),
+ ],
+ )
+
+ rows = _rows(_source("approval_requests", _make_manager()))
+
+ assert [row["approval_request_id"] for row in rows] == ["AR1"]
+
+
+class TestUserGroupsEndpoint:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_keeps_members_and_asks_for_team_managers(self, MockSession) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(
+ session,
+ [
+ _response([{"id": "W1"}]),
+ _response([{"id": "G1", "name": "Design", "userIds": ["U1", "U2"], "teamManagers": [{"id": "U1"}]}]),
+ ],
+ )
+
+ rows = _rows(_source("user_groups", _make_manager()))
+
+ assert rows[0]["workspace_id"] == "W1"
+ assert rows[0]["userIds"] == ["U1", "U2"]
+ url, params = snapshots[-1]
+ assert url == f"{CLOCKIFY_BASE_URL}/workspaces/W1/user-groups"
+ # Team managers are left out of the response unless asked for.
+ assert params["includeTeamManagers"] == "true"
+
+
class TestChainedResource:
def test_endpoint_without_a_fan_out_parent_is_rejected(self) -> None:
with pytest.raises(ValueError, match="no fan-out parent"):