: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(data-warehouse): add four Everhour tables for timesheets and time off (#107694)
Tom Owersceb17578c197
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 88b6951f3b59..2a37ba05d3bb 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@@ -2941,7 +2941,7 @@ Note: The Redoc page embeds the full OpenAPI document. Its entire GET surface is## Everhour — gaps-Today (9): `assignments`, `clients`, `expenses`, `invoices`, `projects`, `tasks`, `time_records`, `timecards`, `users`+Today (13): `allocations`, `assignments`, `clients`, `expense_categories`, `expenses`, `invoices`, `projects`, `tasks`, `time_off_types`, `time_records`, `timecards`, `timesheets`, `users`Diffed against: <https://everhour.docs.apiary.io/api-description-document>@@ -2949,10 +2949,10 @@ Diffed against: <https://everhour.docs.apiary.io/api-description-document>- [x] `GET /expenses` — project cost records that pair with time_records for margin analysis (high)- [x] `GET /timecards, GET /users/{user_id}/timecards` — clock-in/clock-out attendance records, distinct from time_records (high)- [x] `GET /resource-planner/assignments` — scheduled/planned work per user, project and task - planned vs actual (high)-- [ ] `GET /expenses/categories` — lookup table resolving the category id carried on every expense (high)-- [ ] `GET /timesheets, GET /users/{user_id}/timesheets` — weekly timesheet approval state and transitions (medium)-- [ ] `GET /resource-planner/time-off-types` — lookup resolving time-off type ids on assignments/allocations (medium)-- [ ] `GET /allocations` — time-off and capacity allocations per user (medium)+- [x] `GET /expenses/categories` — lookup table resolving the category id carried on every expense (high)+- [x] `GET /timesheets, GET /users/{user_id}/timesheets` — weekly timesheet approval state and transitions (medium)+- [x] `GET /resource-planner/time-off-types` — lookup resolving time-off type ids on assignments/allocations (medium)+- [x] `GET /allocations` — time-off and capacity allocations per user (medium)- [ ] `GET /projects/{project_id}/sections` — lookup resolving the section id on tasks (medium)- [ ] `GET /projects/{project_id}/fields` — custom field definitions needed to interpret task custom field values (medium)- [ ] `GET /dashboards/projects, /dashboards/clients, /dashboards/users` — prebuilt report aggregates by project, client and member (low)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/canonical_descriptions.pyindex 6977aead83b9..563da0e4f3ae 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/canonical_descriptions.py@@ -123,6 +123,18 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"attachments": "Receipts and other files attached to the expense.",},},+ "expense_categories": {+ "description": "Expense category definitions, resolving the `category` id carried on every expense row.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique identifier for the expense category.",+ "name": "Name of the category, for example 'Mileage'.",+ "color": "Hex colour the category is shown in.",+ "unitBased": "Whether expenses in this category are entered as a number of units rather than an amount.",+ "unitName": "Name of the unit for unit-based categories, for example 'Miles'.",+ "unitPrice": "Cost of one unit, in cents.",+ },+ },"timecards": {"description": "Clock-in and clock-out attendance per user per day. Separate from time records, which log time against tasks.","docs_url": _DOCS_URL,@@ -150,4 +162,52 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"time": "Scheduled time across the period, in seconds.",},},+ "timesheets": {+ "description": "A user's week of tracked work and its approval state. Fanned out over every team member.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique identifier for the timesheet: the user id and the week id concatenated.",+ "user": "Identifier of the user the timesheet belongs to.",+ "week": "The week the timesheet covers (id, start and end dates, and which day the week starts on).",+ "tasks": "Tasks added to the timesheet.",+ "dailyTime": "Time totalled per day, in seconds, including time tracked without a task.",+ "taskTime": "Time totals per task on the timesheet, in seconds.",+ "approval": "Approval state of the week, with the reviewer and the history of submit, approve, reject and discard actions.",+ "timecards": "Clock-in and clock-out records falling in the week.",+ "timeOffAssignments": "Time off scheduled during the week.",+ },+ },+ "time_off_types": {+ "description": "Time off category definitions, resolving the `timeOffType` id carried on assignments and allocations.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique identifier for the time off type.",+ "name": "Name of the type, for example 'Sick'.",+ "color": "Hex colour the type is shown in.",+ "paid": "Whether time off of this type is paid.",+ "description": "Free-text description of the type.",+ },+ },+ "allocations": {+ "description": "How much time off of each type a user is entitled to over a period, and how much of it they have used.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique identifier for the allocation.",+ "user": "Identifier of the user the allocation belongs to.",+ "timeOffType": "Identifier of the time off type being allocated.",+ "startDate": "First day of the period the allocation covers.",+ "endDate": "Last day of the period the allocation covers.",+ "contractStartDate": "Date the user's contract starts, used to accrue days part way through a period.",+ "days": "Total days available in the period.",+ "daysCarried": "Days carried over from the previous period.",+ "daysAllocated": "Days accrued so far in the period.",+ "daysUsed": "Days already taken from the allocation.",+ "accrualFrequency": "How days accrue: 'daily' over the period, or 'immediately' in full.",+ "restrictOverAllocation": "Whether the user is blocked from booking more days than allocated.",+ "completed": "Whether the allocation period has finished.",+ "notes": "Free-text notes on the allocation.",+ "createdBy": "Identifier of the user who created the allocation.",+ "createdAt": "When the allocation was created.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/everhour.com-doc.md b/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/everhour.com-doc.mdindex 2d9e1a4d5d4f..8338cd462484 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/everhour.com-doc.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/everhour.com-doc.md@@ -29,7 +29,7 @@ import AlphaRelease from "../\_snippets/alpha-release.mdx"<AlphaRelease />-[Everhour](https://everhour.com) is a time-tracking, budgeting, and resource-planning tool for teams. This source syncs your Everhour clients, projects, tasks, team members, time records, invoices, expenses, timecards, and resource planner assignments into the PostHog data warehouse so you can join time-tracking data with your product and revenue data.+[Everhour](https://everhour.com) is a time-tracking, budgeting, and resource-planning tool for teams. This source syncs your Everhour clients, projects, tasks, team members, time records, invoices, expenses, expense categories, timecards, timesheets, and resource planner assignments, time off types and allocations into the PostHog data warehouse so you can join time-tracking data with your product and revenue data.## Prerequisites@@ -53,7 +53,7 @@ Paste the key into the API key field when connecting the source in PostHog. The**Time records** support incremental sync: PostHog uses Everhour's server-side `from`/`to` date window to pull only entries on or after the last synced date.-Every other table syncs as **full refresh**. Clients, projects, users, tasks, invoices, and expenses have no server-side change timestamp to filter on. Timecards and assignments do accept a date filter, but it selects rows by the day they cover rather than the day they changed, so it cannot tell PostHog what is new since the last sync.+Every other table syncs as **full refresh**. Clients, projects, users, tasks, invoices, expenses, expense categories, timesheets, time off types, and allocations have no server-side change timestamp to filter on. Timecards and assignments do accept a date filter, but it selects rows by the day they cover rather than the day they changed, so it cannot tell PostHog what is new since the last sync.## Configuration@@ -71,6 +71,9 @@ A few notes:- **Timecards and time records are different things.** A time record is time logged against a task. A timecard is a clock-in and clock-out for one person on one day. Timecards carry no id of their own, so the table is keyed on `(user, date)`.- **Invoice line items are nested.** Each invoice row carries its line items in the `invoiceItems` column rather than in a separate table.- **Assignments cover planned work and time off.** The `type` column tells the two apart, and the rows reach into the future because they describe scheduled work.+- **Timesheets are fetched per person.** Everhour's team-wide timesheet endpoint returns one week at a time, so PostHog reads each member's own timesheet history instead, going back about five years. Each row is one person's week, with its tasks, daily totals, timecards, scheduled time off, and approval history nested inside it.+- **Lookup tables resolve the ids on other rows.** Expense categories name the `category` on an expense, and time off types name the `timeOffType` on an assignment or an allocation.+- **Allocations are entitlements, not bookings.** A row says how many days off of one type a person has over a period and how many they have used. The time off they actually booked is in assignments.## Troubleshootingdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/everhour.py b/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/everhour.pyindex a88da0614de3..e6dcb1ea62e8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/everhour.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/everhour.py@@ -15,6 +15,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typfrom products.warehouse_sources.backend.temporal.data_imports.sources.everhour.settings import (EVERHOUR_ENDPOINTS,EverhourEndpointConfig,+ FanOut,)EVERHOUR_BASE_URL = "https://api.everhour.com"@@ -31,6 +32,9 @@ EARLIEST_FROM_DATE = "2015-01-01"# Matches the parent project id in a fan-out tasks URL: /projects/{project_id}/tasks_PROJECT_ID_RE = re.compile(r"/projects/([^/?]+)/tasks")+# The endpoint each fan-out mode draws its parent ids from.+_FAN_OUT_PARENT_ENDPOINTS: dict[FanOut, str] = {"project": "projects", "user": "users"}+class EverhourRetryableError(Exception):pass@@ -164,19 +168,20 @@ def _build_initial_urls(logger: FilteringBoundLogger,session: requests.Session,) -> list[str]:- """Resolve the set of base request URLs for an endpoint, fanning out over projects as needed."""+ """Resolve the set of base request URLs for an endpoint, fanning out over parents as needed."""if config.fan_out == "none":return [_build_base_url(config, window)]- if config.fan_out == "project":- projects_config = EVERHOUR_ENDPOINTS["projects"]- projects_url = _build_base_url(projects_config, None)- return [- _with_query(config.path_template.format(project_id=project["id"]), {"limit": config.page_size})- for project in _iter_all_items(projects_url, projects_config.page_size, headers, logger, session)- ]+ parent_endpoint = _FAN_OUT_PARENT_ENDPOINTS.get(config.fan_out)+ if parent_endpoint is None:+ raise ValueError(f"Unknown fan_out mode: {config.fan_out}")- raise ValueError(f"Unknown fan_out mode: {config.fan_out}")+ parent_config = EVERHOUR_ENDPOINTS[parent_endpoint]+ parent_url = _build_base_url(parent_config, None)+ return [+ _with_query(config.path_template.format(parent_id=parent["id"]), {"limit": config.page_size})+ for parent in _iter_all_items(parent_url, parent_config.page_size, headers, logger, session)+ ]def _parent_project_id(url: str) -> Optional[str]:@@ -233,7 +238,8 @@ def get_rows(pages_on_current = 0while current is not None:- items = _fetch_page(_with_query(current, {"offset": offset}), headers, logger, session)+ page_url = _with_query(current, {"offset": offset}) if config.paginates else current+ items = _fetch_page(page_url, headers, logger, session)pages_on_current += 1new_items = [item for item in items if _row_key(item, config.dedupe_keys) not in seen_keys]@@ -246,7 +252,7 @@ def get_rows(# A full page of genuinely new rows means there may be more; a short page (or one that# surfaced no new rows, i.e. offset was ignored) ends this URL.- would_continue = len(items) >= config.page_size and len(new_items) > 0+ would_continue = config.paginates and len(items) >= config.page_size and len(new_items) > 0if would_continue and pages_on_current >= MAX_PAGES_PER_URL:logger.warning(f"Everhour: hit max page cap while paginating {current}")has_more = would_continue and pages_on_current < MAX_PAGES_PER_URLdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/settings.pyindex 4f0a1b71fd72..5e74c63816f8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/settings.py@@ -11,19 +11,24 @@ ASSIGNMENTS_DAYS_AHEAD = 5 * 365# How an endpoint's request URLs are derived:# "none" -> a single top-level list endpoint (no parent fan-out)# "project" -> one request per project (fan out over /projects)-FanOut = Literal["none", "project"]+# "user" -> one request per team member (fan out over /team/users)+FanOut = Literal["none", "project", "user"]@frozenclass EverhourEndpointConfig:name: strfan_out: FanOut- # Relative path appended to the API base. Fan-out task paths carry a single ``{project_id}``- # placeholder (the parent project id); top-level paths have no placeholder.+ # Relative path appended to the API base. Fan-out paths carry a single ``{parent_id}``+ # placeholder (the parent project or user id); top-level paths have no placeholder.path_template: str# Everhour caps most list endpoints at a small page size and paginates with limit/offset.# /time-records is capped at 50 per page; the reference endpoints comfortably take 100.page_size: int = 100+ # Whether the endpoint is walked with ``offset``. When False it is fetched in one request and+ # ``page_size`` is still sent as ``limit``, because some Everhour endpoints give ``limit`` a+ # different meaning (on /users/{id}/timesheets it caps the number of weeks) and take no offset.+ paginates: bool = Trueprimary_keys: list[str] = field(default_factory=lambda: ["id"])# Fields identifying a row while paginating, used to spot a page the API re-served because it# ignored ``offset``. Kept separate from ``primary_keys`` because an injected parent id is only@@ -66,7 +71,7 @@ EVERHOUR_ENDPOINTS: dict[str, EverhourEndpointConfig] = {"tasks": EverhourEndpointConfig(name="tasks",fan_out="project",- path_template="/projects/{project_id}/tasks",+ path_template="/projects/{parent_id}/tasks",primary_keys=["project_id", "id"],include_parent_id_as="project_id",),@@ -100,6 +105,11 @@ EVERHOUR_ENDPOINTS: dict[str, EverhourEndpointConfig] = {path_template="/expenses",partition_key="date",),+ "expense_categories": EverhourEndpointConfig(+ name="expense_categories",+ fan_out="none",+ path_template="/expenses/categories",+ ),"timecards": EverhourEndpointConfig(name="timecards",fan_out="none",@@ -121,6 +131,31 @@ EVERHOUR_ENDPOINTS: dict[str, EverhourEndpointConfig] = {supports_date_window=True,window_days_ahead=ASSIGNMENTS_DAYS_AHEAD,),+ "timesheets": EverhourEndpointConfig(+ name="timesheets",+ fan_out="user",+ path_template="/users/{parent_id}/timesheets",+ # The team-level /timesheets needs an explicit weekId per request, so the per-user endpoint+ # is the only one that can walk history. Its `limit` counts weeks (defaulting to 10), and+ # it takes no offset, so ask for ~5 years in a single request per user.+ page_size=260,+ paginates=False,+ # `id` is the user id and week id concatenated, so it is unique across the whole table.+ # The week is a nested object, leaving no top-level date to partition on.+ ),+ "time_off_types": EverhourEndpointConfig(+ name="time_off_types",+ fan_out="none",+ path_template="/resource-planner/time-off-types",+ ),+ "allocations": EverhourEndpointConfig(+ name="allocations",+ fan_out="none",+ path_template="/allocations",+ # `startDate` moves whenever the entitlement period is re-cut, so partition on the+ # creation date instead.+ partition_key="createdAt",+ ),}ENDPOINTS = tuple(EVERHOUR_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/tests/test_everhour.py b/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/tests/test_everhour.pyindex c494ff404bff..127dff713131 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/tests/test_everhour.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/tests/test_everhour.py@@ -159,6 +159,19 @@ class TestBuildInitialUrls:f"{EVERHOUR_BASE_URL}/projects/p2/tasks?limit=100",]+ @mock.patch(f"{EVERHOUR_MODULE}._iter_all_items")+ def test_user_fan_out_draws_parents_from_the_team_users_endpoint(self, mock_iter_items: mock.MagicMock) -> None:+ mock_iter_items.return_value = iter([{"id": 11}, {"id": 22}])+ urls = _build_initial_urls(EVERHOUR_ENDPOINTS["timesheets"], None, {}, mock.MagicMock(), mock.MagicMock())++ # The parent walk must hit /team/users, not /users.+ assert mock_iter_items.call_args.args[0] == f"{EVERHOUR_BASE_URL}/team/users?limit=100"+ # `limit` on the timesheets endpoint is a week count, so it carries the endpoint's own value.+ assert urls == [+ f"{EVERHOUR_BASE_URL}/users/11/timesheets?limit=260",+ f"{EVERHOUR_BASE_URL}/users/22/timesheets?limit=260",+ ]+class TestGetRows:@mock.patch(f"{EVERHOUR_MODULE}.make_tracked_session")@@ -285,6 +298,28 @@ class TestGetRows:assert len(rows) == 101assert "offset=100" in mock_fetch.call_args_list[1].args[0]+ @mock.patch(f"{EVERHOUR_MODULE}.make_tracked_session")+ @mock.patch(f"{EVERHOUR_MODULE}._build_initial_urls")+ @mock.patch(f"{EVERHOUR_MODULE}._fetch_page")+ def test_unpaginated_endpoint_fetches_each_url_once_without_offset(+ self, mock_fetch: mock.MagicMock, mock_build_urls: mock.MagicMock, _mock_session: mock.MagicMock+ ) -> None:+ # /users/{id}/timesheets takes no offset, and its `limit` caps weeks rather than page size,+ # so a full page must not be read as "there may be more".+ urls = [+ f"{EVERHOUR_BASE_URL}/users/11/timesheets?limit=260",+ f"{EVERHOUR_BASE_URL}/users/22/timesheets?limit=260",+ ]+ mock_build_urls.return_value = list(urls)+ mock_fetch.side_effect = [_items(0, 260), _items(260, 260)]++ manager = _make_manager()+ rows = [row for batch in get_rows("key", "timesheets", mock.MagicMock(), manager) for row in batch]++ assert len(rows) == 520+ assert mock_fetch.call_count == 2+ assert [call.args[0] for call in mock_fetch.call_args_list] == urls+@mock.patch(f"{EVERHOUR_MODULE}.make_tracked_session")@mock.patch(f"{EVERHOUR_MODULE}._build_initial_urls")def test_no_urls_yields_nothing(self, mock_build_urls: mock.MagicMock, _mock_session: mock.MagicMock) -> None: