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(bamboohr): sync employee history, time off policies and timesheets (#99809)

Tom Owersba02c9d173d6
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 6fca3d9aa01a..42a5baa6958d 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
@@ -698,14 +698,14 @@ Note: The developer hub serves a Swagger UI whose visible initializer points at
## BambooHR — **thin**
-Today (6): `employees`, `meta_fields`, `meta_lists`, `meta_users`, `time_off_requests`, `time_off_types`
+Today (13): `employee_compensation`, `employee_employment_status`, `employee_job_info`, `employee_time_off_balances`, `employee_time_off_policies`, `employees`, `meta_fields`, `meta_lists`, `meta_users`, `time_off_policies`, `time_off_requests`, `time_off_types`, `timesheet_entries`
Diffed against: <https://documentation.bamboohr.com/sitemap.xml>
-- [ ] `GET employee table data / changed employee table data` — jobInfo, compensation and employmentStatus history tables - the state-transition history behind every HR metric (promotions, pay changes, terminations); today only current employee fields are synced (high)
-- [ ] `GET time off policies + employee time off policies` — lookup resolving the policy behind time_off_requests and accrual rules (high)
-- [ ] `GET time off balance` — current accrued balance per employee - the headline time-off metric, absent even though requests and types are synced (high)
-- [ ] `GET timesheet entries / time tracking records` — hours worked, the core fact table for the whole time-tracking product (high)
+- [x] `GET employee table data / changed employee table data` — jobInfo, compensation and employmentStatus history tables - the state-transition history behind every HR metric (promotions, pay changes, terminations); today only current employee fields are synced (high)
+- [x] `GET time off policies + employee time off policies` — lookup resolving the policy behind time_off_requests and accrual rules (high)
+- [x] `GET time off balance` — current accrued balance per employee - the headline time-off metric, absent even though requests and types are synced (high)
+- [x] `GET timesheet entries / time tracking records` — hours worked, the core fact table for the whole time-tracking product (high)
- [ ] `GET applications, application details, job summaries, statuses (ATS)` — recruiting funnel - candidates, applications and stage; an entire product area with zero coverage (high)
- [ ] `GET company locations / list locations` — lookup resolving the location ID on employees (high)
- [ ] `GET who's out` — resolved out-of-office calendar, commonly wanted alongside time_off_requests (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bamboohr/bamboohr.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bamboohr/bamboohr.py
index 856a91a2948d..1e8822dc09dc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bamboohr/bamboohr.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bamboohr/bamboohr.py
@@ -1,37 +1,58 @@
import re
import dataclasses
-from datetime import UTC, datetime, timedelta
-from typing import Any, Optional
+from collections.abc import Iterable, Iterator
+from datetime import UTC, date, datetime, timedelta
+from typing import Any, Optional, cast
from requests import Response
from products.warehouse_sources.backend.temporal.data_imports.sources.bamboohr.settings import (
BAMBOOHR_ENDPOINTS,
+ EMPLOYEE_TABLE_EMPLOYEE_ID,
+ EMPLOYEE_TABLE_LAST_CHANGED,
BambooHREndpointConfig,
+ ChunkedDateWindow,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import parse_datetime_value
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.rest_source.auth import HttpBasicAuth
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ build_dependent_resource,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
BaseNextUrlPaginator,
+ 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.rest_source.typing import (
+ ClientConfig,
+ Endpoint,
)
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
# BambooHR's API is served through a single gateway host; the company subdomain is a path segment.
-# Confirmed live: the gateway returns 401 (not 404) for the v1 paths below, so the route shape is correct.
+# Confirmed live: the gateway returns 401 (not 404) for the versioned paths in settings.py, so the route
+# shape is correct.
BAMBOOHR_API_HOST = "https://api.bamboohr.com/api/gateway.php"
# Basic auth uses the API key as the username and any non-empty string as the password.
BAMBOOHR_BASIC_AUTH_PASSWORD = "x"
# Credential validation is a single cheap probe; keep it snappy so source creation doesn't feel hung.
VALIDATE_TIMEOUT_SECONDS = 10
+# Bounds each sync request, so a gateway that accepts the connection then stalls cannot hold a
+# worker open indefinitely.
+SYNC_TIMEOUT_SECONDS = 120
# Time-off endpoints require an explicit window; widen it enough to capture all history and pending future requests.
TIME_OFF_WINDOW_START = "2000-01-01"
TIME_OFF_FUTURE_DAYS = 730
+# The employee-table history endpoints require a `since` cursor, so a full refresh needs a floor
+# old enough to predate any company's records.
+EMPLOYEE_TABLE_HISTORY_START = datetime(2000, 1, 1, tzinfo=UTC)
# A BambooHR company subdomain is the "<company>" slug from <company>.bamboohr.com — letters, digits,
# and hyphens only. It's an editable, non-secret field spliced straight into the request path, so pin
@@ -50,14 +71,14 @@ def _validate_subdomain(subdomain: str) -> None:
raise ValueError(f"Invalid BambooHR subdomain: {subdomain!r}")
[email protected](frozen=False)
class BambooHRResumeConfig:
next_url: str
def _base_url(subdomain: str) -> str:
_validate_subdomain(subdomain)
- return f"{BAMBOOHR_API_HOST}/{subdomain}/v1"
+ return f"{BAMBOOHR_API_HOST}/{subdomain}"
class BambooHRBasicAuth(HttpBasicAuth):
@@ -126,6 +147,97 @@ def _selector_for(config: BambooHREndpointConfig) -> tuple[str | None, bool]:
return None, True
+def _endpoint_extra(config: BambooHREndpointConfig) -> Endpoint:
+ """The response-shape half of an endpoint config, for the fan-out helper's endpoint overrides."""
+ data_selector, data_selector_required = _selector_for(config)
+ extra: Endpoint = {"data_selector_required": data_selector_required}
+ if data_selector is not None:
+ extra["data_selector"] = data_selector
+ return extra
+
+
+def _rest_client(base_url: str, api_key: str) -> RESTClient:
+ return RESTClient(
+ base_url=base_url,
+ headers={"Accept": "application/json"},
+ auth=BambooHRBasicAuth(username=api_key, password=BAMBOOHR_BASIC_AUTH_PASSWORD),
+ # Neither stream built on this client paginates: each response carries its whole collection.
+ paginator=SinglePagePaginator(),
+ # Pins every request to the gateway host the API key was issued for.
+ allowed_hosts=[],
+ request_timeout=SYNC_TIMEOUT_SECONDS,
+ )
+
+
+def _employee_table_rows(body: Any) -> Iterator[dict[str, Any]]:
+ """Flatten one ``employees/changed/tables/{table}`` response into rows.
+
+ The response groups rows under a map of employee id — ``{"employees": {"123": {"lastChanged":
+ ..., "rows": [...]}}}`` — so the employee id and the change timestamp exist only on the map
+ entry. Both are stamped onto every row; the map key wins over any ``employeeId`` in the row
+ because it is what the API keyed the group by.
+ """
+ employees = body.get("employees") if isinstance(body, dict) else None
+ if not isinstance(employees, dict):
+ raise ValueError(
+ "Required an 'employees' object in the response body, got "
+ f"{type(employees).__name__}. The API response shape may have changed."
+ )
+ for employee_id, entry in employees.items():
+ if not isinstance(entry, dict):
+ continue
+ last_changed = entry.get(EMPLOYEE_TABLE_LAST_CHANGED)
+ for row in entry.get("rows") or []:
+ yield {
+ **row,
+ EMPLOYEE_TABLE_EMPLOYEE_ID: str(employee_id),
+ EMPLOYEE_TABLE_LAST_CHANGED: last_changed,
+ }
+
+
+def _employee_table_pages(
+ client: RESTClient, config: BambooHREndpointConfig, since: datetime
+) -> Iterator[list[dict[str, Any]]]:
+ for page in client.paginate(path=config.path, params={"since": since.isoformat()}):
+ for body in page:
+ rows = list(_employee_table_rows(body))
+ # Rows arrive grouped by employee, in no order — sort so the cursor really is
+ # ascending and the pipeline's watermark can only move forward over rows we yielded.
+ rows.sort(key=_last_changed_sort_key)
+ if rows:
+ yield rows
+
+
+def _last_changed_sort_key(row: dict[str, Any]) -> datetime:
+ return parse_datetime_value(row.get(EMPLOYEE_TABLE_LAST_CHANGED)) or datetime.min.replace(tzinfo=UTC)
+
+
+def _chunked_window_pages(
+ client: RESTClient, config: BambooHREndpointConfig, window: ChunkedDateWindow
+) -> Iterator[list[dict[str, Any]]]:
+ today = datetime.now(UTC).date()
+ start = today - timedelta(days=window.history_days)
+ while start <= today:
+ end = min(start + timedelta(days=window.chunk_days - 1), today)
+ yield from _window_pages(client, config, start, end)
+ start = end + timedelta(days=1)
+
+
+def _window_pages(
+ client: RESTClient, config: BambooHREndpointConfig, start: date, end: date
+) -> Iterator[list[dict[str, Any]]]:
+ params = {"start": start.isoformat(), "end": end.isoformat()}
+ for page in client.paginate(path=config.path, params=params, data_selector_required=True):
+ if page:
+ yield page
+
+
+def _employee_table_since(should_use_incremental_field: bool, db_incremental_field_last_value: Any) -> datetime:
+ if not should_use_incremental_field:
+ return EMPLOYEE_TABLE_HISTORY_START
+ return parse_datetime_value(db_incremental_field_last_value) or EMPLOYEE_TABLE_HISTORY_START
+
+
def bamboohr_source(
subdomain: str,
api_key: str,
@@ -133,10 +245,64 @@ def bamboohr_source(
team_id: int,
job_id: str,
resumable_source_manager: ResumableSourceManager[BambooHRResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
) -> SourceResponse:
config = BAMBOOHR_ENDPOINTS[endpoint]
base_url = _base_url(subdomain)
+ if config.employee_table is not None:
+ client = _rest_client(base_url, api_key)
+ since = _employee_table_since(should_use_incremental_field, db_incremental_field_last_value)
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: _employee_table_pages(client, config, since),
+ primary_keys=config.primary_keys,
+ )
+
+ if config.chunked_date_window is not None:
+ client = _rest_client(base_url, api_key)
+ window = config.chunked_date_window
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: _chunked_window_pages(client, config, window),
+ primary_keys=config.primary_keys,
+ )
+
+ client_config: ClientConfig = {
+ "base_url": base_url,
+ "headers": {"Accept": "application/json"},
+ # Auth goes through the framework config so the API key is redacted from logs;
+ # only the non-secret Accept header is set on the session.
+ "auth": BambooHRBasicAuth(username=api_key, password=BAMBOOHR_BASIC_AUTH_PASSWORD),
+ "paginator": BambooHRPaginator(),
+ }
+
+ if config.fanout is not None:
+ parent_config = BAMBOOHR_ENDPOINTS[config.fanout.parent_name]
+ resource = cast(
+ Iterable[Any],
+ build_dependent_resource(
+ endpoint_configs=BAMBOOHR_ENDPOINTS,
+ child_endpoint=endpoint,
+ fanout=config.fanout,
+ client_config=client_config,
+ path_format_values={},
+ team_id=team_id,
+ job_id=job_id,
+ db_incremental_field_last_value=None,
+ # BambooHR list endpoints take no page-size parameter.
+ page_size_param=None,
+ parent_endpoint_extra=_endpoint_extra(parent_config),
+ child_endpoint_extra=_endpoint_extra(config),
+ ),
+ )
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: resource,
+ primary_keys=config.primary_keys,
+ )
+
params: dict[str, Any] = {}
if config.requires_date_window:
end = (datetime.now(UTC) + timedelta(days=TIME_OFF_FUTURE_DAYS)).strftime("%Y-%m-%d")
@@ -145,14 +311,7 @@ def bamboohr_source(
data_selector, data_selector_required = _selector_for(config)
rest_config: RESTAPIConfig = {
- "client": {
- "base_url": base_url,
- "headers": {"Accept": "application/json"},
- # Auth goes through the framework config so the API key is redacted from logs;
- # only the non-secret Accept header is set on the session.
- "auth": BambooHRBasicAuth(username=api_key, password=BAMBOOHR_BASIC_AUTH_PASSWORD),
- "paginator": BambooHRPaginator(),
- },
+ "client": client_config,
"resources": [
{
"name": endpoint,
@@ -205,7 +364,7 @@ def validate_credentials(subdomain: str, api_key: str, schema_name: Optional[str
(``schema_name is None``) since users may only grant the scopes they intend to sync.
"""
try:
- url = f"{_base_url(subdomain)}/meta/fields"
+ url = f"{_base_url(subdomain)}/v1/meta/fields"
except ValueError:
return False, INVALID_SUBDOMAIN_MESSAGE
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bamboohr/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bamboohr/canonical_descriptions.py
index 5628c77f1dd8..b3dbfe1a7582 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bamboohr/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bamboohr/canonical_descriptions.py
@@ -57,6 +57,91 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"icon": "Icon associated with the time-off type.",
},
},
+ "employee_job_info": {
+ "description": "A dated row from an employee's job information history table. A row records the job title, department, division, location and reporting line an employee held from a given effective date. The columns depend on how the company has configured the table.",
+ "docs_url": "https://documentation.bamboohr.com/reference/get-changed-employee-table-data",
+ "columns": {
+ "id": "Unique identifier for the row within the jobInfo table.",
+ "employeeId": "ID of the employee the row belongs to.",
+ "lastChanged": "Time at which any field on this employee's record last changed.",
+ "date": "The effective date of the row.",
+ },
+ },
+ "employee_compensation": {
+ "description": "A dated row from an employee's compensation history table. A row records the pay rate, pay type, pay schedule and overtime status an employee held from a given effective date. The columns depend on how the company has configured the table.",
+ "docs_url": "https://documentation.bamboohr.com/reference/get-changed-employee-table-data",
+ "columns": {
+ "id": "Unique identifier for the row within the compensation table.",
+ "employeeId": "ID of the employee the row belongs to.",
+ "lastChanged": "Time at which any field on this employee's record last changed.",
+ "date": "The effective date of the row.",
+ },
+ },
+ "employee_employment_status": {
+ "description": "A dated row from an employee's employment status history table. A row records the employment status and status change an employee held from a given effective date, including terminations. The columns depend on how the company has configured the table.",
+ "docs_url": "https://documentation.bamboohr.com/reference/get-changed-employee-table-data",
+ "columns": {
+ "id": "Unique identifier for the row within the employmentStatus table.",
+ "employeeId": "ID of the employee the row belongs to.",
+ "lastChanged": "Time at which any field on this employee's record last changed.",
+ "date": "The effective date of the row.",
+ },
+ },
+ "time_off_policies": {
+ "description": "A time-off policy configured for the company, governing how a time-off type accrues.",
+ "docs_url": "https://documentation.bamboohr.com/reference/list-time-off-policies",
+ "columns": {
+ "id": "Unique identifier for the policy.",
+ "timeOffTypeId": "ID of the time-off type the policy belongs to.",
+ "name": "Name of the policy.",
+ "type": "The policy type: accruing, discretionary or manual.",
+ "effectiveDate": "Deprecated by BambooHR and always empty.",
+ },
+ },
+ "employee_time_off_policies": {
+ "description": "The assignment of a time-off policy to an employee.",
+ "docs_url": "https://documentation.bamboohr.com/reference/list-employee-time-off-policies-v1_1",
+ "columns": {
+ "employeeId": "ID of the employee the policy is assigned to.",
+ "timeOffPolicyId": "ID of the assigned time-off policy.",
+ "timeOffTypeId": "ID of the time-off type the policy covers.",
+ "accrualStartDate": "Date accruals started, empty for manual and unlimited policies.",
+ },
+ },
+ "employee_time_off_balances": {
+ "description": "An employee's current time-off balance for one time-off type, as of the day the table was synced.",
+ "docs_url": "https://documentation.bamboohr.com/reference/get-time-off-balance",
+ "columns": {
+ "employeeId": "ID of the employee the balance belongs to.",
+ "timeOffType": "ID of the time-off type the balance covers.",
+ "name": "Name of the time-off type.",
+ "units": "The unit the balance is measured in (hours or days).",
+ "balance": "Balance available as of the calculation date.",
+ "end": "The date the balance was calculated as of.",
+ "policyType": "The policy type behind the balance: accruing, discretionary or manual.",
+ "usedYearToDate": "Amount of this time-off type used so far this year.",
+ },
+ },
+ "timesheet_entries": {
+ "description": "A single tracked block of time worked by an employee, either clocked or entered as hours.",
+ "docs_url": "https://documentation.bamboohr.com/reference/list-timesheet-entries",
+ "columns": {
+ "id": "Unique identifier for the timesheet entry.",
+ "employeeId": "ID of the employee who worked the time.",
+ "type": "Whether the entry was clocked or entered as hours.",
+ "date": "The date the time was worked.",
+ "start": "Time the employee clocked in.",
+ "end": "Time the employee clocked out.",
+ "timezone": "Timezone the entry was recorded in.",
+ "hours": "Hours worked.",
+ "note": "Note attached to the entry.",
+ "projectInfo": "The project and task the time was booked to.",
+ "approved": "Whether the entry has been approved.",
+ "approvedAt": "Time at which the entry was approved.",
+ "createdAt": "Time at which the entry was created.",
+ "updatedAt": "Time at which the entry was last updated.",
+ },
+ },
"meta_fields": {
"description": "A field definition available in the company's BambooHR account.",
"docs_url": "https://documentation.bamboohr.com/reference/metadata-get-a-list-of-fields",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bamboohr/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bamboohr/settings.py
index 03dd7cebc4e5..8b31b50f15eb 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bamboohr/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bamboohr/settings.py
@@ -1,6 +1,10 @@
from dataclasses import dataclass, field
from typing import Literal
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ DependentEndpointConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
from products.warehouse_sources.backend.types import IncrementalField
# How records are laid out in a BambooHR JSON response.
@@ -8,11 +12,30 @@ from products.warehouse_sources.backend.types import IncrementalField
# "dict" — the records are a JSON object keyed by id (e.g. ``meta/users``); we take ``.values()``
DataShape = Literal["list", "dict"]
+# The employee-table history endpoints group their rows under a map of employee id, and only that
+# map carries the employee id and the timestamp of their last change — see ``bamboohr.py``.
+EMPLOYEE_TABLE_LAST_CHANGED = "lastChanged"
+EMPLOYEE_TABLE_EMPLOYEE_ID = "employeeId"
-@dataclass
+
+@dataclass(frozen=True)
+class ChunkedDateWindow:
+ """Walk an endpoint's date range in slices instead of asking for all of it at once.
+
+ For endpoints that take a start/end window and return every matching row in one unpaginated
+ response, so a wide window puts a whole company's history in a single response body.
+ """
+
+ history_days: int
+ chunk_days: int
+
+
+@dataclass(frozen=False)
class BambooHREndpointConfig:
name: str
- # Path relative to ``/api/gateway.php/{subdomain}/v1/``.
+ # Path relative to ``/api/gateway.php/{subdomain}/``, including the API version segment.
+ # BambooHR revises individual endpoints under a ``v1_1`` segment of the same v1 API, so the
+ # segment belongs to the endpoint rather than to the source.
path: str
primary_keys: list[str]
# JSON key holding the records, or ``None`` when the body itself is the collection.
@@ -20,43 +43,103 @@ class BambooHREndpointConfig:
data_shape: DataShape = "list"
# Some endpoints (time off) reject requests without an explicit date window.
requires_date_window: bool = False
- # No BambooHR endpoint we ship exposes a verified server-side "modified since" filter
- # that also returns full records, so every stream is full-refresh for now. See bamboohr.py.
+ # Set on the employee-table history streams, naming the BambooHR table they read.
+ employee_table: str | None = None
+ # Set when the endpoint's window has to be fetched in slices.
+ chunked_date_window: ChunkedDateWindow | None = None
+ # Fan-out over the employee directory, for endpoints addressed by a single employee.
+ fanout: DependentEndpointConfig | None = None
+ # Only the employee-table history endpoints expose a verified server-side "changed since"
+ # filter; every other stream is full-refresh. See bamboohr.py.
incremental_fields: list[IncrementalField] = field(default_factory=list)
+ default_incremental_field: str | None = None
+ # BambooHR list endpoints take no page-size parameter; declared to satisfy the fan-out
+ # helper's endpoint protocol.
+ page_size: int = 100
+
+
+_EMPLOYEE_FANOUT = DependentEndpointConfig(
+ parent_name="employees",
+ resolve_param="employeeId",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": EMPLOYEE_TABLE_EMPLOYEE_ID},
+)
+
+
+def _employee_table_endpoint(name: str, table: str) -> BambooHREndpointConfig:
+ return BambooHREndpointConfig(
+ name=name,
+ path=f"v1/employees/changed/tables/{table}",
+ employee_table=table,
+ # The row id is unique within its table, not across employees, so pair the two.
+ primary_keys=[EMPLOYEE_TABLE_EMPLOYEE_ID, "id"],
+ incremental_fields=[incremental_field(EMPLOYEE_TABLE_LAST_CHANGED)],
+ default_incremental_field=EMPLOYEE_TABLE_LAST_CHANGED,
+ )
BAMBOOHR_ENDPOINTS: dict[str, BambooHREndpointConfig] = {
"employees": BambooHREndpointConfig(
name="employees",
- path="employees/directory",
+ path="v1/employees/directory",
data_key="employees",
primary_keys=["id"],
),
+ "employee_job_info": _employee_table_endpoint("employee_job_info", "jobInfo"),
+ "employee_compensation": _employee_table_endpoint("employee_compensation", "compensation"),
+ "employee_employment_status": _employee_table_endpoint("employee_employment_status", "employmentStatus"),
"time_off_requests": BambooHREndpointConfig(
name="time_off_requests",
- path="time_off/requests",
+ path="v1/time_off/requests",
primary_keys=["id"],
requires_date_window=True,
),
"time_off_types": BambooHREndpointConfig(
name="time_off_types",
- path="meta/time_off/types",
+ path="v1/meta/time_off/types",
data_key="timeOffTypes",
primary_keys=["id"],
),
+ "time_off_policies": BambooHREndpointConfig(
+ name="time_off_policies",
+ path="v1/meta/time_off/policies",
+ primary_keys=["id"],
+ ),
+ "employee_time_off_policies": BambooHREndpointConfig(
+ name="employee_time_off_policies",
+ # v1.1 of this endpoint also returns manual and unlimited policies, which v1 leaves out.
+ path="v1_1/employees/{employeeId}/time_off/policies",
+ primary_keys=[EMPLOYEE_TABLE_EMPLOYEE_ID, "timeOffPolicyId"],
+ fanout=_EMPLOYEE_FANOUT,
+ ),
+ "employee_time_off_balances": BambooHREndpointConfig(
+ name="employee_time_off_balances",
+ path="v1/employees/{employeeId}/time_off/calculator",
+ primary_keys=[EMPLOYEE_TABLE_EMPLOYEE_ID, "timeOffType"],
+ fanout=_EMPLOYEE_FANOUT,
+ ),
+ "timesheet_entries": BambooHREndpointConfig(
+ name="timesheet_entries",
+ path="v1/time_tracking/timesheet_entries",
+ primary_keys=["id"],
+ # BambooHR rejects a window reaching further back than a year, so a year of entries is all
+ # this endpoint can ever return. A month per request keeps each response body bounded.
+ chunked_date_window=ChunkedDateWindow(history_days=365, chunk_days=31),
+ ),
"meta_fields": BambooHREndpointConfig(
name="meta_fields",
- path="meta/fields",
+ path="v1/meta/fields",
primary_keys=["id"],
),
"meta_lists": BambooHREndpointConfig(
name="meta_lists",
- path="meta/lists",
+ path="v1/meta/lists",
primary_keys=["fieldId"],
),
"meta_users": BambooHREndpointConfig(
name="meta_users",
- path="meta/users",
+ path="v1/meta/users",
data_shape="dict",
primary_keys=["id"],
),
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bamboohr/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bamboohr/source.py
index 88fb0597e53d..f647da596f73 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bamboohr/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bamboohr/source.py
@@ -100,7 +100,14 @@ Make sure your API key has access to the data you want to sync (employee, time o
force_refresh: bool = False,
api_version: str | None = None,
) -> list[SourceSchema]:
- return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+ return build_endpoint_schemas(
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ names,
+ # Every BambooHR stream that syncs incrementally is an employee-table history table
+ # whose rows update in place, so appending would stack a copy of each row every sync.
+ merge_only=[name for name, fields in INCREMENTAL_FIELDS.items() if fields],
+ )
def validate_credentials(
self,
@@ -133,4 +140,6 @@ Make sure your API key has access to the data you want to sync (employee, time o
team_id=inputs.team_id,
job_id=inputs.job_id,
resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bamboohr/tests/test_bamboohr.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bamboohr/tests/test_bamboohr.py
index b7a1a079ee79..06a10b47f719 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bamboohr/tests/test_bamboohr.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bamboohr/tests/test_bamboohr.py
@@ -1,5 +1,6 @@
import json
-from typing import Any
+from datetime import UTC, date, datetime, timedelta
+from typing import Any, cast
import pytest
from unittest import mock
@@ -9,6 +10,7 @@ from requests import Response
from products.warehouse_sources.backend.temporal.data_imports.sources.bamboohr.bamboohr import (
BAMBOOHR_API_HOST,
+ EMPLOYEE_TABLE_HISTORY_START,
INVALID_SUBDOMAIN_MESSAGE,
BambooHRBasicAuth,
BambooHRResumeConfig,
@@ -17,11 +19,15 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.bamboohr.b
bamboohr_source,
validate_credentials,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.bamboohr.settings import BAMBOOHR_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.bamboohr.settings import (
+ BAMBOOHR_ENDPOINTS,
+ EMPLOYEE_TABLE_EMPLOYEE_ID,
+)
MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.bamboohr.bamboohr"
# 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"
+FANOUT_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout"
def _response(payload: Any, status_code: int = 200) -> Response:
@@ -49,7 +55,10 @@ def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str,
def _prepare(request: Any) -> mock.MagicMock:
request_snapshots.append({"url": request.url, "params": dict(request.params or {}), "auth": request.auth})
- return mock.MagicMock()
+ prepared = mock.MagicMock()
+ # The client re-checks the host of the prepared URL before sending, so it must be real.
+ prepared.url = request.url
+ return prepared
session.prepare_request.side_effect = _prepare
session.send.side_effect = responses
@@ -66,11 +75,14 @@ def _run(
MockSession: mock.MagicMock,
manager: mock.MagicMock | None = None,
subdomain: str = "acme",
+ rows_from_pages: bool = True,
) -> tuple[list[dict[str, Any]], list[dict[str, Any]], mock.MagicMock]:
session = MockSession.return_value
requests_made = _wire(session, responses)
manager = manager if manager is not None else _make_manager()
- rows = _rows(bamboohr_source(subdomain, "key", endpoint, team_id=1, job_id="j", resumable_source_manager=manager))
+ response = bamboohr_source(subdomain, "key", endpoint, team_id=1, job_id="j", resumable_source_manager=manager)
+ # Fan-out resources yield rows; every other resource yields pages of rows.
+ rows = _rows(response) if rows_from_pages else list(cast(Any, response.items()))
return rows, requests_made, manager
@@ -258,7 +270,7 @@ class TestValidateSubdomain:
]
)
def test_valid_subdomains_build_urls(self, _name: str, subdomain: str) -> None:
- assert _base_url(subdomain) == f"{BAMBOOHR_API_HOST}/{subdomain}/v1"
+ assert _base_url(subdomain) == f"{BAMBOOHR_API_HOST}/{subdomain}"
@parameterized.expand(
[
@@ -316,6 +328,219 @@ class TestValidateCredentials:
session.get.assert_not_called()
+class TestEmployeeTableStreams:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_flattens_the_employee_map_onto_rows(self, MockSession) -> None:
+ payload = {
+ "table": "jobInfo",
+ "employees": {
+ "2": {
+ "lastChanged": "2024-03-01T00:00:00+00:00",
+ # The row carries a stale employeeId; the map key is what the API grouped by.
+ "rows": [{"id": "20", "employeeId": "999", "jobTitle": "Engineer"}],
+ },
+ "1": {
+ "lastChanged": "2024-01-01T00:00:00+00:00",
+ "rows": [{"id": "10", "jobTitle": "Designer"}, {"id": "11", "jobTitle": "Lead"}],
+ },
+ },
+ }
+
+ rows, requests_made, _manager = _run("employee_job_info", [_response(payload)], MockSession)
+
+ assert requests_made[0]["url"] == (
+ "https://api.bamboohr.com/api/gateway.php/acme/v1/employees/changed/tables/jobInfo"
+ )
+ # Employees come back in map order, so the rows must be re-sorted onto the cursor before
+ # the pipeline checkpoints a watermark against them.
+ assert rows == [
+ {"id": "10", "jobTitle": "Designer", "employeeId": "1", "lastChanged": "2024-01-01T00:00:00+00:00"},
+ {"id": "11", "jobTitle": "Lead", "employeeId": "1", "lastChanged": "2024-01-01T00:00:00+00:00"},
+ {"id": "20", "employeeId": "2", "jobTitle": "Engineer", "lastChanged": "2024-03-01T00:00:00+00:00"},
+ ]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_rows_without_a_last_changed_sort_first(self, MockSession) -> None:
+ payload = {
+ "employees": {
+ "1": {"lastChanged": "2024-01-01T00:00:00+00:00", "rows": [{"id": "10"}]},
+ "2": {"rows": [{"id": "20"}]},
+ }
+ }
+
+ rows, _requests, _manager = _run("employee_compensation", [_response(payload)], MockSession)
+
+ assert [row["id"] for row in rows] == ["20", "10"]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_empty_response_yields_no_rows(self, MockSession) -> None:
+ rows, _requests, _manager = _run(
+ "employee_employment_status", [_response({"table": "employmentStatus", "employees": {}})], MockSession
+ )
+ assert rows == []
+
+ @parameterized.expand(
+ [
+ ("missing_employees_key", {"table": "jobInfo"}),
+ ("employees_is_a_list", {"employees": [{"id": "1"}]}),
+ ]
+ )
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_unexpected_shape_fails_loudly(self, _name: str, payload: Any, MockSession) -> None:
+ with pytest.raises(ValueError, match="'employees' object"):
+ _run("employee_job_info", [_response(payload)], MockSession)
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_full_refresh_asks_for_the_whole_history(self, MockSession) -> None:
+ _rows_, requests_made, _manager = _run("employee_job_info", [_response({"employees": {}})], MockSession)
+ assert requests_made[0]["params"] == {"since": EMPLOYEE_TABLE_HISTORY_START.isoformat()}
+
+ @parameterized.expand(
+ [
+ ("watermark_as_string", "2024-05-06T07:08:09+00:00", "2024-05-06T07:08:09+00:00"),
+ ("watermark_as_datetime", datetime(2024, 5, 6, 7, 8, 9, tzinfo=UTC), "2024-05-06T07:08:09+00:00"),
+ ("no_watermark_yet", None, EMPLOYEE_TABLE_HISTORY_START.isoformat()),
+ ]
+ )
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_incremental_sync_sends_the_watermark(self, _name: str, watermark: Any, expected: str, MockSession) -> None:
+ session = MockSession.return_value
+ requests_made = _wire(session, [_response({"employees": {}})])
+
+ response = bamboohr_source(
+ "acme",
+ "key",
+ "employee_job_info",
+ team_id=1,
+ job_id="j",
+ resumable_source_manager=_make_manager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=watermark,
+ )
+ _rows(response)
+
+ assert requests_made[0]["params"] == {"since": expected}
+
+
+class TestTimesheetEntries:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_walks_the_year_in_contiguous_windows(self, MockSession) -> None:
+ window = BAMBOOHR_ENDPOINTS["timesheet_entries"].chunked_date_window
+ assert window is not None
+ expected_requests = -(-(window.history_days + 1) // window.chunk_days)
+
+ _rows_, requests_made, _manager = _run(
+ "timesheet_entries", [_response([]) for _ in range(expected_requests)], MockSession
+ )
+
+ assert len(requests_made) == expected_requests
+ windows = [
+ (date.fromisoformat(r["params"]["start"]), date.fromisoformat(r["params"]["end"])) for r in requests_made
+ ]
+ today = datetime.now(UTC).date()
+ # The whole supported range is covered exactly once: no gap and no overlap between slices,
+ # and nothing reaching past the API's 365-day limit.
+ assert windows[0][0] == today - timedelta(days=window.history_days)
+ assert windows[-1][1] == today
+ for (_start, end), (next_start, _next_end) in zip(windows, windows[1:]):
+ assert next_start == end + timedelta(days=1)
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_entries_from_every_window_are_yielded(self, MockSession) -> None:
+ window = BAMBOOHR_ENDPOINTS["timesheet_entries"].chunked_date_window
+ assert window is not None
+ request_count = -(-(window.history_days + 1) // window.chunk_days)
+ responses = [_response([]) for _ in range(request_count)]
+ responses[0] = _response([{"id": 1}])
+ responses[-1] = _response([{"id": 2}])
+
+ rows, _requests, _manager = _run("timesheet_entries", responses, MockSession)
+
+ assert rows == [{"id": 1}, {"id": 2}]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_non_list_body_fails_loudly(self, MockSession) -> None:
+ with pytest.raises(ValueError, match="list response body"):
+ _run("timesheet_entries", [_response({"error": "nope"})], MockSession)
+
+
+class _FakeDltResource:
+ """Stand-in for the DltResource the fan-out helper returns.
+
+ ``process_parent_data_item`` injects parent fields as ``_<parent_resource>_<field>``, which is
+ what the rename mapper under test reads.
+ """
+
+ def __init__(self, name: str, rows: list[dict[str, Any]]) -> None:
+ self.name = name
+ self._rows = rows
+
+ def add_map(self, mapper: Any) -> "_FakeDltResource":
+ self._rows = [mapper(dict(row)) for row in self._rows]
+ return self
+
+ def __iter__(self) -> Any:
+ return iter(self._rows)
+
+
+class TestEmployeeFanout:
+ @parameterized.expand(
+ [
+ (
+ "time_off_policies",
+ "employee_time_off_policies",
+ {"timeOffPolicyId": "5", "timeOffTypeId": 1, "_employees_id": "7"},
+ {"timeOffPolicyId": "5", "timeOffTypeId": 1, "employeeId": "7"},
+ ),
+ (
+ "time_off_balances",
+ "employee_time_off_balances",
+ {"timeOffType": "1", "balance": "24.50", "_employees_id": "7"},
+ {"timeOffType": "1", "balance": "24.50", "employeeId": "7"},
+ ),
+ ]
+ )
+ @mock.patch(f"{FANOUT_MODULE}.rest_api_resources")
+ def test_child_rows_carry_the_parent_employee_id(
+ self, _name: str, endpoint: str, child_row: dict[str, Any], expected: dict[str, Any], mock_resources
+ ) -> None:
+ mock_resources.return_value = [
+ _FakeDltResource("employees", [{"id": "7"}]),
+ _FakeDltResource(endpoint, [child_row]),
+ ]
+
+ response = bamboohr_source(
+ "acme", "key", endpoint, team_id=1, job_id="j", resumable_source_manager=_make_manager()
+ )
+
+ assert list(cast(Any, response.items())) == [expected]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_child_requests_resolve_the_versioned_employee_path(self, MockSession) -> None:
+ directory = _response({"employees": [{"id": "7"}, {"id": "8"}]})
+ policies = [_response([{"timeOffPolicyId": "5"}]), _response([])]
+
+ _rows_, requests_made, _manager = _run(
+ "employee_time_off_policies", [directory, *policies], MockSession, rows_from_pages=False
+ )
+
+ assert [r["url"] for r in requests_made] == [
+ "https://api.bamboohr.com/api/gateway.php/acme/v1/employees/directory",
+ "https://api.bamboohr.com/api/gateway.php/acme/v1_1/employees/7/time_off/policies",
+ "https://api.bamboohr.com/api/gateway.php/acme/v1_1/employees/8/time_off/policies",
+ ]
+
+
+class TestEndpointCatalog:
+ @parameterized.expand(
+ [(name,) for name, config in BAMBOOHR_ENDPOINTS.items() if config.fanout or config.employee_table]
+ )
+ def test_employee_scoped_endpoints_key_on_the_employee(self, endpoint: str) -> None:
+ # These ids are only unique within one employee, so a key without the employee collides
+ # across the directory and every later merge multi-matches the duplicates.
+ assert EMPLOYEE_TABLE_EMPLOYEE_ID in BAMBOOHR_ENDPOINTS[endpoint].primary_keys
+
+
class TestBambooHRSource:
@parameterized.expand([(endpoint,) for endpoint in BAMBOOHR_ENDPOINTS])
@mock.patch(CLIENT_SESSION_PATCH)