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(clockodo): add attendance, absences, target hours and reports (#102935)

Tom Owers901ab41018f9
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 eba6b3d7223c..265cd67b45f7 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
@@ -1617,10 +1617,10 @@ Today (8): `customers`, `entries`, `lumpsum_services`, `projects`, `services`, `
Diffed against: <https://www.clockodo.com/en/api/>
-- [ ] `/v2/absences` — vacation, sick leave and other absences - the main non-billable time dimension (high)
-- [ ] `/v2/worktimes` — clock-in/clock-out attendance records, distinct from the project time entries we sync (high)
-- [ ] `/v2/userreports` — per-user yearly report (target vs actual hours, overtime, holidays) - the vendor's headline utilization metric (high)
-- [ ] `/v2/targethours` — target working hours per user, the denominator for any utilization or overtime calculation (high)
+- [x] `/v2/absences` — vacation, sick leave and other absences - the main non-billable time dimension (high)
+- [x] `/v2/worktimes` — clock-in/clock-out attendance records, distinct from the project time entries we sync (high)
+- [x] `/v2/userreports` — per-user yearly report (target vs actual hours, overtime, holidays) - the vendor's headline utilization metric (high)
+- [x] `/v2/targethours` — target working hours per user, the denominator for any utilization or overtime calculation (high)
- [ ] `/v2/entrygroups` — grouped/aggregated entry rollups by customer, project or service - the built-in report breakdown (medium)
- [ ] `/v2/nonbusinessdays (+ /nonbusinessgroups)` — public holiday calendars and their groups, needed for working-day normalization (medium)
- [ ] `/v2/holidaysquota and /v2/holidayscarry` — leave entitlement and carry-over balances per user and year (medium)
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
index 818767f6677d..1b0c1f49eb70 100644
--- 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
@@ -98,4 +98,80 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"time_last_change": "Time the entry was last modified (ISO 8601).",
},
},
+ "absences": {
+ "description": "Absences of each co-worker: holidays, sick days, overtime reduction and other non-working time, with their approval status.",
+ "docs_url": "https://docs.clockodo.com/#tag/Absence",
+ "columns": {
+ "id": "Unique identifier of the absence.",
+ "users_id": "Identifier of the co-worker the absence belongs to.",
+ "date_since": "First day of the absence (YYYY-MM-DD).",
+ "date_until": "Last day of the absence (YYYY-MM-DD).",
+ "type": "Type of absence, e.g. 1 regular holiday, 2 special leave, 3 overtime reduction, 4 sick day, 8 home office.",
+ "status": "Status of the absence: 0 enquired, 1 approved, 2 declined, 3 approval cancelled, 4 request cancelled.",
+ "count_days": "Number of absence days. Null for overtime reduction.",
+ "count_hours": "Number of hours of overtime reduction. Null for other types.",
+ "sick_note": "Whether a doctor's sick note exists, for sick-day types.",
+ "note": "Internal note on the absence.",
+ "public_note": "Note on the absence visible to other co-workers.",
+ "date_enquired": "Date the absence was requested (YYYY-MM-DD).",
+ "date_approved": "Date the request was approved, declined or cancelled (YYYY-MM-DD).",
+ "approved_by": "Identifier of the co-worker who approved, declined or cancelled the request.",
+ },
+ },
+ "target_hours": {
+ "description": "Target (planned) working hours per co-worker, the denominator for utilization and overtime. One row per period the settings apply to.",
+ "docs_url": "https://docs.clockodo.com/#tag/TargetHour",
+ "columns": {
+ "id": "Unique identifier of the target hours settings.",
+ "users_id": "Identifier of the co-worker the target hours apply to.",
+ "type": "Whether the target is set weekly ('weekly') or monthly ('monthly').",
+ "date_since": "First day the target hours apply (YYYY-MM-DD).",
+ "date_until": "Last day the target hours apply (YYYY-MM-DD). Null while they still apply.",
+ "monday": "Target hours for Monday, for weekly targets.",
+ "tuesday": "Target hours for Tuesday, for weekly targets.",
+ "wednesday": "Target hours for Wednesday, for weekly targets.",
+ "thursday": "Target hours for Thursday, for weekly targets.",
+ "friday": "Target hours for Friday, for weekly targets.",
+ "saturday": "Target hours for Saturday, for weekly targets.",
+ "sunday": "Target hours for Sunday, for weekly targets.",
+ "monthly_target": "Target hours to reach in a month, for monthly targets.",
+ "compensation_daily": "Automatic time compensation per day, in minutes.",
+ "compensation_monthly": "Automatic time compensation per month, in hours.",
+ "surcharge_models_id": "Identifier of the surcharge model that applies.",
+ "test_data": "Whether the row was generated as test data.",
+ },
+ },
+ "user_reports": {
+ "description": "Yearly report per co-worker: target versus actual hours, overtime and holidays. One row per co-worker per year.",
+ "docs_url": "https://docs.clockodo.com/#tag/UserReport",
+ "columns": {
+ "users_id": "Identifier of the co-worker the report covers.",
+ "year": "Year the report covers. Added by PostHog from the requested year, which the API does not return on the row.",
+ "users_name": "Name of the co-worker.",
+ "users_email": "Email address of the co-worker.",
+ "users_number": "Personnel number of the co-worker.",
+ "sum_target": "Planned work time for the year, in seconds.",
+ "sum_hours": "Work time in the year, in seconds.",
+ "sum_reduction_used": "Overtime reduction taken in the year, in seconds.",
+ "sum_reduction_planned": "Overtime reduction planned for the rest of the year, in seconds.",
+ "overtime_carryover": "Overtime carried into the year, in seconds.",
+ "overtime_reduced": "Overtime withdrawn or paid out in the year, in seconds.",
+ "diff": "Difference between actual and planned work time for the year, in seconds.",
+ "holidays_quota": "Holiday quota for the year, in days.",
+ "holidays_carry": "Holiday days carried into the year.",
+ "sum_absence": "Days of absence in the year, broken down by absence type.",
+ "surcharges": "Surcharge hours in the year, broken down by surcharge type.",
+ "workdays": "Working days of the year.",
+ },
+ },
+ "work_times": {
+ "description": "Attendance per co-worker per day, with the clock-in/clock-out intervals of the day. Separate from the project time booked in entries.",
+ "docs_url": "https://docs.clockodo.com/#tag/WorkTime",
+ "columns": {
+ "date": "Day the attendance covers (YYYY-MM-DD).",
+ "users_id": "Identifier of the co-worker the attendance belongs to.",
+ "offset": "Work time of the day that does not come from its intervals, in seconds. Only for days before 2023-01-01.",
+ "intervals": "Clock-in/clock-out intervals of the day, each with time_since and time_until.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clockodo/clockodo.mdx b/products/warehouse_sources/backend/temporal/data_imports/sources/clockodo/clockodo.mdx
index b9b13d245493..2b468ab38e02 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clockodo/clockodo.mdx
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clockodo/clockodo.mdx
@@ -15,7 +15,7 @@ import AlphaRelease from '../_snippets/alpha-release.mdx'
<AlphaRelease />
-Clockodo is a cloud-based time-tracking and project-management tool for agencies, service firms, and freelancers. This connector syncs your Clockodo time entries, customers, projects, services, users, teams, and supporting reference data into the PostHog data warehouse so you can join tracked time and billing data with your product and revenue data.
+Clockodo is a cloud-based time-tracking and project-management tool for agencies, service firms, and freelancers. This connector syncs your Clockodo time entries, attendance, absences, target hours, yearly co-worker reports, customers, projects, services, users, teams, and supporting reference data into the PostHog data warehouse so you can join tracked time and billing data with your product and revenue data.
## Prerequisites
@@ -47,6 +47,11 @@ All Clockodo tables are **full refresh** only. The Clockodo API does not expose
<SourceTables />
+Two tables cover a fixed period rather than your whole account history, because the Clockodo API bounds what they can return:
+
+- `work_times` starts at 21 August 2023, the first day the API reports attendance for.
+- `user_reports` covers 2011 to the current year. The API needs an explicit year per request, and Clockodo launched in 2011.
+
## Troubleshooting
- **Invalid credentials** — if the connection fails to validate, double-check your account email and API key. You can regenerate the key under **Personal data** in Clockodo. Bad credentials return a `401 Unauthorized`.
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
index e27a818481ee..02cc098abf0f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clockodo/clockodo.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clockodo/clockodo.py
@@ -1,9 +1,17 @@
import dataclasses
-from datetime import UTC, datetime, timedelta
+from collections.abc import Iterator
+from datetime import UTC, date, datetime, timedelta
from typing import Any, Optional
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.temporal.data_imports.sources.clockodo.settings import (
ENTRIES_TIME_SINCE,
+ USER_REPORTS_FIRST_YEAR,
+ USER_REPORTS_TYPE,
+ USER_REPORTS_YEAR_FIELD,
+ WORK_TIMES_FIRST_DATE,
+ WORK_TIMES_WINDOW_DAYS,
ClockodoEndpointConfig,
endpoints_for_version,
)
@@ -12,11 +20,13 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
RESTAPIConfig,
rest_api_resource,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import APIKeyAuth
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
BasePaginator,
PageNumberPaginator,
SinglePagePaginator,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import RESTClient
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
@@ -28,6 +38,16 @@ CLOCKODO_BASE_URL = "https://my.clockodo.com/api"
# "[application name];[email address]". We send our app name plus the connecting user's email.
EXTERNAL_APPLICATION_NAME = "PostHog"
+# Bounds every request the swept endpoints issue, as (connect, read) seconds. Without it a
+# stalled response holds the import worker for as long as the activity deadline allows.
+REQUEST_TIMEOUT_SECONDS = (10.0, 120.0)
+
+# Endpoints that no single request can cover: work times take one co-worker and one date range
+# at a time, co-worker reports take one year at a time. Both are swept in the transport instead
+# of through a declarative resource.
+WORK_TIMES_ENDPOINT = "work_times"
+USER_REPORTS_ENDPOINT = "user_reports"
+
@dataclasses.dataclass
class ClockodoResumeConfig:
@@ -61,6 +81,93 @@ def _endpoint_params(endpoint: str, config: ClockodoEndpointConfig) -> dict[str,
return params
+def _paginator_for(config: ClockodoEndpointConfig) -> BasePaginator:
+ # Paginated responses carry the total page count at paging.count_pages, so we stop after
+ # the last page. An empty page also terminates (stop_after_empty_page default).
+ return (
+ PageNumberPaginator(base_page=1, page_param="page", total_path="paging.count_pages")
+ if config.paginated
+ else SinglePagePaginator()
+ )
+
+
+def _rest_client(api_user: str, api_key: str) -> RESTClient:
+ return RESTClient(
+ base_url=CLOCKODO_BASE_URL,
+ headers=_build_headers(api_user),
+ # The key travels via the framework auth config so its value is redacted from logs.
+ auth=APIKeyAuth(api_key=api_key, name="X-ClockodoApiKey", location="header"),
+ paginator=SinglePagePaginator(),
+ request_timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+
+
+def _rows_for(
+ client: RESTClient, config: ClockodoEndpointConfig, params: Optional[dict[str, Any]] = None
+) -> Iterator[dict[str, Any]]:
+ for page in client.paginate(
+ path=config.path,
+ params=params or {},
+ paginator=_paginator_for(config),
+ data_selector=config.data_key,
+ ):
+ yield from page
+
+
+@frozen
+class _WorkTimeWindow:
+ date_since: date
+ date_until: date
+
+
+def _work_time_windows(today: date) -> Iterator[_WorkTimeWindow]:
+ start = WORK_TIMES_FIRST_DATE
+ while start <= today:
+ end = min(start + timedelta(days=WORK_TIMES_WINDOW_DAYS - 1), today)
+ yield _WorkTimeWindow(date_since=start, date_until=end)
+ start = end + timedelta(days=1)
+
+
+def _work_time_pages(
+ client: RESTClient, users_config: ClockodoEndpointConfig, config: ClockodoEndpointConfig
+) -> Iterator[list[dict[str, Any]]]:
+ """Walk every co-worker, then every date window of that co-worker's attendance.
+
+ The endpoint requires a single users_id plus a date range, so the co-worker list is the only
+ way to reach the whole account. Rows already name their co-worker and day, so nothing has to
+ be stamped on.
+ """
+ windows = list(_work_time_windows(datetime.now(UTC).date()))
+ for user in _rows_for(client, users_config):
+ users_id = user.get("id")
+ if users_id is None:
+ continue
+ for window in windows:
+ for page in client.paginate(
+ path=config.path,
+ params={
+ "users_id": users_id,
+ "date_since": window.date_since.isoformat(),
+ "date_until": window.date_until.isoformat(),
+ },
+ paginator=SinglePagePaginator(),
+ data_selector=config.data_key,
+ ):
+ if page:
+ yield page
+
+
+def _user_report_pages(client: RESTClient, config: ClockodoEndpointConfig) -> Iterator[list[dict[str, Any]]]:
+ """Walk one year of co-worker reports at a time, stamping the year onto each row."""
+ for year in range(USER_REPORTS_FIRST_YEAR, datetime.now(UTC).year + 1):
+ rows = [
+ {**row, USER_REPORTS_YEAR_FIELD: year}
+ for row in _rows_for(client, config, params={"year": year, "type": USER_REPORTS_TYPE})
+ ]
+ if rows:
+ yield rows
+
+
def clockodo_source(
api_user: str,
api_key: str,
@@ -70,16 +177,31 @@ def clockodo_source(
resumable_source_manager: ResumableSourceManager[ClockodoResumeConfig],
api_version: str,
) -> SourceResponse:
- config = endpoints_for_version(api_version)[endpoint]
+ endpoints = endpoints_for_version(api_version)
+ config = endpoints[endpoint]
- # Clockodo only paginates a subset of resources; paginated responses carry the total
- # page count at paging.count_pages, so we stop after the last page. An empty page also
- # terminates (stop_after_empty_page default).
- paginator: BasePaginator = (
- PageNumberPaginator(base_page=1, page_param="page", total_path="paging.count_pages")
- if config.paginated
- else SinglePagePaginator()
- )
+ # The swept endpoints issue one request per co-worker or per year, so a saved page number
+ # would point into a single request rather than at the sweep's position — they restart
+ # instead of resuming, which a full refresh tolerates.
+ if endpoint == WORK_TIMES_ENDPOINT:
+ client = _rest_client(api_user, api_key)
+ users_config = endpoints["users"]
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: _work_time_pages(client, users_config, config),
+ primary_keys=config.primary_keys,
+ )
+
+ if endpoint == USER_REPORTS_ENDPOINT:
+ client = _rest_client(api_user, api_key)
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: _user_report_pages(client, config),
+ primary_keys=config.primary_keys,
+ )
+
+ # Clockodo only paginates a subset of resources.
+ paginator: BasePaginator = _paginator_for(config)
rest_config: RESTAPIConfig = {
"client": {
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
index 0f38c0840f9c..1518297b58fb 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clockodo/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clockodo/settings.py
@@ -1,5 +1,6 @@
import dataclasses
from dataclasses import dataclass, field
+from datetime import date
from products.warehouse_sources.backend.types import IncrementalField
@@ -36,6 +37,25 @@ class ClockodoEndpointConfig:
# time to also capture future-dated (planned) entries. ISO 8601 UTC, as the API requires.
ENTRIES_TIME_SINCE = "2000-01-01T00:00:00Z"
+# The work times endpoint documents that it only yields valid data from 2023-08-21 on, so the
+# sweep starts there rather than at the account's first time entry.
+WORK_TIMES_FIRST_DATE = date(2023, 8, 21)
+# Work times are requested one co-worker and one date range at a time, and the endpoint
+# documents no page param even though it returns a paging block. A row is one day of one
+# co-worker, so a window of at most a year stays well inside the API's 1000-row page, which is
+# what makes a single-page fetch per window complete.
+WORK_TIMES_WINDOW_DAYS = 365
+
+# The co-worker report endpoint requires an explicit year and offers no way to discover the
+# account's first one. Clockodo launched in 2011, so no account holds a report before then.
+USER_REPORTS_FIRST_YEAR = 2011
+# Report detail level: 0 keeps the report at year level. The deeper levels nest month, week and
+# day arrays inside each row, which is a report shape rather than a table shape.
+USER_REPORTS_TYPE = 0
+# Year the report covers. The rows name their co-worker but not the year requested, so the
+# sweep stamps it on to keep them unique across years.
+USER_REPORTS_YEAR_FIELD = "year"
+
CLOCKODO_ENDPOINTS_V2: dict[str, ClockodoEndpointConfig] = {
"customers": ClockodoEndpointConfig(
@@ -83,6 +103,35 @@ CLOCKODO_ENDPOINTS_V2: dict[str, ClockodoEndpointConfig] = {
description="Time entries across the full account history. Full refresh only — the API "
"has no server-side modified-since filter.",
),
+ "absences": ClockodoEndpointConfig(
+ name="absences",
+ path="v4/absences",
+ data_key="data",
+ description="Vacation, sick leave and other absences of each co-worker.",
+ ),
+ "target_hours": ClockodoEndpointConfig(
+ name="target_hours",
+ path="targethours",
+ data_key="targethours",
+ description="Target (planned) working hours per co-worker, and the periods they apply to.",
+ ),
+ "user_reports": ClockodoEndpointConfig(
+ name="user_reports",
+ path="userreports",
+ data_key="userreports",
+ primary_keys=["users_id", USER_REPORTS_YEAR_FIELD],
+ description="Yearly co-worker report: target versus actual hours, overtime and holidays. "
+ f"One row per co-worker per year from {USER_REPORTS_FIRST_YEAR} on.",
+ ),
+ "work_times": ClockodoEndpointConfig(
+ name="work_times",
+ path="v2/workTimes",
+ data_key="work_time_days",
+ primary_keys=["users_id", "date"],
+ description="Attendance per co-worker per day, with the clock-in/clock-out intervals of "
+ f"the day. Starts at {WORK_TIMES_FIRST_DATE.isoformat()}, the first day the API reports. "
+ "Separate from the project time in `entries`.",
+ ),
}
@@ -96,8 +145,10 @@ def _v3(config: ClockodoEndpointConfig, path: str) -> ClockodoEndpointConfig:
return dataclasses.replace(config, path=path, data_key="data", paginated=True)
-# v3 reuses the v2 configs for the two resources Clockodo did not decommission (surcharges,
-# entries) and points the other six at their v3/v4 successors from the deprecation notice.
+# v3 reuses the v2 configs for the resources Clockodo did not decommission (surcharges, entries)
+# and for the four this source only ever reached through their current route (absences,
+# target_hours, user_reports, work_times), and points the other six at their v3/v4 successors
+# from the deprecation notice.
CLOCKODO_ENDPOINTS_V3: dict[str, ClockodoEndpointConfig] = {
**CLOCKODO_ENDPOINTS_V2,
"customers": _v3(CLOCKODO_ENDPOINTS_V2["customers"], "v3/customers"),
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
index 44cee34e4703..de7e161b7913 100644
--- 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
@@ -1,5 +1,5 @@
import json
-from datetime import UTC, datetime
+from datetime import UTC, date, datetime, timedelta
from typing import Any
import pytest
@@ -14,6 +14,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.clockodo.c
ClockodoResumeConfig,
_endpoint_params,
_format_z,
+ _work_time_windows,
clockodo_source,
validate_credentials,
)
@@ -23,6 +24,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.clockodo.s
CLOCKODO_ENDPOINTS_V2,
CLOCKODO_SUPPORTED_VERSIONS,
ENDPOINTS,
+ USER_REPORTS_FIRST_YEAR,
+ WORK_TIMES_FIRST_DATE,
+ WORK_TIMES_WINDOW_DAYS,
endpoints_for_version,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import APIKeyAuth
@@ -317,6 +321,129 @@ class TestVersionDispatch:
assert params[1]["page"] == 2
+class TestWorkTimeWindows:
+ @time_machine.travel("2026-06-29T12:00:00Z", tick=False)
+ def test_windows_tile_the_reported_period_without_gaps(self) -> None:
+ windows = list(_work_time_windows(date(2026, 6, 29)))
+
+ # A gap between windows silently drops the attendance days inside it, an overlap
+ # re-fetches them, and a window longer than the API's page would truncate one.
+ assert windows[0].date_since == WORK_TIMES_FIRST_DATE
+ assert windows[-1].date_until == date(2026, 6, 29)
+ for window, next_window in zip(windows, windows[1:]):
+ assert next_window.date_since == window.date_until + timedelta(days=1)
+ for window in windows:
+ assert window.date_since <= window.date_until
+ assert (window.date_until - window.date_since).days < WORK_TIMES_WINDOW_DAYS
+
+
+class TestWorkTimesSweep:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ @time_machine.travel("2024-06-29T12:00:00Z", tick=False)
+ def test_fans_out_over_co_workers_and_windows(self, MockSession) -> None:
+ session = MockSession.return_value
+ params, _auths, urls = _wire(
+ session,
+ [
+ _response([{"id": 7}, {"id": 9}], data_key="users"),
+ _response([{"users_id": 7, "date": "2024-06-03"}], data_key="work_time_days"),
+ _response([{"users_id": 9, "date": "2024-06-04"}], data_key="work_time_days"),
+ ],
+ )
+
+ rows = _rows(_source("work_times", _make_manager()))
+
+ # The endpoint reaches one co-worker at a time, so the co-worker list is the only way
+ # to cover the account.
+ assert "/api/v2/users" in urls[0]
+ assert [p.get("users_id") for p in params[1:]] == [7, 9]
+ assert all(p["date_since"] == WORK_TIMES_FIRST_DATE.isoformat() for p in params[1:])
+ assert all(p["date_until"] == "2024-06-29" for p in params[1:])
+ assert [(r["users_id"], r["date"]) for r in rows] == [(7, "2024-06-03"), (9, "2024-06-04")]
+
+ @parameterized.expand(
+ [
+ (CLOCKODO_API_VERSION_V2, "users", "/api/v2/users"),
+ (CLOCKODO_API_VERSION_V3, "data", "/api/v3/users"),
+ ]
+ )
+ @mock.patch(CLIENT_SESSION_PATCH)
+ @time_machine.travel("2024-06-29T12:00:00Z", tick=False)
+ def test_co_worker_list_follows_the_pinned_version(
+ self, api_version: str, users_data_key: str, expected_users_path: str, MockSession
+ ) -> None:
+ session = MockSession.return_value
+ _params, _auths, urls = _wire(
+ session,
+ [
+ _response([{"id": 7}], data_key=users_data_key, count_pages=1),
+ _response([{"users_id": 7, "date": "2024-06-03"}], data_key="work_time_days"),
+ ],
+ )
+
+ rows = _rows(_source("work_times", _make_manager(), api_version=api_version))
+
+ # A v2 path or envelope under a v3 pin reaches a decommissioned endpoint or yields no
+ # co-workers, which would sweep no work times at all.
+ assert expected_users_path in urls[0]
+ assert "/api/v2/workTimes" in urls[1]
+ assert [r["users_id"] for r in rows] == [7]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ @time_machine.travel("2024-06-29T12:00:00Z", tick=False)
+ def test_no_co_workers_sweeps_nothing(self, MockSession) -> None:
+ session = MockSession.return_value
+ _wire(session, [_response([], data_key="users")])
+
+ assert _rows(_source("work_times", _make_manager())) == []
+ assert session.send.call_count == 1
+
+
+class TestUserReportsSweep:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ @time_machine.travel("2026-06-29T12:00:00Z", tick=False)
+ def test_walks_every_year_and_stamps_it_on_each_row(self, MockSession) -> None:
+ session = MockSession.return_value
+ years = list(range(USER_REPORTS_FIRST_YEAR, 2027))
+ params, _auths, _urls = _wire(
+ session,
+ [_response([{"users_id": 3}], data_key="userreports") for _ in years],
+ )
+
+ rows = _rows(_source("user_reports", _make_manager()))
+
+ # The API requires an explicit year and returns it on no row, so without the stamp
+ # every year would merge onto the same primary key.
+ assert [p["year"] for p in params] == years
+ assert [r["year"] for r in rows] == years
+ assert {r["users_id"] for r in rows} == {3}
+ # Year level only — the deeper report types nest month, week and day arrays per row.
+ assert {p["type"] for p in params} == {0}
+
+
+class TestSinglePageEndpoints:
+ @parameterized.expand(
+ [
+ ("absences", "data", "/api/v4/absences"),
+ ("target_hours", "targethours", "/api/targethours"),
+ ]
+ )
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_reads_the_whole_collection_in_one_request(
+ self, endpoint: str, data_key: str, expected_path: str, MockSession
+ ) -> None:
+ session = MockSession.return_value
+ params, _auths, urls = _wire(session, [_response([{"id": 1}, {"id": 2}], data_key=data_key)])
+
+ rows = _rows(_source(endpoint, _make_manager()))
+
+ assert expected_path in urls[0]
+ assert session.send.call_count == 1
+ # Neither endpoint documents a page param, and neither returns a paging block.
+ assert "page" not in params[0]
+ assert [r["id"] for r in rows] == [1, 2]
+
+
class TestValidateCredentials:
@parameterized.expand([("ok", 200, True), ("unauthorized", 401, False), ("forbidden", 403, False)])
@mock.patch(CLOCKODO_SESSION_PATCH)