: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): implement hoorayhr import source (#72636)
Tom Owersac18066e5720
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 12ea6bdec15f..43f34821e873 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -268,6 +268,7 @@ the row lists both.| hibob | HTTP | requests | ✅ || honeybadger | HTTP | requests | ✅ || honeycomb | HTTP | requests | ✅ |+| hoorayhr | HTTP | requests + `rest_source.RESTClient` | ✅ || humanitix | HTTP | requests | ✅ || hubplanner | HTTP | requests | ✅ || hubspot | HTTP | requests | ✅ |@@ -763,7 +764,6 @@ doesn't conflict with concurrent PRs.- hightouch- honeybadger- honeycomb-- hoorayhr- hubplanner- humanitix- ikasdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/hoorayhr.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/hoorayhr.pyindex 22ef97db23d5..a45dde3d40ca 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/hoorayhr.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/hoorayhr.py@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass HoorayHRSourceConfig(config.Config):- pass+ api_key: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hoorayhr/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hoorayhr/canonical_descriptions.pynew file mode 100644index 000000000000..d75070506df1--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hoorayhr/canonical_descriptions.py@@ -0,0 +1,272 @@+"""Canonical, documentation-sourced descriptions for HoorayHR endpoints and columns.++Sourced from the official HoorayHR OpenAPI spec (https://api.hoorayhr.io/swagger.json, rendered at+https://api.hoorayhr.io/documentation). Keyed by the table names in `settings.py`+`HOORAYHR_ENDPOINTS`, which match the `ExternalDataSchema.name` of a synced HoorayHR table. Columns+absent here fall back to LLM enrichment.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_DOCS_URL = "https://api.hoorayhr.io/documentation"++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "users": {+ "description": "An employee (or other user) in the HoorayHR company, with personal, contact, and employment details.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique id of the user.",+ "entityId": "Unique id of the entity the user belongs to.",+ "isDemoData": "Whether the user is demo data created during the company's trial period.",+ "email": "E-mail address of the user.",+ "status": "Status of the user. 0 = NOT INVITED, 1 = INVITED, 2 = ACTIVE, 3 = ARCHIVED.",+ "isAdmin": "Tiny-int indicating if the user has admin rights. 0 = NON-ADMIN, 1 = ADMIN.",+ "isHidden": "Hidden users are not visible in the application to non-admins.",+ "timezone": "Timezone of the user.",+ "teams": "Stringified array containing the team ids the user is part of.",+ "companyStartDate": "Start of employment date.",+ "companyEndDate": "End of employment date.",+ "seniorityDate": "Historical start date of employment.",+ "firstName": "First name of the user.",+ "lastName": "Last name of the user.",+ "displayName": "Generated full display name of the user based on name fields and lastNameUsage.",+ "birthdate": "Birthdate of the user.",+ "jobTitle": "Job title of the user.",+ "phone": "Phone number of the user.",+ "employeeNumber": "Employee number of the user.",+ "locale": "The user's language preference.",+ "invitedByUserId": "Unique user id of the inviter.",+ "onBoardedAt": "Date the user completed the onboarding wizard after the first login.",+ "currency": "ISO 4217 code of the user's currency, used as the default for expense claims.",+ "travelAllowance": "Default travel allowance per kilometer for travel expenses.",+ "createdAt": "Creation date of the user.",+ "updatedAt": "Last updated date of the user.",+ },+ },+ "time_off": {+ "description": "A time-off item: leave requests, holidays, overtime, and budget transactions.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "ID of the time-off item.",+ "userId": "Unique id of the user the time-off item belongs to.",+ "isPrivate": "Tiny-int indicating if the time-off item is private.",+ "budgetCalculated": "The calculated time for a time-off item in hours.",+ "budgetAdjustment": "For mutations, the amount of time added to or subtracted from the user's budget, in hours.",+ "budgetTotal": "The total time-off budget of a user in hours for this year.",+ "notes": "Optional reason given for the time-off request.",+ "start": "Start date and time of the time-off.",+ "end": "End date and time of the time-off.",+ "status": "Status of the time-off item. 1 = REQUESTED, 2 = DENIED, 3 = APPROVED, 4 = WITHDRAWN.",+ "leaveTypeId": "ID of the corresponding leave type. Can be null in case of holidays.",+ "timeOffType": "Enum describing the type of time-off item (e.g. LEAVE, HOLIDAY, overtime and transaction variants).",+ "leaveUnit": "The unit of the time-off item.",+ "holidayId": "If the time-off item was created from a holiday, the id of that holiday.",+ "labelIds": "List of ids belonging to labels.",+ "timezone": "The time zone of the time-off item, set from the user's time zone.",+ "userIdApproved": "Unique id of the user that approved the time-off item.",+ "reply": "Optional text with the reason for approval or denial of the request.",+ "createdAt": "Creation date of the time-off item.",+ "updatedAt": "Last updated date of the time-off item.",+ },+ },+ "leave_types": {+ "description": "A leave type configured for the company (e.g. vacation, parental leave), including budget calculation rules.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "ID of the leave type.",+ "updatedBy": "ID of the user who updated the item last.",+ "name": "Name of the leave type.",+ "color": "Color of the leave type.",+ "icon": "Icon of the leave type.",+ "budget": "Default budget for the leave type.",+ "default": "Tiny-int indicating whether the leave type is assigned automatically to new users.",+ "calculationMethod": "Enum describing the way the budget should be calculated.",+ "periodOffset": "Number of months the leave period is offset from January.",+ "unpaidLeave": "Tiny-int indicating whether the time of leave is marked as unpaid.",+ "leaveInDays": "Tiny-int indicating if the budgets are defined in days instead of minutes.",+ "leaveTypeSystemCategory": "Enum describing a pre-defined leave type.",+ "isLegacy": "Tiny-int indicating whether the leave type is considered a legacy leave type.",+ "archivedAt": "Timestamp of the leave type being archived.",+ "createdAt": "Creation date of the leave type.",+ "updatedAt": "Last updated date of the leave type.",+ },+ },+ "contracts": {+ "description": "An employment contract belonging to a user.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "ID of the contract.",+ "userId": "Unique id of the user the contract belongs to.",+ "userIdApproved": "Unique id of the user that added the contract.",+ "contractStartDate": "Start date of the contract.",+ "contractEndDate": "End date of the contract.",+ "probationEndDate": "End date of the probation period of the contract.",+ "signedContract": "Tiny-int indicating if the contract has been signed.",+ "notes": "Optional remarks about the contract.",+ "status": "Status of the contract.",+ "type": "The type of contract. 1 = fixed-term, 2 = permanent, 3 = internship.",+ "createdAt": "Creation date of the contract.",+ "updatedAt": "Last updated date of the contract.",+ },+ },+ "sick_leave_dossiers": {+ "description": "A sick leave dossier for a user, grouping the phases of one continuous case of absence.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique id of the sick leave dossier.",+ "userId": "Unique id of the user that the dossier is about.",+ "timezone": "The time zone of the sick leave dossier, set from the user's time zone.",+ "phases": "The phases of the dossier (reported sick, partial recovery, recovery).",+ "createdAt": "The creation date of the dossier.",+ "updatedAt": "The date that the dossier or any of its phases was last updated.",+ },+ },+ "sick_leave_phases": {+ "description": "A phase within a sick leave dossier, tracking (partial) absence over a period.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique id of the sick leave phase.",+ "sickLeaveDossierId": "Unique id of the sick leave dossier the phase belongs to.",+ "userIdReported": "Unique id of the user who reported the REPORTED_SICK phase.",+ "userIdConfirmed": "Unique id of the user who confirmed the REPORTED_RECOVERY phase.",+ "percentage": "The percentage of hours worked during the period, used in the calculation of the hours.",+ "expectedTotal": "The amount of minutes the phase is expected to last, based on the start date and expected return date.",+ "actualTotal": "The amount of minutes the phase lasts, based on the start date and end date.",+ "startDate": "The start date and time of the phase.",+ "expectedReturn": "The expected return date.",+ "calculatedEndDate": "The end date and time of the phase.",+ "status": "The type of phase.",+ "notes": "A text field for notes related to the phase.",+ "createdAt": "The creation date of the phase.",+ "updatedAt": "The date that the phase was last updated.",+ },+ },+ "time_tracking": {+ "description": "A time tracking entry: hours a user logged on a day, split into activities.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique id of the time tracking entry.",+ "userId": "Unique id of the user the entry belongs to.",+ "startDate": "Start date of the entry.",+ "endDate": "End date of the entry.",+ "period": "The period the entry covers.",+ "status": "Status of the entry.",+ "activities": "The activities logged within the entry.",+ "createdAt": "Creation date of the entry.",+ "updatedAt": "Last updated date of the entry.",+ },+ },+ "availability": {+ "description": "A user's work schedule (availability), used to calculate leave budgets and calendar days.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "ID of the availability item.",+ "userId": "Unique id of the user the schedule belongs to.",+ "start": "Start of the work schedule.",+ "end": "End of the work schedule.",+ "schedule": "The actual work schedule, showing how long someone works in a day.",+ "workweek": "The amount of minutes in the schedule; the average of odd and even weeks when they differ.",+ "calendarSchedule": "The schedule describing what an actual calendar day looks like, used to calculate leave budget.",+ "calendarScheduleWorkweek": "The amount of minutes in calendarSchedule; the average of odd and even weeks when they differ.",+ "createdAt": "Creation date of the availability item.",+ "updatedAt": "Last updated date of the availability item.",+ },+ },+ "entities": {+ "description": "A legal entity of the company that users can belong to.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "ID of the entity.",+ "name": "Name of the entity.",+ "createdAt": "Creation date of the entity.",+ "updatedAt": "Last updated date of the entity.",+ },+ },+ "labels": {+ "description": "A label used to categorize items across HoorayHR services (documents, workflows, time off, and more).",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "ID of the label.",+ "documentCategoryId": "ID of the parent document category.",+ "workflowCategoryId": "ID of the parent workflow category.",+ "name": "Name of the label.",+ "type": "Enum of the service the label is assigned to.",+ "systemCategoryType": "Type of system pre-defined labels.",+ "archivedAt": "Timestamp of the label being archived.",+ "createdAt": "Creation date of the label.",+ "updatedAt": "Last updated date of the label.",+ "deletedAt": "Deleted date of the label.",+ },+ },+ "employment_terms": {+ "description": "An employment term (e.g. salary, hours) that can be assigned to users.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique id of the employment term.",+ "title": "Title of the employment term.",+ "type": "Determines the type of the values for assignments of this employment term.",+ "frequency": "Frequency of the employment term.",+ "systemType": "System type of the employment term.",+ "salarySubTypes": "The salary sub types (only set for the employment term with system type SALARY).",+ "createdAt": "Creation date of the employment term.",+ "updatedAt": "Last updated date of the employment term.",+ },+ },+ "employment_term_assignments": {+ "description": "An assignment of an employment term to a user, with its value over a period.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique id of the employment term assignment.",+ "userId": "The user the employment term is assigned to.",+ "employmentTermId": "The ID of the employment term.",+ "startDate": "The start date of the assignment, or the termination date if isTerminated is true.",+ "currency": "ISO 4217 code of the currency of the assignment.",+ "value": "Value of the assignment. Terminated assignments do not have a value.",+ "isTerminated": "Whether the employment term assignment is terminated.",+ "status": "Status of the assignment: FUTURE for assignments starting in the future, otherwise ACTIVE.",+ "salarySubTypeId": "The salary sub type the assignment is linked to (SALARY system term only).",+ "note": "Optional note for the assignment.",+ "createdAt": "Creation date of the assignment.",+ "updatedAt": "Last updated date of the assignment.",+ },+ },+ "document_categories": {+ "description": "A document category. COMPANY categories hold shared documents; PERSONAL categories hold per-user documents.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "ID of the document category.",+ "name": "Name of the category.",+ "color": "Display color of the category.",+ "icon": "Icon identifier.",+ "type": "Category type: COMPANY (shared, optionally scoped to teams) or PERSONAL (per-user).",+ "teams": "Team IDs linked to this category; an empty array means visible to the whole company.",+ "createdAt": "Creation date of the category.",+ "updatedAt": "Last updated date of the category.",+ },+ },+ "work_location_categories": {+ "description": "A work location category (e.g. office, home) users can select when indicating where they work.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique id of the work location category.",+ "name": "Name of the work location category.",+ "systemCategoryType": "System category type of the work location.",+ "icon": "Icon of the work location category.",+ "archivedAt": "Date when the work location category was archived.",+ "createdAt": "Creation date of the item.",+ "updatedAt": "Last updated date of the item.",+ },+ },+ "teams_information": {+ "description": "A team in the company, with its leaders and members.",+ "docs_url": _DOCS_URL,+ "columns": {+ "teamId": "The team id.",+ "teamName": "The team name.",+ "teamLeadersIds": "The user ids of the team leaders.",+ "teamMembersIds": "The user ids of the team members.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hoorayhr/hoorayhr.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hoorayhr/hoorayhr.pynew file mode 100644index 000000000000..9be6e583ee50--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hoorayhr/hoorayhr.py@@ -0,0 +1,61 @@+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+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.hoorayhr.settings import (+ HOORAYHR_BASE_URL,+ HOORAYHR_ENDPOINTS,+)+++def hoorayhr_source(+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+) -> SourceResponse:+ config = HOORAYHR_ENDPOINTS[endpoint]++ rest_config: RESTAPIConfig = {+ "client": {+ "base_url": HOORAYHR_BASE_URL,+ "headers": {"Accept": "application/json"},+ # Both personal API keys (pk_ prefixed) and partner OAuth access tokens are sent as+ # `Authorization: Bearer <token>`.+ "auth": {"type": "bearer", "token": api_key},+ # No pagination is documented on any list endpoint — each table is a single bare-array+ # page, full refresh only.+ "paginator": "single_page",+ },+ "resource_defaults": None,+ "resources": [{"name": endpoint, "endpoint": {"path": config.path}}],+ }++ resource = rest_api_resource(rest_config, team_id, job_id, None)++ has_partition_key = config.partition_key is not None+ return SourceResponse(+ name=endpoint,+ items=lambda: resource,+ primary_keys=config.primary_keys,+ # Month is the coarsest datetime tier; the auto-repartitioner only steps finer, so this+ # gives it the most headroom. Endpoints without a stable creation field stay unpartitioned.+ partition_mode="datetime" if has_partition_key else None,+ partition_format="month" if has_partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )+++def validate_credentials(api_key: str) -> bool:+ # /leave-types is the cheapest authenticated read: a handful of rows per company. The probe runs+ # before the source is saved, so `redact_values` masks the API key in tracked telemetry here too.+ ok, _status = validate_via_probe(+ lambda: make_tracked_session(redact_values=(api_key,)),+ f"{HOORAYHR_BASE_URL}{HOORAYHR_ENDPOINTS['leave_types'].path}",+ headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},+ timeout=15,+ )+ return okdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hoorayhr/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hoorayhr/settings.pynew file mode 100644index 000000000000..50b79ef2df8b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hoorayhr/settings.py@@ -0,0 +1,57 @@+from dataclasses import dataclass, field+from typing import Optional++HOORAYHR_BASE_URL = "https://api.hoorayhr.io"+++@dataclass+class HoorayHREndpointConfig:+ name: str+ """Table name we expose to the user (snake_case)."""+ path: str+ """Path relative to the API root (e.g. ``/time-off``)."""+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ partition_key: Optional[str] = None+ """Stable creation-time field used for Delta partitioning; None leaves the table unpartitioned."""+++# HoorayHR's public API (OpenAPI spec at https://api.hoorayhr.io/swagger.json) exposes no pagination,+# no cursors, and no server-side timestamp filters on any of these list endpoints — each returns the+# full collection as one bare JSON array, so every table is full refresh only (matching the Airbyte+# connector's capabilities). Report-style endpoints that require date-range parameters+# (/attendance-report, /working-today, /public-holidays) are point-in-time views, not warehouse+# tables, and are deliberately not synced.+HOORAYHR_ENDPOINTS: dict[str, HoorayHREndpointConfig] = {+ "users": HoorayHREndpointConfig(name="users", path="/users", partition_key="createdAt"),+ "time_off": HoorayHREndpointConfig(name="time_off", path="/time-off", partition_key="createdAt"),+ "leave_types": HoorayHREndpointConfig(name="leave_types", path="/leave-types", partition_key="createdAt"),+ "contracts": HoorayHREndpointConfig(name="contracts", path="/contracts", partition_key="createdAt"),+ "sick_leave_dossiers": HoorayHREndpointConfig(+ name="sick_leave_dossiers", path="/sick-leave-dossiers", partition_key="createdAt"+ ),+ "sick_leave_phases": HoorayHREndpointConfig(+ name="sick_leave_phases", path="/sick-leave-phases", partition_key="createdAt"+ ),+ "time_tracking": HoorayHREndpointConfig(name="time_tracking", path="/time-tracking", partition_key="createdAt"),+ "availability": HoorayHREndpointConfig(name="availability", path="/availability", partition_key="createdAt"),+ "entities": HoorayHREndpointConfig(name="entities", path="/entities", partition_key="createdAt"),+ "labels": HoorayHREndpointConfig(name="labels", path="/labels", partition_key="createdAt"),+ "employment_terms": HoorayHREndpointConfig(+ name="employment_terms", path="/employment-terms", partition_key="createdAt"+ ),+ "employment_term_assignments": HoorayHREndpointConfig(+ name="employment_term_assignments", path="/employment-term-assignments", partition_key="createdAt"+ ),+ "document_categories": HoorayHREndpointConfig(+ name="document_categories", path="/document-categories", partition_key="createdAt"+ ),+ "work_location_categories": HoorayHREndpointConfig(+ name="work_location_categories", path="/work-location-categories", partition_key="createdAt"+ ),+ # Rows are teams (with member/leader user-id arrays), keyed by teamId; no timestamps exposed.+ "teams_information": HoorayHREndpointConfig(+ name="teams_information", path="/teams-information", primary_keys=["teamId"]+ ),+}++ENDPOINTS = tuple(HOORAYHR_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hoorayhr/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hoorayhr/source.pyindex 4f72536cc83b..776dd970fd5c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/hoorayhr/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hoorayhr/source.py@@ -1,21 +1,43 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.hoorayhr import (HoorayHRSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.hoorayhr.hoorayhr import (+ hoorayhr_source,+ validate_credentials as validate_hoorayhr_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.hoorayhr.settings import ENDPOINTSfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.registerclass HoorayHRSource(SimpleSource[HoorayHRSourceConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ api_docs_url = "https://api.hoorayhr.io/documentation"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.HOORAYHR@@ -26,7 +48,64 @@ class HoorayHRSource(SimpleSource[HoorayHRSourceConfig]):name=SchemaExternalDataSourceType.HOORAY_HR,category=DataWarehouseSourceCategory.HR___RECRUITING,label="HoorayHR",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your HoorayHR API key to pull your HR data (users, time off, sick leave, contracts, and more) into the PostHog Data warehouse.++You need the admin role in your HoorayHR company to create an API key: go to [Settings → API keys](https://app.hoorayhr.io/settings/api-keys) and click "New API key". The key (prefixed `pk_`) is shown only once, so copy it right away.""",iconPath="/static/services/hoorayhr.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/hoorayhr",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="pk_...",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.hoorayhr.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Your HoorayHR API key is invalid or has been revoked. Create a new key under Settings → API keys in HoorayHR, then reconnect.",+ "403 Client Error": "Your HoorayHR API key is not authorized for this data. API keys act as the user who created them, so make sure that user still has the admin role.",+ }++ def get_schemas(+ self,+ config: HoorayHRSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # HoorayHR's API exposes no pagination, cursors, or server-side timestamp filters, so every+ # table is full refresh only.+ return build_endpoint_schemas(ENDPOINTS, {}, names)++ def validate_credentials(+ self, config: HoorayHRSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_hoorayhr_credentials(config.api_key):+ return True, None++ return False, "HoorayHR rejected the credentials. Check the API key is correct and hasn't been revoked."++ def source_for_pipeline(self, config: HoorayHRSourceConfig, inputs: SourceInputs) -> SourceResponse:+ return hoorayhr_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hoorayhr/tests/test_hoorayhr.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hoorayhr/tests/test_hoorayhr.pynew file mode 100644index 000000000000..ce3f63a6ac6f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hoorayhr/tests/test_hoorayhr.py@@ -0,0 +1,120 @@+import json+from typing import Any++import pytest+from unittest import mock++from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.hoorayhr.hoorayhr import (+ hoorayhr_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.hoorayhr.settings import (+ ENDPOINTS,+ HOORAYHR_BASE_URL,+ HOORAYHR_ENDPOINTS,+)++# RESTClient builds its session via make_tracked_session in the rest_client module.+CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+# validate_credentials builds its own tracked session in the hoorayhr module.+HOORAYHR_SESSION_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.hoorayhr.hoorayhr.make_tracked_session"+)+++def _response(body: Any, status: int = 200) -> Response:+ resp = Response()+ resp.status_code = status+ resp._content = json.dumps(body).encode()+ return resp+++def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:+ """Wire a mock session and snapshot each request's URL + auth headers at prepare time."""+ session.headers = {}+ seen: list[dict[str, Any]] = []++ def _prepare(request: Any) -> mock.MagicMock:+ prepared = mock.MagicMock()+ prepared.headers = {}+ if request.auth is not None:+ request.auth(prepared)+ seen.append({"url": request.url, "auth_headers": dict(prepared.headers)})+ return prepared++ session.prepare_request.side_effect = _prepare+ session.send.side_effect = responses+ return seen+++def _source(endpoint: str):+ return hoorayhr_source("pk_test_key", endpoint, team_id=1, job_id="j")+++def _batches(source_response) -> list[list[dict[str, Any]]]:+ return [list(page) for page in source_response.items()]+++class TestHoorayHRTransport:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_time_off_yields_single_batch_with_bearer_auth(self, MockSession) -> None:+ session = MockSession.return_value+ seen = _wire(session, [_response([{"id": 1}, {"id": 2}])])++ batches = _batches(_source("time_off"))++ assert batches == [[{"id": 1}, {"id": 2}]]+ # No pagination anywhere on HoorayHR's API — exactly one request per endpoint.+ assert session.send.call_count == 1+ assert seen[0]["url"] == f"{HOORAYHR_BASE_URL}/time-off"+ assert seen[0]["auth_headers"]["Authorization"] == "Bearer pk_test_key"+++class TestSourceResponseConfig:+ def test_all_endpoints_buildable_with_declared_keys(self) -> None:+ for endpoint in ENDPOINTS:+ response = _source(endpoint)+ assert response.name == endpoint+ assert response.primary_keys == HOORAYHR_ENDPOINTS[endpoint].primary_keys++ def test_partitioning_uses_stable_creation_field(self) -> None:+ users = _source("users")+ assert users.partition_mode == "datetime"+ assert users.partition_format == "month"+ assert users.partition_keys == ["createdAt"]++ def test_teams_information_is_unpartitioned_and_keyed_by_team_id(self) -> None:+ teams = _source("teams_information")+ assert teams.primary_keys == ["teamId"]+ assert teams.partition_mode is None+ assert teams.partition_keys is None+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ "status, expected",+ [(200, True), (401, False), (403, False), (500, False)],+ )+ @mock.patch(HOORAYHR_SESSION_PATCH)+ def test_status_mapping(self, mock_session: mock.MagicMock, status: int, expected: bool) -> None:+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=status)+ assert validate_credentials("pk_k") is expected++ @mock.patch(HOORAYHR_SESSION_PATCH)+ def test_connection_error_returns_false(self, mock_session: mock.MagicMock) -> None:+ mock_session.return_value.get.side_effect = Exception("boom")+ assert validate_credentials("pk_k") is False++ @mock.patch(HOORAYHR_SESSION_PATCH)+ def test_probes_leave_types_with_bearer_header(self, mock_session: mock.MagicMock) -> None:+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)+ validate_credentials("pk_k")++ call = mock_session.return_value.get.call_args+ called_url = call.args[0] if call.args else call.kwargs["url"]+ assert called_url == f"{HOORAYHR_BASE_URL}/leave-types"+ assert call.kwargs["headers"]["Authorization"] == "Bearer pk_k"+ # The key must be registered for redaction in tracked telemetry.+ assert mock_session.call_args.kwargs["redact_values"] == ("pk_k",)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hoorayhr/tests/test_hoorayhr_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hoorayhr/tests/test_hoorayhr_source.pynew file mode 100644index 000000000000..6421038548ad--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hoorayhr/tests/test_hoorayhr_source.py@@ -0,0 +1,120 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.hoorayhr import (+ HoorayHRSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.hoorayhr.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.hoorayhr.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.hoorayhr.source import HoorayHRSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestHoorayHRSource:+ def setup_method(self) -> None:+ self.source = HoorayHRSource()+ self.team_id = 123+ self.config = HoorayHRSourceConfig(api_key="pk_test_key")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.HOORAYHR++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "HoorayHR"+ assert config.label == "HoorayHR"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # A finished source is visible to users — the scaffold's unreleasedSource flag must be gone.+ assert not config.unreleasedSource+ assert config.iconPath == "/static/services/hoorayhr.png"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/hoorayhr"++ def test_api_key_field_is_secret_password(self) -> None:+ config = self.source.get_source_config+ assert [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)] == ["api_key"]+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig))+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_get_schemas_covers_all_endpoints_as_full_refresh(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)+ assert all(s.supports_incremental is False for s in schemas)+ assert all(s.supports_append is False for s in schemas)+ assert all(s.incremental_fields == [] for s in schemas)++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["users"])+ assert [s.name for s in schemas] == ["users"]++ def test_documented_tables_render_for_public_docs(self) -> None:+ # lists_tables_without_credentials=True + static get_schemas means the doc's Supported tables+ # section is populated without a live connection.+ tables = self.source.get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)+ assert all("Full refresh" in t["sync_methods"] for t in tables)++ def test_canonical_descriptions_keyed_by_endpoint_names(self) -> None:+ # A renamed endpoint would silently orphan its curated descriptions.+ assert set(CANONICAL_DESCRIPTIONS.keys()) == set(ENDPOINTS)++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://api.hoorayhr.io/users",+ "403 Client Error: Forbidden for url: https://api.hoorayhr.io/time-off",+ ],+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @pytest.mark.parametrize(+ "unrelated_error",+ ["429 Client Error: Too Many Requests", "500 Server Error", "Connection reset by peer"],+ )+ def test_non_retryable_errors_ignore_transient(self, unrelated_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in unrelated_error for key in non_retryable)++ @pytest.mark.parametrize(+ "valid_creds, expected_valid, expected_message",+ [+ (True, True, None),+ (False, False, "HoorayHR rejected the credentials. Check the API key is correct and hasn't been revoked."),+ ],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.hoorayhr.source.validate_hoorayhr_credentials"+ )+ def test_validate_credentials(+ self,+ mock_validate: mock.MagicMock,+ valid_creds: bool,+ expected_valid: bool,+ expected_message: str | None,+ ) -> None:+ mock_validate.return_value = valid_creds+ is_valid, message = self.source.validate_credentials(self.config, self.team_id)+ assert is_valid is expected_valid+ assert message == expected_message+ mock_validate.assert_called_once_with("pk_test_key")++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.hoorayhr.source.hoorayhr_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_hoorayhr_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "time_off"++ self.source.source_for_pipeline(self.config, inputs)++ mock_hoorayhr_source.assert_called_once()+ kwargs = mock_hoorayhr_source.call_args.kwargs+ assert kwargs["api_key"] == "pk_test_key"+ assert kwargs["endpoint"] == "time_off"+ assert kwargs["team_id"] is inputs.team_id+ assert kwargs["job_id"] is inputs.job_id