Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(warehouse-sources): add BambooHR ATS, location, who's out and goal tables (#100955)

Tom Owersd9d142f3c360
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 e60c5fa0274d..1f9b40f7606b 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
@@ -707,7 +707,7 @@ Note: The developer hub serves a Swagger UI whose visible initializer points at
## BambooHR — **thin**
-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`
+Today (22): `applicant_statuses`, `application_details`, `applications`, `ats_locations`, `employee_compensation`, `employee_employment_status`, `employee_goal_comments`, `employee_goals`, `employee_job_info`, `employee_time_off_balances`, `employee_time_off_policies`, `employees`, `job_openings`, `locations`, `meta_fields`, `meta_lists`, `meta_users`, `time_off_policies`, `time_off_requests`, `time_off_types`, `timesheet_entries`, `whos_out`
Diffed against: <https://documentation.bamboohr.com/sitemap.xml>
@@ -715,10 +715,10 @@ Diffed against: <https://documentation.bamboohr.com/sitemap.xml>
- [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)
-- [ ] `GET goals + goal comments` — performance goals and progress updates per employee (medium)
+- [x] `GET applications, application details, job summaries, statuses (ATS)` — recruiting funnel - candidates, applications and stage; an entire product area with zero coverage (high)
+- [x] `GET company locations / list locations` — lookup resolving the location ID on employees (high)
+- [x] `GET who's out` — resolved out-of-office calendar, commonly wanted alongside time_off_requests (medium)
+- [x] `GET goals + goal comments` — performance goals and progress updates per employee (medium)
- [ ] `GET employee trainings + training types + training categories` — completion facts plus the lookup tables that name them (medium)
- [ ] `GET company benefits, employee benefits, benefit coverages, deduction types` — benefits enrollment and its lookup tables - a major HRIS reporting area (medium)
- [ ] `GET list datasets + get data from dataset (Workforce Analytics)` — the vendor's own analytics datasets, discoverable at sync time (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 1e8822dc09dc..b7092b655a10 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
@@ -3,13 +3,15 @@ import dataclasses
from collections.abc import Iterable, Iterator
from datetime import UTC, date, datetime, timedelta
from typing import Any, Optional, cast
+from urllib.parse import parse_qs, quote, urlsplit
-from requests import Response
+from requests import Request, Response
from products.warehouse_sources.backend.temporal.data_imports.sources.bamboohr.settings import (
BAMBOOHR_ENDPOINTS,
EMPLOYEE_TABLE_EMPLOYEE_ID,
EMPLOYEE_TABLE_LAST_CHANGED,
+ GOAL_ID,
BambooHREndpointConfig,
ChunkedDateWindow,
)
@@ -25,6 +27,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
BaseNextUrlPaginator,
+ BasePaginator,
+ PageNumberPaginator,
SinglePagePaginator,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import RESTClient
@@ -53,6 +57,10 @@ 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)
+# BambooHR's page-numbered endpoints count from zero.
+FIRST_PAGE_NUMBER = 0
+# Endpoint whose rows the goal-comment iterator walks to reach each goal.
+GOAL_COMMENTS_PARENT = "employee_goals"
# 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
@@ -130,11 +138,86 @@ class BambooHRPaginator(BaseNextUrlPaginator):
return "BambooHRPaginator(_links.next|links.next)"
+def _page_from_url(url: Any) -> int | None:
+ if not isinstance(url, str):
+ return None
+ values = parse_qs(urlsplit(url).query).get("page")
+ if not values:
+ return None
+ try:
+ return int(values[0])
+ except ValueError:
+ return None
+
+
+class BambooHRApplicationsPaginator(BasePaginator):
+ """Walks the ATS applications envelope (``paginationComplete`` plus ``nextPageUrl``).
+
+ ``nextPageUrl`` is read only for the page number it carries, never followed: BambooHR builds
+ it against the company's own domain while we call the same API through the gateway host the
+ API key was issued for, so following it verbatim would leave that host.
+ """
+
+ def __init__(self, page_param: str = "page") -> None:
+ super().__init__()
+ self.page_param = page_param
+ # None until the first response tells us which page the API served by default.
+ self.page: int | None = None
+
+ def _apply(self, request: Request) -> None:
+ if self.page is None:
+ return
+ if request.params is None:
+ request.params = {}
+ request.params[self.page_param] = self.page
+
+ def init_request(self, request: Request) -> None:
+ self._apply(request)
+
+ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
+ try:
+ payload = response.json()
+ except Exception:
+ payload = None
+ if not isinstance(payload, dict) or payload.get("paginationComplete") or not data:
+ self._has_next_page = False
+ return
+ next_page = _page_from_url(payload.get("nextPageUrl"))
+ if next_page is None:
+ if not payload.get("nextPageUrl"):
+ self._has_next_page = False
+ return
+ # A next link we cannot read a page number out of still means more rows, so step
+ # forward rather than truncating the table. The step is always +1 on the page we
+ # last asked for, so the walk cannot revisit a page it already fetched.
+ next_page = (self.page or 0) + 1
+ self.page = next_page
+ self._has_next_page = True
+
+ def update_request(self, request: Request) -> None:
+ self._apply(request)
+
+ def __str__(self) -> str:
+ return "BambooHRApplicationsPaginator(paginationComplete|nextPageUrl)"
+
+
+def _paginator_for(config: BambooHREndpointConfig) -> BasePaginator:
+ if config.pagination == "single":
+ return SinglePagePaginator()
+ if config.pagination == "page_number":
+ return PageNumberPaginator(base_page=FIRST_PAGE_NUMBER, stop_after_empty_page=True)
+ if config.pagination == "ats_applications":
+ return BambooHRApplicationsPaginator()
+ return BambooHRPaginator()
+
+
def _selector_for(config: BambooHREndpointConfig) -> tuple[str | None, bool]:
"""Map an endpoint's response layout to a (data_selector, data_selector_required) pair.
- "dict" shape (e.g. ``meta/users`` — ``{"<id>": {...}}``): the ``*`` wildcard flattens the
object to its values; not required so an empty account (empty object) is a legit 0-row page.
+ - "object" shape (a by-id detail endpoint): no selector, and not required, so the single
+ object body is wrapped as one row instead of failing the list check.
- Enveloped list (``data_key``): select the key and fail loudly when it's absent (an API
change) rather than silently syncing zero rows.
- Bare list body: no selector; require a list so an unexpected 200 envelope fails loudly
@@ -142,6 +225,9 @@ def _selector_for(config: BambooHREndpointConfig) -> tuple[str | None, bool]:
"""
if config.data_shape == "dict":
return "*", False
+ if config.data_shape == "object":
+ # A by-id detail body is one record; the client wraps it into a single row.
+ return None, False
if config.data_key is not None:
return config.data_key, True
return None, True
@@ -150,7 +236,8 @@ def _selector_for(config: BambooHREndpointConfig) -> tuple[str | None, bool]:
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}
+ # Parent and child are paginated separately, so each side needs its own paginator instance.
+ extra: Endpoint = {"data_selector_required": data_selector_required, "paginator": _paginator_for(config)}
if data_selector is not None:
extra["data_selector"] = data_selector
return extra
@@ -161,7 +248,8 @@ def _rest_client(base_url: str, api_key: str) -> 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.
+ # Default for the streams this client drives directly; callers that need an endpoint's
+ # own paginator pass one to `paginate`.
paginator=SinglePagePaginator(),
# Pins every request to the gateway host the API key was issued for.
allowed_hosts=[],
@@ -232,6 +320,75 @@ def _window_pages(
yield page
+def _format_path(path: str, **values: Any) -> str:
+ """Bind path placeholders to ids taken from an API response.
+
+ The ids are percent-encoded because they land in the request path: an id carrying a ``/`` or
+ a ``?`` would otherwise add path segments or query params to an authenticated request.
+ """
+ for key, value in values.items():
+ path = path.replace("{" + key + "}", quote(str(value), safe=""))
+ return path
+
+
+def _rows_for(
+ client: RESTClient, config: BambooHREndpointConfig, path: str | None = None, params: dict[str, Any] | None = None
+) -> Iterator[dict[str, Any]]:
+ data_selector, data_selector_required = _selector_for(config)
+ for page in client.paginate(
+ path=path or config.path,
+ params=config.params if params is None else params,
+ paginator=_paginator_for(config),
+ data_selector=data_selector,
+ data_selector_required=data_selector_required,
+ ):
+ yield from page
+
+
+def _param_variant_pages(client: RESTClient, config: BambooHREndpointConfig) -> Iterator[list[dict[str, Any]]]:
+ """Walk an endpoint once per param variant, because no single request reaches every row."""
+ for variant in config.param_variants:
+ for page in client.paginate(
+ path=config.path,
+ params={**config.params, **variant},
+ paginator=_paginator_for(config),
+ data_selector=_selector_for(config)[0],
+ data_selector_required=_selector_for(config)[1],
+ ):
+ if page:
+ yield page
+
+
+def _goal_comment_pages(client: RESTClient, config: BambooHREndpointConfig) -> Iterator[list[dict[str, Any]]]:
+ """Walk the directory, then each employee's goals, then each goal's comments.
+
+ Two fan-out levels deep, which the single-hop dependent-resource helper cannot express. A
+ comment row names neither the goal nor the employee it belongs to, so both are stamped on.
+ """
+ goals_config = BAMBOOHR_ENDPOINTS[GOAL_COMMENTS_PARENT]
+ goals_fanout = goals_config.fanout
+ if goals_fanout is None:
+ raise ValueError(f"'{GOAL_COMMENTS_PARENT}' must fan out over a parent endpoint")
+ employees_config = BAMBOOHR_ENDPOINTS[goals_fanout.parent_name]
+
+ for employee in _rows_for(client, employees_config):
+ employee_id = employee.get(goals_fanout.resolve_field)
+ if employee_id is None:
+ continue
+ goals_path = _format_path(goals_config.path, employeeId=employee_id)
+ for goal in _rows_for(client, goals_config, path=goals_path, params=dict(goals_fanout.child_params)):
+ goal_id = goal.get("id")
+ if goal_id is None:
+ continue
+ path = _format_path(config.path, employeeId=employee_id, goalId=goal_id)
+ rows = [
+ {**row, EMPLOYEE_TABLE_EMPLOYEE_ID: str(employee_id), GOAL_ID: str(goal_id)}
+ for row in _rows_for(client, config, path=path)
+ ]
+ if rows:
+ yield rows
+
+
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
@@ -251,6 +408,22 @@ def bamboohr_source(
config = BAMBOOHR_ENDPOINTS[endpoint]
base_url = _base_url(subdomain)
+ if config.param_variants:
+ client = _rest_client(base_url, api_key)
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: _param_variant_pages(client, config),
+ primary_keys=config.primary_keys,
+ )
+
+ if config.custom_iterator == "goal_comments":
+ client = _rest_client(base_url, api_key)
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: _goal_comment_pages(client, config),
+ primary_keys=config.primary_keys,
+ )
+
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)
@@ -275,7 +448,7 @@ def bamboohr_source(
# 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(),
+ "paginator": _paginator_for(config),
}
if config.fanout is not None:
@@ -303,10 +476,10 @@ def bamboohr_source(
primary_keys=config.primary_keys,
)
- params: dict[str, Any] = {}
+ params: dict[str, Any] = dict(config.params)
if config.requires_date_window:
- end = (datetime.now(UTC) + timedelta(days=TIME_OFF_FUTURE_DAYS)).strftime("%Y-%m-%d")
- params = {"start": TIME_OFF_WINDOW_START, "end": end}
+ params["start"] = TIME_OFF_WINDOW_START
+ params["end"] = (datetime.now(UTC) + timedelta(days=TIME_OFF_FUTURE_DAYS)).strftime("%Y-%m-%d")
data_selector, data_selector_required = _selector_for(config)
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 b3dbfe1a7582..0bc850e472e1 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
@@ -162,6 +162,128 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"options": "The available option values for the list field.",
},
},
+ "whos_out": {
+ "description": "An employee time-off entry or company holiday on the Who's Out calendar for a date range.",
+ "docs_url": "https://documentation.bamboohr.com/reference/list-whos-out",
+ "columns": {
+ "id": "Identifier of the time-off request or the holiday. Only unique within its type.",
+ "type": "Whether the entry is a time-off request ('timeOff') or a company holiday ('holiday').",
+ "employeeId": "ID of the employee who is out. Only present on time-off entries.",
+ "name": "The employee's name on time-off entries, or the holiday's name on holiday entries.",
+ "start": "First day the entry covers.",
+ "end": "Last day the entry covers.",
+ },
+ },
+ "locations": {
+ "description": "A work location configured for the company, used to place employees and job openings.",
+ "docs_url": "https://documentation.bamboohr.com/reference/get-locations",
+ "columns": {
+ "id": "Unique identifier for the location.",
+ "label": "Display name of the location.",
+ "archived": "Whether the location is archived.",
+ "manageable": "Whether the location can be managed by the caller.",
+ "address": "Street address, city, state, postal code, country and timezone of the location.",
+ "createdAt": "Time at which the location was created.",
+ "archivedAt": "Time at which the location was archived, if it is.",
+ },
+ },
+ "ats_locations": {
+ "description": "A company location that can be attached to a job opening in applicant tracking.",
+ "docs_url": "https://documentation.bamboohr.com/reference/get-company-locations",
+ "columns": {
+ "id": "Unique identifier for the location.",
+ "name": "Name of the location.",
+ "description": "Description of the location.",
+ "city": "City the location is in.",
+ "state": "State or province the location is in.",
+ "country": "Country the location is in.",
+ "zipcode": "Postal code of the location.",
+ },
+ },
+ "job_openings": {
+ "description": "A job opening in applicant tracking, with its applicant counts.",
+ "docs_url": "https://documentation.bamboohr.com/reference/get-job-summaries",
+ "columns": {
+ "id": "Unique identifier for the job opening.",
+ "title": "Job title of the opening.",
+ "postedDate": "Time at which the opening was posted.",
+ "location": "Location the opening is based at.",
+ "department": "Department the opening belongs to.",
+ "status": "Current status of the opening (for example Open, Filled, On Hold).",
+ "hiringLead": "The employee leading hiring for the opening.",
+ "newApplicantsCount": "Number of applicants still in the 'New' status.",
+ "activeApplicantsCount": "Number of applicants in an active status.",
+ "totalApplicantsCount": "Total number of applicants for the opening.",
+ "postingUrl": "Public URL of the job posting, if it is posted.",
+ },
+ },
+ "applications": {
+ "description": "An application submitted to a job opening, with the applicant and current stage.",
+ "docs_url": "https://documentation.bamboohr.com/reference/get-applications",
+ "columns": {
+ "id": "Unique identifier for the application.",
+ "appliedDate": "Time at which the application was submitted.",
+ "status": "Current status of the application in the hiring funnel.",
+ "rating": "Rating given to the candidate, from 1 to 5, or null when not rated.",
+ "applicant": "Name, email, avatar and source of the applicant.",
+ "job": "The job opening the application was submitted to.",
+ },
+ },
+ "application_details": {
+ "description": "The full detail of a single application, including when its status last changed.",
+ "docs_url": "https://documentation.bamboohr.com/reference/get-application-details",
+ "columns": {
+ "id": "Unique identifier for the application.",
+ "appliedDate": "Time at which the application was submitted.",
+ "status": "Current status, when it last changed, and the user who changed it.",
+ "rating": "Rating given to the candidate, from 1 to 5, or null when not rated.",
+ "applicant": "Contact details, education, experience and attached files of the applicant.",
+ "job": "The job opening the application was submitted to.",
+ },
+ },
+ "applicant_statuses": {
+ "description": "A status an application can be placed in, resolving the status IDs on applications.",
+ "docs_url": "https://documentation.bamboohr.com/reference/get-statuses",
+ "columns": {
+ "id": "Unique identifier for the status.",
+ "code": "Internal status code, or null for a status the company added.",
+ "label": "Display name of the status.",
+ },
+ },
+ "employee_goals": {
+ "description": "A performance goal assigned to an employee, with its progress and milestones.",
+ "docs_url": "https://documentation.bamboohr.com/reference/list-goals",
+ "columns": {
+ "employeeId": "ID of the employee the goal is assigned to.",
+ "id": "Identifier of the goal, unique within the employee.",
+ "title": "Title of the goal.",
+ "description": "Description of the goal.",
+ "percentComplete": "How complete the goal is, from 0 to 100.",
+ "status": "Status of the goal: in_progress, completed or closed.",
+ "dueDate": "Date the goal is due.",
+ "completionDate": "Time at which the goal was completed.",
+ "lastChangedDateTime": "Time at which the goal was last modified.",
+ "alignsWithOptionId": "ID of the goal this goal is aligned with, if any.",
+ "sharedWithEmployeeIds": "IDs of the employees who can see the goal.",
+ "milestones": "The goal's milestones and their progress, when it uses milestones.",
+ },
+ },
+ "employee_goal_comments": {
+ "description": (
+ "A comment left on an employee's performance goal. BambooHR answers with at most 50 "
+ "comments per goal and offers no way to page past them, so a goal discussed more than "
+ "that holds only the 50 the API returns."
+ ),
+ "docs_url": "https://documentation.bamboohr.com/reference/list-goal-comments",
+ "columns": {
+ "employeeId": "ID of the employee the goal belongs to.",
+ "goalId": "ID of the goal the comment was left on.",
+ "id": "Identifier of the comment, unique within the goal.",
+ "authorUserId": "User ID of the person who wrote the comment.",
+ "createdAt": "Time at which the comment was written.",
+ "text": "Text of the comment.",
+ },
+ },
"meta_users": {
"description": "A user account with access to the company's BambooHR.",
"docs_url": "https://documentation.bamboohr.com/reference/get-a-list-of-users",
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 8b31b50f15eb..a447d196f879 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,5 +1,5 @@
from dataclasses import dataclass, field
-from typing import Literal
+from typing import Any, Literal
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
DependentEndpointConfig,
@@ -8,15 +8,30 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.sch
from products.warehouse_sources.backend.types import IncrementalField
# How records are laid out in a BambooHR JSON response.
-# "list" — the records are a JSON array (either the whole body or under ``data_key``)
-# "dict" — the records are a JSON object keyed by id (e.g. ``meta/users``); we take ``.values()``
-DataShape = Literal["list", "dict"]
+# "list" — the records are a JSON array (either the whole body or under ``data_key``)
+# "dict" — the records are a JSON object keyed by id (e.g. ``meta/users``); we take ``.values()``
+# "object" — the body is one record (a by-id detail endpoint), yielded as a single row
+DataShape = Literal["list", "dict", "object"]
+
+# How an endpoint's pages are walked.
+# "links" — follow the absolute URL under ``_links.next``; classic endpoints carry no
+# links at all and so return a single page
+# "single" — the body is the whole response; never ask for a second page
+# "page_number" — ``page``/``pageSize`` query params, walked until a page comes back empty
+# "ats_applications" — the ATS applications envelope (``paginationComplete`` + ``nextPageUrl``)
+PaginationStyle = Literal["links", "single", "page_number", "ats_applications"]
# 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"
+# Goal comments are addressed by employee *and* goal, and the comment rows carry neither.
+GOAL_ID = "goalId"
+
+# BambooHR's org locations endpoint is the only one that takes a page size.
+LOCATIONS_PAGE_SIZE = 500
+
@dataclass(frozen=True)
class ChunkedDateWindow:
@@ -47,8 +62,16 @@ class BambooHREndpointConfig:
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.
+ # Fan-out over a parent listing, for endpoints addressed by a single parent record.
fanout: DependentEndpointConfig | None = None
+ # Set when the endpoint is two fan-out levels deep, which the single-hop helper cannot express.
+ custom_iterator: Literal["goal_comments"] | None = None
+ # Static query params every request for this endpoint carries.
+ params: dict[str, Any] = field(default_factory=dict)
+ # Set when one request set cannot reach the whole collection: the endpoint is walked once per
+ # variant and the results concatenated. Each variant must select a disjoint set of rows.
+ param_variants: list[dict[str, Any]] = field(default_factory=list)
+ pagination: PaginationStyle = "links"
# 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)
@@ -66,6 +89,36 @@ _EMPLOYEE_FANOUT = DependentEndpointConfig(
parent_field_renames={"id": EMPLOYEE_TABLE_EMPLOYEE_ID},
)
+_EMPLOYEE_GOALS_FANOUT = DependentEndpointConfig(
+ parent_name="employees",
+ resolve_param="employeeId",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": EMPLOYEE_TABLE_EMPLOYEE_ID},
+ # Closed goals are left out unless the filter asks for every status.
+ child_params={"filter": "status-all"},
+)
+
+# The defaults narrow the funnel to open positions and active applications, which would leave
+# hired and rejected applications — the outcomes the funnel is measured by — out of the table.
+_ATS_APPLICATION_PARAMS: dict[str, Any] = {
+ "applicationStatus": "ALL",
+ "jobStatusGroups": "ALL",
+ "sortBy": "created_date",
+ "sortOrder": "ASC",
+}
+
+_APPLICATION_FANOUT = DependentEndpointConfig(
+ parent_name="applications",
+ resolve_param="applicationId",
+ resolve_field="id",
+ # The detail body carries its own id, so nothing has to be copied off the parent row.
+ include_from_parent=[],
+ parent_params=_ATS_APPLICATION_PARAMS,
+ # An application deleted between the listing and its detail fetch is not a sync failure.
+ child_response_actions=[{"status_code": 404, "action": "ignore", "message": None}],
+)
+
def _employee_table_endpoint(name: str, table: str) -> BambooHREndpointConfig:
return BambooHREndpointConfig(
@@ -143,6 +196,73 @@ BAMBOOHR_ENDPOINTS: dict[str, BambooHREndpointConfig] = {
data_shape="dict",
primary_keys=["id"],
),
+ "whos_out": BambooHREndpointConfig(
+ name="whos_out",
+ path="v1/time_off/whos_out",
+ # Holiday entries and time-off entries number their ids separately, so the two can collide.
+ primary_keys=["type", "id"],
+ requires_date_window=True,
+ # Without this the response is narrowed to the API user's saved Who's Out calendar filter.
+ params={"filter": "off"},
+ ),
+ "locations": BambooHREndpointConfig(
+ name="locations",
+ path="v1/hris/org/locations",
+ data_key="data",
+ primary_keys=["id"],
+ pagination="page_number",
+ params={"pageSize": LOCATIONS_PAGE_SIZE},
+ # The endpoint answers with active locations only, so archived ones are asked for
+ # separately. Employees and job openings still point at locations after they are archived.
+ param_variants=[{"filter": "archived eq false"}, {"filter": "archived eq true"}],
+ ),
+ "job_openings": BambooHREndpointConfig(
+ name="job_openings",
+ path="v1/applicant_tracking/jobs",
+ primary_keys=["id"],
+ # The default omits deleted positions, which synced applications still point at.
+ params={"statusGroups": "ALL"},
+ ),
+ "applications": BambooHREndpointConfig(
+ name="applications",
+ path="v1/applicant_tracking/applications",
+ data_key="applications",
+ primary_keys=["id"],
+ pagination="ats_applications",
+ params=_ATS_APPLICATION_PARAMS,
+ ),
+ "application_details": BambooHREndpointConfig(
+ name="application_details",
+ path="v1/applicant_tracking/applications/{applicationId}",
+ data_shape="object",
+ pagination="single",
+ primary_keys=["id"],
+ fanout=_APPLICATION_FANOUT,
+ ),
+ "applicant_statuses": BambooHREndpointConfig(
+ name="applicant_statuses",
+ path="v1/applicant_tracking/statuses",
+ primary_keys=["id"],
+ ),
+ "ats_locations": BambooHREndpointConfig(
+ name="ats_locations",
+ path="v1/applicant_tracking/locations",
+ primary_keys=["id"],
+ ),
+ "employee_goals": BambooHREndpointConfig(
+ name="employee_goals",
+ path="v1/performance/employees/{employeeId}/goals",
+ data_key="goals",
+ primary_keys=[EMPLOYEE_TABLE_EMPLOYEE_ID, "id"],
+ fanout=_EMPLOYEE_GOALS_FANOUT,
+ ),
+ "employee_goal_comments": BambooHREndpointConfig(
+ name="employee_goal_comments",
+ path="v1/performance/employees/{employeeId}/goals/{goalId}/comments",
+ data_key="comments",
+ primary_keys=[EMPLOYEE_TABLE_EMPLOYEE_ID, GOAL_ID, "id"],
+ custom_iterator="goal_comments",
+ ),
}
ENDPOINTS = tuple(BAMBOOHR_ENDPOINTS.keys())
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 06a10b47f719..d09ac0f7f6a8 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
@@ -16,12 +16,15 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.bamboohr.b
BambooHRResumeConfig,
_base_url,
_next_url,
+ _page_from_url,
bamboohr_source,
validate_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.bamboohr.settings import (
BAMBOOHR_ENDPOINTS,
EMPLOYEE_TABLE_EMPLOYEE_ID,
+ GOAL_ID,
+ LOCATIONS_PAGE_SIZE,
)
MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.bamboohr.bamboohr"
@@ -498,6 +501,12 @@ class TestEmployeeFanout:
{"timeOffType": "1", "balance": "24.50", "_employees_id": "7"},
{"timeOffType": "1", "balance": "24.50", "employeeId": "7"},
),
+ (
+ "goals",
+ "employee_goals",
+ {"id": "4", "title": "Ship the thing", "_employees_id": "7"},
+ {"id": "4", "title": "Ship the thing", "employeeId": "7"},
+ ),
]
)
@mock.patch(f"{FANOUT_MODULE}.rest_api_resources")
@@ -531,9 +540,224 @@ class TestEmployeeFanout:
]
+class TestStaticEndpointParams:
+ @parameterized.expand(
+ [
+ # Each of these defaults to a narrowed slice of the collection, so the param is what
+ # keeps the synced table complete rather than a silently filtered subset.
+ ("job_openings", [], {"statusGroups": "ALL"}),
+ ("applicant_statuses", [], {}),
+ ("ats_locations", [], {}),
+ ]
+ )
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_list_endpoint_request(self, endpoint: str, payload: Any, expected: dict[str, Any], MockSession) -> None:
+ _rows_, requests_made, _manager = _run(endpoint, [_response(payload)], MockSession)
+ assert requests_made[0]["params"] == expected
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_whos_out_asks_for_the_whole_calendar(self, MockSession) -> None:
+ _rows_, requests_made, _manager = _run("whos_out", [_response([{"id": 1, "type": "holiday"}])], MockSession)
+
+ assert requests_made[0]["url"] == "https://api.bamboohr.com/api/gateway.php/acme/v1/time_off/whos_out"
+ params = requests_made[0]["params"]
+ # Without filter=off the endpoint answers with the API user's saved calendar filter only.
+ assert params["filter"] == "off"
+ assert params["start"] == "2000-01-01"
+ assert len(params["end"]) == 10
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_applications_ask_for_every_status(self, MockSession) -> None:
+ page = {"applications": [{"id": 1}], "paginationComplete": True}
+ _rows_, requests_made, _manager = _run("applications", [_response(page)], MockSession)
+
+ assert (
+ requests_made[0]["url"]
+ == "https://api.bamboohr.com/api/gateway.php/acme/v1/applicant_tracking/applications"
+ )
+ assert requests_made[0]["params"] == {
+ "applicationStatus": "ALL",
+ "jobStatusGroups": "ALL",
+ "sortBy": "created_date",
+ "sortOrder": "ASC",
+ }
+
+
+class TestApplicationsPagination:
+ def _pages(self, MockSession, payloads: list[Any]) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
+ rows, requests_made, _manager = _run("applications", [_response(p) for p in payloads], MockSession)
+ return rows, requests_made
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_page_number_comes_from_the_next_page_url(self, MockSession) -> None:
+ # The next link points at the company domain, not the gateway we authenticated against,
+ # so only its page number may be reused.
+ page1 = {
+ "applications": [{"id": 1}],
+ "paginationComplete": False,
+ "nextPageUrl": "https://acme.bamboohr.com/api/v1/applicant_tracking/applications?page=4",
+ }
+ page2 = {"applications": [{"id": 2}], "paginationComplete": True}
+
+ rows, requests_made = self._pages(MockSession, [page1, page2])
+
+ assert [r["id"] for r in rows] == [1, 2]
+ assert (
+ requests_made[0]["url"]
+ == "https://api.bamboohr.com/api/gateway.php/acme/v1/applicant_tracking/applications"
+ )
+ assert "page" not in requests_made[0]["params"]
+ assert requests_made[1]["params"]["page"] == 4
+
+ @parameterized.expand(
+ [
+ ("pagination_complete", {"applications": [{"id": 1}], "paginationComplete": True}),
+ ("no_next_page_url", {"applications": [{"id": 1}], "paginationComplete": False, "nextPageUrl": None}),
+ ("empty_page", {"applications": [], "paginationComplete": False, "nextPageUrl": "?page=2"}),
+ ]
+ )
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_walk_terminates(self, _name: str, payload: Any, MockSession) -> None:
+ _rows_, requests_made = self._pages(MockSession, [payload])
+ assert len(requests_made) == 1
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_unreadable_next_link_still_advances(self, MockSession) -> None:
+ # A next link we cannot parse a page out of must not silently truncate the table.
+ page1 = {"applications": [{"id": 1}], "paginationComplete": False, "nextPageUrl": "/next"}
+ page2 = {"applications": [{"id": 2}], "paginationComplete": True}
+
+ rows, requests_made = self._pages(MockSession, [page1, page2])
+
+ assert [r["id"] for r in rows] == [1, 2]
+ assert requests_made[1]["params"]["page"] == 1
+
+ @parameterized.expand(
+ [
+ ("absolute", "https://acme.bamboohr.com/api/v1/x?page=3&limit=50", 3),
+ ("relative", "/api/v1/x?page=0", 0),
+ ("no_page_param", "https://acme.bamboohr.com/api/v1/x?limit=50", None),
+ ("non_numeric", "https://acme.bamboohr.com/api/v1/x?page=abc", None),
+ ("not_a_string", None, None),
+ ]
+ )
+ def test_page_from_url(self, _name: str, url: Any, expected: int | None) -> None:
+ assert _page_from_url(url) == expected
+
+
+class TestLocationsPagination:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_walks_every_page_of_active_and_archived_locations(self, MockSession) -> None:
+ pages = [
+ _response({"data": [{"id": "1"}]}),
+ _response({"data": [{"id": "2"}]}),
+ _response({"data": []}),
+ _response({"data": [{"id": "3"}]}),
+ _response({"data": []}),
+ ]
+
+ rows, requests_made, _manager = _run("locations", pages, MockSession)
+
+ # The endpoint answers with active locations only, so an archived location a synced
+ # employee still points at reaches the table through the second walk.
+ assert [r["id"] for r in rows] == ["1", "2", "3"]
+ assert requests_made[0]["url"] == "https://api.bamboohr.com/api/gateway.php/acme/v1/hris/org/locations"
+ assert [r["params"]["filter"] for r in requests_made] == [
+ "archived eq false",
+ "archived eq false",
+ "archived eq false",
+ "archived eq true",
+ "archived eq true",
+ ]
+ # Each walk pages from zero and stops on its first empty page.
+ assert [r["params"]["page"] for r in requests_made] == [0, 1, 2, 0, 1]
+ assert {r["params"]["pageSize"] for r in requests_made} == {LOCATIONS_PAGE_SIZE}
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_missing_data_key_fails_loudly(self, MockSession) -> None:
+ with pytest.raises(ValueError, match="matched nothing"):
+ _run("locations", [_response({"meta": {}})], MockSession)
+
+
+class TestApplicationDetailsFanout:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_detail_body_becomes_one_row_per_application(self, MockSession) -> None:
+ listing = _response({"applications": [{"id": 11}, {"id": 12}], "paginationComplete": True})
+ details = [_response({"id": 11, "rating": 4}), _response({"id": 12, "rating": None})]
+
+ rows, requests_made, _manager = _run("application_details", [listing, *details], MockSession)
+
+ assert rows == [{"id": 11, "rating": 4}, {"id": 12, "rating": None}]
+ assert [r["url"] for r in requests_made] == [
+ "https://api.bamboohr.com/api/gateway.php/acme/v1/applicant_tracking/applications",
+ "https://api.bamboohr.com/api/gateway.php/acme/v1/applicant_tracking/applications/11",
+ "https://api.bamboohr.com/api/gateway.php/acme/v1/applicant_tracking/applications/12",
+ ]
+
+
+class TestGoalStreams:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_goals_request_every_status_per_employee(self, MockSession) -> None:
+ directory = _response({"employees": [{"id": "7"}, {"id": "8"}]})
+ goals = [_response({"goals": [{"id": "4"}]}), _response({"goals": []})]
+
+ _rows_, requests_made, _manager = _run(
+ "employee_goals", [directory, *goals], 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/performance/employees/7/goals",
+ "https://api.bamboohr.com/api/gateway.php/acme/v1/performance/employees/8/goals",
+ ]
+ # Closed goals are dropped from the response unless every status is asked for.
+ assert requests_made[1]["params"]["filter"] == "status-all"
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_comments_walk_every_goal_of_every_employee(self, MockSession) -> None:
+ responses = [
+ _response({"employees": [{"id": "7"}, {"id": "8"}]}),
+ _response({"goals": [{"id": "4"}, {"id": "5"}]}),
+ _response({"comments": [{"id": "100", "text": "nice"}]}),
+ _response({"comments": []}),
+ _response({"goals": []}),
+ ]
+
+ rows, requests_made, _manager = _run("employee_goal_comments", responses, MockSession)
+
+ # A comment row names neither its goal nor its employee, so both have to be stamped on.
+ assert rows == [{"id": "100", "text": "nice", "employeeId": "7", GOAL_ID: "4"}]
+ 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/performance/employees/7/goals",
+ "https://api.bamboohr.com/api/gateway.php/acme/v1/performance/employees/7/goals/4/comments",
+ "https://api.bamboohr.com/api/gateway.php/acme/v1/performance/employees/7/goals/5/comments",
+ "https://api.bamboohr.com/api/gateway.php/acme/v1/performance/employees/8/goals",
+ ]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_ids_from_the_api_cannot_extend_the_request_path(self, MockSession) -> None:
+ responses = [
+ _response({"employees": [{"id": "7/../../meta/users?"}]}),
+ _response({"goals": []}),
+ ]
+
+ _rows_, requests_made, _manager = _run("employee_goal_comments", responses, MockSession)
+
+ assert requests_made[1]["url"] == (
+ "https://api.bamboohr.com/api/gateway.php/acme/v1/performance/employees/7%2F..%2F..%2Fmeta%2Fusers%3F/goals"
+ )
+
+
class TestEndpointCatalog:
@parameterized.expand(
- [(name,) for name, config in BAMBOOHR_ENDPOINTS.items() if config.fanout or config.employee_table]
+ [
+ (name,)
+ for name, config in BAMBOOHR_ENDPOINTS.items()
+ if config.employee_table
+ or config.custom_iterator == "goal_comments"
+ or (config.fanout is not None and config.fanout.parent_name == "employees")
+ ]
)
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