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 deel timesheet, payment, legal entity and time-off tables (#105177)

Tom Owers11c0e86f92fa
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 cd94dedf0177..81cffccf4a07 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
@@ -2373,14 +2373,14 @@ Note: docs.decagon.ai is a fully client-rendered Mintlify site that returns the
## Deel — **thin**
-Today (4): `contracts`, `invoice_adjustments`, `invoices`, `people`
+Today (11): `contracts`, `cost_centers`, `invoice_adjustments`, `invoices`, `legal_entities`, `payment_breakdowns`, `payments`, `people`, `time_off_events`, `time_offs`, `timesheets`
Diffed against: <https://api.letsdeel.com/openapi/rest/definitions>
-- [ ] `/timesheets (and /contracts/{contract_id}/timesheets)` — submitted time entries per contract — the core billable-hours fact table for contractor spend (high)
-- [ ] `/payments (+ /payments/{payment_id}/breakdown)` — actual payment transactions and their per-contract breakdown; today only invoices are synced, not what was paid (high)
-- [ ] `/legal-entities (+ /legal-entities/{id}/cost-centers)` — lookup that resolves the legal entity and cost center IDs carried on contracts and invoices (high)
-- [ ] `/time_offs (+ /time_offs/dailies, /time_offs/time-off-events)` — absence records and transition events per worker — headline HR analytics (high)
+- [x] `/timesheets (and /contracts/{contract_id}/timesheets)` — submitted time entries per contract — the core billable-hours fact table for contractor spend (high)
+- [x] `/payments (+ /payments/{payment_id}/breakdown)` — actual payment transactions and their per-contract breakdown; today only invoices are synced, not what was paid (high)
+- [x] `/legal-entities (+ /legal-entities/{id}/cost-centers)` — lookup that resolves the legal entity and cost center IDs carried on contracts and invoices (high)
+- [x] `/time_offs (+ /time_offs/dailies, /time_offs/time-off-events)` — absence records and transition events per worker — headline HR analytics (high)
- [ ] `/departments, /teams, /groups` — org lookup tables that resolve the department/team IDs on people rows (high)
- [ ] `/contracts/{contract_id}/adjustments` — per-contract bonuses, deductions and expenses; adjustments are only reachable one-by-one today (medium)
- [ ] `/contracts/{contract_id}/milestones` — line items for milestone-based contracts, needed to explain invoice amounts (medium)
@@ -2390,7 +2390,8 @@ Diffed against: <https://api.letsdeel.com/openapi/rest/definitions>
- [ ] `/lookups/countries, /lookups/currencies, /lookups/job-titles, /lookups/seniorities, /lookups/time-off-types` — reference tables that decode the coded fields on contracts, people and time off (medium)
- [ ] `/ats/applications, /ats/candidates, /ats/job-postings` — recruiting funnel objects for orgs using Deel's ATS (low)
-Note: The public spec is served from api.letsdeel.com (linked from developer.deel.com); it has 329 paths / 207 GET operations across ATS, EOR, payroll, HRIS, time tracking and IT modules, so the 4 synced tables cover a small slice.
+Note: The public spec is served from api.letsdeel.com (linked from developer.deel.com); it has hundreds of paths across ATS, EOR, payroll, HRIS, time tracking and IT modules, so the synced tables still cover a small slice.
+Two sub-endpoints of the ticked lines were deliberately not given their own table: `/contracts/{contract_id}/timesheets` returns the same rows as `/timesheets` filtered to one contract, and `/time_offs/dailies` is a date-range query for holidays and work schedules with no row identity, whose absence dailies already arrive nested on `/time_offs` rows.
## Deepgram — gaps
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/deel/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/deel/canonical_descriptions.py
index d1061ba44408..64292cc91264 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/deel/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/deel/canonical_descriptions.py
@@ -66,4 +66,144 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"status": "Current status of the adjustment.",
},
},
+ "timesheets": {
+ "description": "A time entry submitted against a Deel contract, used to bill hourly and pay-as-you-go work.",
+ "docs_url": "https://developer.deel.com/reference/listoftimesheets",
+ "columns": {
+ "id": "Unique identifier for the timesheet.",
+ "type": "Type of work reported (e.g. hourly, milestone, bonus).",
+ "scale": "Unit the reported quantity is measured in (e.g. hourly, daily, weekly).",
+ "status": "Review status of the timesheet (e.g. pending, approved, declined).",
+ "contract": "The contract the time was reported against.",
+ "quantity": "Amount of work reported, in the units given by the scale.",
+ "worksheet": "Breakdown of the reported time into days, hours, weeks and minutes.",
+ "created_at": "Time at which the timesheet was created.",
+ "description": "Free-text description of the work reported.",
+ "reported_by": "The person who submitted the timesheet.",
+ "reviewed_by": "The person who reviewed the timesheet, and their remarks.",
+ "total_amount": "Total amount payable for the reported work.",
+ "currency_code": "Currency the total amount is denominated in.",
+ "payment_cycle": "Start and end date of the payment cycle the timesheet falls in.",
+ "date_submitted": "Date the timesheet was submitted for review.",
+ },
+ },
+ "payments": {
+ "description": "A payment made to Deel, covering the invoices settled in one transaction.",
+ "docs_url": "https://developer.deel.com/reference/retrievepaymentreceipts",
+ "columns": {
+ "id": "Unique identifier for the payment.",
+ "label": "Human-readable label for the payment.",
+ "total": "Total amount of the payment.",
+ "status": "Current status of the payment (e.g. paid, processing).",
+ "paid_at": "Time at which the payment was completed.",
+ "workers": "Workers covered by the payment, with their contract ids.",
+ "invoices": "Invoices settled by the payment.",
+ "total_due": "Amount still due on the payment.",
+ "created_at": "Time at which the payment was created.",
+ "deel_reference": "Deel's own reference for the payment.",
+ "payment_method": "Method used to make the payment.",
+ "payment_currency": "Currency the payment was made in.",
+ },
+ },
+ "payment_breakdowns": {
+ "description": "One contract's share of a payment, split into work, bonuses, expenses and fees.",
+ "docs_url": "https://developer.deel.com/reference/retrieveapaymentbreakdown",
+ "columns": {
+ "payment_id": "Identifier of the payment this line belongs to.",
+ "contract_id": "Identifier of the contract this line is for.",
+ "invoice_id": "Identifier of the invoice this line was billed on.",
+ "date": "Date the line was recorded.",
+ "work": "Amount charged for regular work.",
+ "bonus": "Amount charged as a bonus.",
+ "total": "Total amount for the line, in the contract currency.",
+ "others": "Amount charged under other categories.",
+ "currency": "Currency the line amounts are denominated in.",
+ "expenses": "Amount charged as reimbursed expenses.",
+ "overtime": "Amount charged for overtime.",
+ "pro_rata": "Amount charged as a pro-rata adjustment.",
+ "frequency": "Payment frequency of the contract.",
+ "adjustment": "Amount charged as an adjustment.",
+ "deductions": "Amount withheld as deductions.",
+ "commissions": "Amount charged as commission.",
+ "payment_date": "Date the payment was made.",
+ "contract_type": "Type of the contract this line is for.",
+ "processing_fee": "Deel processing fee charged on the line.",
+ "contract_country": "Country of the contract this line is for.",
+ "payment_currency": "Currency the payment was made in.",
+ "general_ledger_account": "General ledger account the line is booked to.",
+ "total_payment_currency": "Total for the line, converted to the payment currency.",
+ },
+ },
+ "legal_entities": {
+ "description": "A legal entity in the organization that contracts and invoices are issued under.",
+ "docs_url": "https://developer.deel.com/reference/listoflegalentities",
+ "columns": {
+ "id": "Unique identifier for the legal entity.",
+ "name": "Registered name of the legal entity.",
+ "phone": "Contact phone number for the legal entity.",
+ "vat_id": "VAT identification number of the legal entity.",
+ "address": "Registered address of the legal entity.",
+ "country": "Country the legal entity is registered in.",
+ "created_at": "Time at which the legal entity was created.",
+ "updated_at": "Time at which the legal entity was last updated.",
+ "archived_at": "Time at which the legal entity was archived, if applicable.",
+ "entity_type": "Type of the legal entity.",
+ "industry_name": "Industry the legal entity operates in.",
+ "entity_subtype": "Subtype of the legal entity.",
+ "registrationNumber": "Company registration number of the legal entity.",
+ },
+ },
+ "cost_centers": {
+ "description": "A cost center defined on a legal entity, used to book worker costs.",
+ "docs_url": "https://developer.deel.com/reference/getcostcentersbylegalentity",
+ "columns": {
+ "id": "Identifier for the cost center, unique within its legal entity.",
+ "legal_entity_id": "Identifier of the legal entity the cost center belongs to.",
+ "created_at": "Time at which the cost center was created.",
+ "updated_at": "Time at which the cost center was last updated.",
+ "cost_center_name": "Name of the cost center.",
+ "cost_center_number": "Reference number of the cost center.",
+ },
+ },
+ "time_offs": {
+ "description": "A time-off request made by a worker, with the days it covers.",
+ "docs_url": "https://developer.deel.com/reference/listtimeoffrequestsfororganization",
+ "columns": {
+ "id": "Unique identifier for the time-off request.",
+ "amount": "Amount of time off requested, in the entitlement unit.",
+ "reason": "Reason given for the time off.",
+ "status": "Current status of the request (e.g. pending, approved, rejected).",
+ "is_paid": "Whether the time off is paid.",
+ "end_date": "Last day of the time off.",
+ "created_at": "Time at which the request was created.",
+ "deleted_at": "Time at which the request was deleted, if applicable.",
+ "start_date": "First day of the time off.",
+ "updated_at": "Time at which the request was last updated.",
+ "approved_at": "Time at which the request was approved, if applicable.",
+ "canceled_at": "Time at which the request was cancelled, if applicable.",
+ "description": "Free-text description of the request.",
+ "contract_oid": "Identifier of the contract the request is against.",
+ "requested_at": "Time at which the time off was requested.",
+ "time_off_type": "Type of time off, and the policy it draws from.",
+ "deduction_amount": "Amount deducted from the worker's entitlement.",
+ "entitlement_unit": "Unit the amount is measured in (e.g. days, hours).",
+ "time_off_dailies": "Per-day breakdown of the time off.",
+ "recipient_profile": "Worker profile the time off is for.",
+ "requester_profile": "Worker profile that submitted the request.",
+ },
+ },
+ "time_off_events": {
+ "description": "A lifecycle event on a worker's time-off policy, such as a birth or adoption that triggers leave.",
+ "docs_url": "https://developer.deel.com/reference/gettimeoffeventsforprofile",
+ "columns": {
+ "id": "Identifier for the event, unique within its worker profile.",
+ "type": "Type of the event.",
+ "policy_id": "Identifier of the time-off policy the event applies to.",
+ "created_at": "Time at which the event was created.",
+ "updated_at": "Time at which the event was last updated.",
+ "event_details": "Details of the event, such as the birth or adoption date.",
+ "hris_profile_id": "Identifier of the worker profile the event belongs to.",
+ "time_off_type_id": "Identifier of the time-off type the event applies to.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/deel/deel.py b/products/warehouse_sources/backend/temporal/data_imports/sources/deel/deel.py
index ecc21a8fffc3..0b36c2757915 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/deel/deel.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/deel/deel.py
@@ -1,46 +1,88 @@
-import dataclasses
-from typing import Any, Optional
+from collections.abc import Iterable, Iterator
+from functools import partial
+from typing import Any, Optional, cast
from requests import Request, Response
+from posthog.dataclasses import frozen
+
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.fanout import (
+ build_dependent_resource,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
BasePaginator,
OffsetPaginator,
+ SinglePagePaginator,
+)
+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
-from products.warehouse_sources.backend.temporal.data_imports.sources.deel.settings import DEEL_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.deel.settings import (
+ DEEL_ENDPOINTS,
+ TIME_OFF_EVENTS_ENDPOINT,
+ TIME_OFF_EVENTS_PARENT,
+ DeelEndpointConfig,
+)
DEEL_BASE_URL = "https://api.letsdeel.com/rest/v2"
-# Several Deel endpoints cap `limit` below 100, so stay safely under every cap.
-PAGE_SIZE = 50
+REQUEST_TIMEOUT_SECONDS = 30
+
+# Time-off rows carry absence reasons and family/medical event details, and timesheets carry a
+# free-text work description plus a reviewer's remarks — none of it name-tagged in a way the
+# name-based sample scrubbers can spot.
+_UNCAPTURED_ENDPOINTS = frozenset({"time_offs", TIME_OFF_EVENTS_ENDPOINT, "timesheets"})
+@frozen
class DeelResumeConfig:
- # Offset-paginated endpoints persist the offset; the contracts keyset walk
- # persists Deel's opaque `after_cursor` instead.
+ # Offset-paginated endpoints persist the offset; the keyset endpoints persist Deel's opaque
+ # next-page cursor instead.
offset: Optional[int] = None
cursor: Optional[str] = None
+ # Fan-out endpoints resume per parent — see
+ # `common.rest_source.__init__._make_paginate_dependent_resource`.
+ completed: Optional[list[str]] = None
+ current: Optional[str] = None
+ child_state: Optional[dict[str, Any]] = None
+
+
+def _find(body: Any, path: tuple[str, ...]) -> Any:
+ for key in path:
+ if not isinstance(body, dict):
+ return None
+ body = body.get(key)
+ return body
class DeelCursorPaginator(BasePaginator):
- """Keyset paginator for Deel's ``after_cursor`` endpoints (e.g. contracts).
+ """Keyset paginator for Deel's cursor endpoints.
- The next cursor lives at ``page.cursor`` in the body. Terminate when the response
- carries no next cursor OR returns no rows — Deel can echo a stale cursor on an
- exhausted keyset, so an empty page must stop the walk rather than loop.
+ The next cursor's body path and the query param that sends it back vary per endpoint.
+ Terminate when the response carries no next cursor, publishes a false "has more" flag,
+ returns no rows, OR echoes back the same cursor it was just sent — Deel can return a stale
+ or unchanged cursor on an exhausted keyset while still claiming more pages exist, so both
+ an empty page and a repeated cursor must stop the walk rather than loop forever.
"""
- def __init__(self, cursor_param: str = "after_cursor") -> None:
+ def __init__(
+ self,
+ cursor_param: str = "after_cursor",
+ cursor_path: tuple[str, ...] = ("page", "cursor"),
+ has_more_path: Optional[tuple[str, ...]] = None,
+ ) -> None:
super().__init__()
self.cursor_param = cursor_param
+ self.cursor_path = cursor_path
+ self.has_more_path = has_more_path
self._cursor: Optional[str] = None
def _inject(self, request: Request) -> None:
@@ -58,11 +100,16 @@ class DeelCursorPaginator(BasePaginator):
self._has_next_page = False
return
try:
- next_cursor = (response.json().get("page") or {}).get("cursor")
+ body = response.json()
except Exception:
- next_cursor = None
- if next_cursor:
- self._cursor = next_cursor
+ self._has_next_page = False
+ return
+ if self.has_more_path is not None and not _find(body, self.has_more_path):
+ self._has_next_page = False
+ return
+ next_cursor = _find(body, self.cursor_path)
+ if next_cursor and str(next_cursor) != self._cursor:
+ self._cursor = str(next_cursor)
self._has_next_page = True
else:
self._has_next_page = False
@@ -80,6 +127,39 @@ class DeelCursorPaginator(BasePaginator):
self._has_next_page = True
+def _make_paginator(config: DeelEndpointConfig) -> BasePaginator:
+ if config.pagination == "cursor":
+ return DeelCursorPaginator(
+ cursor_param=config.cursor_param,
+ cursor_path=config.cursor_path,
+ has_more_path=config.has_more_path,
+ )
+ if config.pagination == "offset":
+ # OffsetPaginator injects both limit and offset; termination is a short/empty page
+ # (Deel exposes no dependable top-level total).
+ return OffsetPaginator(limit=config.page_size, total_path=None)
+ return SinglePagePaginator()
+
+
+def _client_config(api_token: str, config: DeelEndpointConfig) -> ClientConfig:
+ client_config: ClientConfig = {
+ "base_url": DEEL_BASE_URL,
+ # Bearer auth via the framework so the token is redacted from logs.
+ "auth": {"type": "bearer", "token": api_token},
+ }
+ if config.name in _UNCAPTURED_ENDPOINTS:
+ client_config["capture"] = False
+ return client_config
+
+
+def _base_params(config: DeelEndpointConfig) -> dict[str, Any]:
+ params: dict[str, Any] = dict(config.params)
+ # The offset paginator injects its own limit; the cursor endpoints need it sent up front.
+ if config.pagination == "cursor" and config.page_size_param is not None:
+ params[config.page_size_param] = config.page_size
+ return params
+
+
def validate_credentials(api_token: str) -> tuple[bool, str | None]:
"""Confirm the API token is valid with a cheap one-person listing probe.
@@ -99,70 +179,53 @@ def validate_credentials(api_token: str) -> tuple[bool, str | None]:
return True, None
-def deel_source(
+def _top_level_items(
+ config: DeelEndpointConfig,
api_token: str,
- endpoint: str,
team_id: int,
job_id: str,
resumable_source_manager: ResumableSourceManager[DeelResumeConfig],
- db_incremental_field_last_value: Optional[Any] = None,
-) -> SourceResponse:
- config = DEEL_ENDPOINTS[endpoint]
-
+ db_incremental_field_last_value: Optional[Any],
+) -> Iterable[Any]:
resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
- paginator: BasePaginator
- params: dict[str, Any]
- initial_paginator_state: Optional[dict[str, Any]]
-
- if config.pagination == "cursor":
- paginator = DeelCursorPaginator()
- params = {"limit": PAGE_SIZE}
- initial_paginator_state = (
- {"cursor": resume.cursor} if resume is not None and resume.cursor is not None else None
- )
-
- def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
- # Persist only when a next page remains; save AFTER a page is yielded so a crash
- # re-yields the last page (merge dedupes) rather than skipping it.
- if state and state.get("cursor") is not None:
- resumable_source_manager.save_state(DeelResumeConfig(cursor=str(state["cursor"])))
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resume is not None:
+ if config.pagination == "cursor" and resume.cursor is not None:
+ initial_paginator_state = {"cursor": resume.cursor}
+ elif config.pagination == "offset" and resume.offset is not None:
+ initial_paginator_state = {"offset": resume.offset}
- else:
- # OffsetPaginator injects both limit and offset; termination is a short/empty page
- # (Deel exposes no dependable top-level total), matching the hand-rolled walk.
- paginator = OffsetPaginator(limit=PAGE_SIZE, total_path=None)
- params = {}
- initial_paginator_state = (
- {"offset": resume.offset} if resume is not None and resume.offset is not None else None
- )
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # Persist only when a next page remains; save AFTER a page is yielded so a crash
+ # re-yields the last page (merge dedupes) rather than skipping it.
+ if not state:
+ return
+ if config.pagination == "cursor" and state.get("cursor") is not None:
+ resumable_source_manager.save_state(DeelResumeConfig(cursor=str(state["cursor"])))
+ elif config.pagination == "offset" and state.get("offset") is not None:
+ resumable_source_manager.save_state(DeelResumeConfig(offset=int(state["offset"])))
- def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
- if state and state.get("offset") is not None:
- resumable_source_manager.save_state(DeelResumeConfig(offset=int(state["offset"])))
+ client_config = _client_config(api_token, config)
+ client_config["paginator"] = _make_paginator(config)
rest_config: RESTAPIConfig = {
- "client": {
- "base_url": DEEL_BASE_URL,
- # Bearer auth via the framework so the token is redacted from logs.
- "auth": {"type": "bearer", "token": api_token},
- "paginator": paginator,
- },
+ "client": client_config,
"resources": [
{
- "name": endpoint,
+ "name": config.name,
"endpoint": {
"path": config.path,
- "params": params,
+ "params": _base_params(config),
# A missing `data` key is treated as an empty page (lenient), matching the
# hand-rolled `body.get("data", [])` — not a fail-loud like other sources.
- "data_selector": "data",
+ "data_selector": config.data_selector,
},
}
],
}
- resource = rest_api_resource(
+ return rest_api_resource(
rest_config,
team_id,
job_id,
@@ -171,15 +234,187 @@ def deel_source(
initial_paginator_state=initial_paginator_state,
)
+
+def _fanout_items(
+ config: DeelEndpointConfig,
+ api_token: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[DeelResumeConfig],
+ db_incremental_field_last_value: Optional[Any],
+) -> Iterable[Any]:
+ fanout = config.fanout
+ assert fanout is not None
+ parent_config = DEEL_ENDPOINTS[fanout.parent_name]
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ initial_state: Optional[dict[str, Any]] = None
+ if resume is not None and (resume.completed or resume.current):
+ initial_state = {
+ "completed": resume.completed or [],
+ "current": resume.current,
+ "child_state": resume.child_state,
+ }
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ if state is not None:
+ resumable_source_manager.save_state(
+ DeelResumeConfig(
+ completed=state.get("completed"),
+ current=state.get("current"),
+ child_state=state.get("child_state"),
+ )
+ )
+
+ parent_endpoint: Endpoint = {
+ "paginator": _make_paginator(parent_config),
+ "data_selector": parent_config.data_selector,
+ }
+ child_endpoint: Endpoint = {
+ "paginator": _make_paginator(config),
+ "data_selector": config.data_selector,
+ }
+
+ return cast(
+ Iterable[Any],
+ build_dependent_resource(
+ endpoint_configs=DEEL_ENDPOINTS,
+ child_endpoint=config.name,
+ fanout=fanout,
+ client_config=_client_config(api_token, config),
+ path_format_values={},
+ team_id=team_id,
+ job_id=job_id,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ # Both hops take their page size from fanout.parent_params, or none at all.
+ page_size_param=None,
+ parent_endpoint_extra=parent_endpoint,
+ child_endpoint_extra=child_endpoint,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_state,
+ ),
+ )
+
+
+def _time_off_event_items(
+ config: DeelEndpointConfig,
+ api_token: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[DeelResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ """Yield one batch of time-off event rows per page of people.
+
+ Hand-rolled rather than a dependent resource because Deel takes the worker profile as a query
+ param, and the shared fan-out helper binds path params only.
+ """
+ parent_config = DEEL_ENDPOINTS[TIME_OFF_EVENTS_PARENT]
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ initial_paginator_state = {"offset": resume.offset} if resume is not None and resume.offset is not None else None
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # The hook runs when this generator asks for the next page, so after its rows are out.
+ if state and state.get("offset") is not None:
+ resumable_source_manager.save_state(DeelResumeConfig(offset=int(state["offset"])))
+
+ parent_client_config = _client_config(api_token, parent_config)
+ parent_client_config["paginator"] = _make_paginator(parent_config)
+
+ parent_rest_config: RESTAPIConfig = {
+ "client": parent_client_config,
+ "resources": [
+ {
+ "name": TIME_OFF_EVENTS_PARENT,
+ "endpoint": {
+ "path": parent_config.path,
+ "params": _base_params(parent_config),
+ "data_selector": parent_config.data_selector,
+ },
+ }
+ ],
+ }
+
+ people = rest_api_resource(
+ parent_rest_config,
+ team_id,
+ job_id,
+ None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+ session = make_tracked_session(redact_values=(api_token,), capture=False)
+ headers = {"Authorization": f"Bearer {api_token}", "Accept": "application/json"}
+
+ for page in people:
+ rows: list[dict[str, Any]] = []
+ for person in page:
+ hris_profile_id = person.get("id")
+ if hris_profile_id is None:
+ continue
+ response = session.get(
+ f"{DEEL_BASE_URL}{config.path}",
+ params={"hris_profile_id": str(hris_profile_id)},
+ headers=headers,
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+ if response.status_code == 404:
+ # The person went away between the listing and this fetch.
+ continue
+ response.raise_for_status()
+ body = response.json()
+ events = body.get("data") if isinstance(body, dict) else None
+ for event in events or []:
+ # Deel omits hris_profile_id from some event rows, and it is half the primary key.
+ rows.append({**event, "hris_profile_id": event.get("hris_profile_id") or str(hris_profile_id)})
+ if rows:
+ yield rows
+
+
+def deel_source(
+ api_token: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[DeelResumeConfig],
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = DEEL_ENDPOINTS[endpoint]
+
+ items: Any
+ column_hints: Optional[dict[str, Any]] = None
+ if endpoint == TIME_OFF_EVENTS_ENDPOINT:
+ items = partial(
+ _time_off_event_items,
+ config,
+ api_token,
+ team_id,
+ job_id,
+ resumable_source_manager,
+ )
+ else:
+ builder = _fanout_items if config.fanout is not None else _top_level_items
+ resource = builder(
+ config,
+ api_token,
+ team_id,
+ job_id,
+ resumable_source_manager,
+ db_incremental_field_last_value,
+ )
+ items = lambda: resource # noqa: E731
+ column_hints = getattr(resource, "column_hints", None)
+
return SourceResponse(
name=endpoint,
- items=lambda: resource,
- primary_keys=[config.primary_key],
+ items=items,
+ primary_keys=config.primary_keys,
partition_count=1,
partition_size=1,
partition_mode="datetime" if config.partition_key else None,
partition_format="month" if config.partition_key else None,
partition_keys=[config.partition_key] if config.partition_key else None,
sort_mode="asc",
- column_hints=resource.column_hints,
+ column_hints=column_hints,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/deel/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/deel/settings.py
index 6608f35fec70..541723577d33 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/deel/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/deel/settings.py
@@ -1,23 +1,52 @@
-from dataclasses import dataclass
-from typing import Literal, Optional
+from dataclasses import dataclass, field
+from typing import Any, Literal, Optional
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ DependentEndpointConfig,
+)
+from products.warehouse_sources.backend.types import IncrementalField
-@dataclass
+# Several Deel endpoints cap `limit` below 100, so stay safely under every cap.
+PAGE_SIZE = 50
+
+
+# Mutable by choice, not oversight: instances flow into `build_dependent_resource`'s
+# `endpoint_configs: Mapping[str, FanoutEndpointLike]`, and mypy treats a frozen dataclass's fields
+# as read-only, which is incompatible with that Protocol's plain (read-write) attributes.
+@dataclass(frozen=False)
class DeelEndpointConfig:
name: str
path: str
- # Deel mixes pagination styles per endpoint: limit/offset with `page`
- # metadata on most endpoints, `after_cursor` keyset on contracts.
- pagination: Literal["offset", "cursor"]
- primary_key: str = "id"
+ # Deel mixes pagination styles per endpoint: limit/offset with `page` metadata on most
+ # endpoints, keyset cursors on others, and no pagination at all on the per-parent children.
+ pagination: Literal["offset", "cursor", "none"]
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
# Stable creation-time field used for datetime partitioning.
partition_key: Optional[str] = None
+ # Where the next-page cursor sits in the body, and the query param that sends it back. Deel
+ # varies both per endpoint.
+ cursor_path: tuple[str, ...] = ("page", "cursor")
+ cursor_param: str = "after_cursor"
+ # Body path to an explicit "another page exists" flag, on the endpoints that publish one.
+ has_more_path: Optional[tuple[str, ...]] = None
+ # Query param carrying the page size; None for the endpoints that accept no size param.
+ page_size_param: Optional[str] = "limit"
+ page_size: int = PAGE_SIZE
+ data_selector: str = "data"
+ # Extra query params sent on every request to this endpoint.
+ params: dict[str, Any] = field(default_factory=dict)
+ fanout: Optional[DependentEndpointConfig] = None
+ # Deel exposes no updated-since filter on the endpoints synced here, so both stay empty —
+ # `FanoutEndpointLike` requires them.
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ default_incremental_field: Optional[str] = None
# Core HR objects expose no updated-since filter and invoices change status
# after issuing, so every stream is an honest full refresh (matching Fivetran's
# Lite connector). Date-range incremental on invoices/timesheets is a possible
-# follow-up once the filter behavior is verified against a live account.
+# follow-up once the filter behavior is verified against a live account, as is
+# `updated_start_date` on time_offs.
DEEL_ENDPOINTS: dict[str, DeelEndpointConfig] = {
"people": DeelEndpointConfig(
name="people",
@@ -40,6 +69,85 @@ DEEL_ENDPOINTS: dict[str, DeelEndpointConfig] = {
path="/invoice-adjustments",
pagination="offset",
),
+ "timesheets": DeelEndpointConfig(
+ name="timesheets",
+ path="/timesheets",
+ pagination="offset",
+ partition_key="created_at",
+ ),
+ "payments": DeelEndpointConfig(
+ name="payments",
+ path="/payments",
+ pagination="cursor",
+ cursor_path=("data", "next_cursor"),
+ cursor_param="cursor",
+ has_more_path=("data", "has_more"),
+ data_selector="data.rows",
+ # /payments accepts no page-size param.
+ page_size_param=None,
+ partition_key="created_at",
+ ),
+ "payment_breakdowns": DeelEndpointConfig(
+ name="payment_breakdowns",
+ path="/payments/{payment_id}/breakdown",
+ pagination="none",
+ # Breakdown rows carry no id of their own: one row per contract line of a payment.
+ primary_keys=["payment_id", "contract_id", "invoice_id"],
+ page_size_param=None,
+ fanout=DependentEndpointConfig(
+ parent_name="payments",
+ resolve_param="payment_id",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "payment_id"},
+ ),
+ ),
+ "legal_entities": DeelEndpointConfig(
+ name="legal_entities",
+ path="/legal-entities",
+ pagination="cursor",
+ cursor_param="cursor",
+ params={"sort_order": "ASC"},
+ ),
+ "cost_centers": DeelEndpointConfig(
+ name="cost_centers",
+ path="/legal-entities/{legal_entity_id}/cost-centers",
+ pagination="none",
+ # Deel does not document the cost centre id as unique outside its legal entity.
+ primary_keys=["legal_entity_id", "id"],
+ page_size_param=None,
+ fanout=DependentEndpointConfig(
+ parent_name="legal_entities",
+ resolve_param="legal_entity_id",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "legal_entity_id"},
+ parent_params={"limit": PAGE_SIZE, "sort_order": "ASC"},
+ ),
+ ),
+ "time_offs": DeelEndpointConfig(
+ name="time_offs",
+ path="/time_offs",
+ pagination="cursor",
+ cursor_path=("next",),
+ cursor_param="next",
+ has_more_path=("has_next_page",),
+ page_size_param="page_size",
+ partition_key="created_at",
+ ),
+ "time_off_events": DeelEndpointConfig(
+ name="time_off_events",
+ path="/time_offs/time-off-events",
+ pagination="none",
+ # Deel does not document the event id as unique outside its worker profile.
+ primary_keys=["hris_profile_id", "id"],
+ page_size_param=None,
+ ),
}
+# `/time_offs/time-off-events` takes its worker profile as a query param, which the shared fan-out
+# helper cannot bind (it binds path params only), so it walks its parent by hand.
+TIME_OFF_EVENTS_ENDPOINT = "time_off_events"
+TIME_OFF_EVENTS_PARENT = "people"
+
ENDPOINTS = tuple(DEEL_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/deel/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/deel/source.py
index 3dee7535947b..03fa0269d17a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/deel/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/deel/source.py
@@ -54,7 +54,7 @@ class DeelSource(ResumableSource[DeelSourceConfig, DeelResumeConfig]):
label="Deel",
caption="""Enter your Deel API token to pull your Deel workforce and payroll data into the PostHog Data warehouse.
-Create an organization token in [Deel](https://app.deel.com/developer-center) under More > Developer with read scopes for the data you want to sync (e.g. `people:read`, `contracts:read`, `accounting:read`). Prefer an organization token over a personal token — personal tokens stop working when the user leaves the organization.""",
+Create an organization token in [Deel](https://app.deel.com/developer-center) under More > Developer with read scopes for the data you want to sync (`people:read`, `contracts:read`, `accounting:read`, `timesheets:read`, `time-off:read`, `legal-entity:read`, `organizations:read`). Prefer an organization token over a personal token — personal tokens stop working when the user leaves the organization.""",
iconPath="/static/services/deel.png",
docsUrl="https://posthog.com/docs/cdp/sources/deel",
releaseStatus=ReleaseStatus.ALPHA,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/deel/tests/test_deel.py b/products/warehouse_sources/backend/temporal/data_imports/sources/deel/tests/test_deel.py
index ff3e87cdd093..09a369ac7cef 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/deel/tests/test_deel.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/deel/tests/test_deel.py
@@ -8,12 +8,15 @@ import requests
from requests import Response
from products.warehouse_sources.backend.temporal.data_imports.sources.deel.deel import (
- PAGE_SIZE,
DeelResumeConfig,
deel_source,
validate_credentials,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.deel.settings import DEEL_ENDPOINTS, ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.deel.settings import (
+ DEEL_ENDPOINTS,
+ ENDPOINTS,
+ PAGE_SIZE,
+)
# 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"
@@ -34,6 +37,27 @@ def _response(items: list[dict[str, Any]] | None, *, cursor: str | None = None,
return resp
+def _wrapped_response(body: dict[str, Any]) -> Response:
+ resp = Response()
+ resp.status_code = 200
+ resp._content = json.dumps(body).encode()
+ return resp
+
+
+def _payments_response(
+ items: list[dict[str, Any]], *, next_cursor: str | None = None, has_more: bool = False
+) -> Response:
+ return _wrapped_response(
+ {"data": {"rows": items, "has_more": has_more, "next_cursor": next_cursor, "total": len(items)}}
+ )
+
+
+def _time_offs_response(
+ items: list[dict[str, Any]], *, next_token: str | None = None, has_next: bool = False
+) -> Response:
+ return _wrapped_response({"data": items, "next": next_token, "has_next_page": has_next})
+
+
def _make_manager(resume_state: DeelResumeConfig | None = None) -> mock.MagicMock:
manager = mock.MagicMock()
manager.can_resume.return_value = resume_state is not None
@@ -41,22 +65,29 @@ def _make_manager(resume_state: DeelResumeConfig | None = None) -> mock.MagicMoc
return manager
-def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:
- """Wire a mock session and capture each request's params AT SEND TIME.
+def _wire_capture(session: mock.MagicMock, responses: list[Response]) -> tuple[list[dict[str, Any]], list[str]]:
+ """Wire a mock session and capture each request's params and URL AT SEND TIME.
``request.params`` is a single dict mutated in place across pages, so snapshot a copy
when each request is prepared instead of inspecting the final state.
"""
session.headers = {}
param_snapshots: list[dict[str, Any]] = []
+ urls: list[str] = []
def _prepare(request: Any) -> mock.MagicMock:
param_snapshots.append(dict(request.params or {}))
+ urls.append(request.url)
return mock.MagicMock()
session.prepare_request.side_effect = _prepare
session.send.side_effect = responses
- return param_snapshots
+ return param_snapshots, urls
+
+
+def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:
+ params, _urls = _wire_capture(session, responses)
+ return params
def _source(endpoint: str, manager: mock.MagicMock):
@@ -212,7 +243,7 @@ class TestDeelSourceResponse:
response = _source(endpoint, _make_manager())
assert response.name == endpoint
- assert response.primary_keys == [config.primary_key]
+ assert response.primary_keys == config.primary_keys
assert response.sort_mode == "asc"
if config.partition_key:
assert response.partition_mode == "datetime"
@@ -225,3 +256,181 @@ class TestDeelSourceResponse:
def test_partition_keys_are_stable_creation_fields(self, config):
if config.partition_key:
assert config.partition_key == "created_at"
+
+
+class TestPaymentsPagination:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_walks_data_rows_until_has_more_is_false(self, MockSession):
+ # Payments nest their rows and cursor under `data`, unlike every other Deel endpoint.
+ session = MockSession.return_value
+ params = _wire(
+ session,
+ [
+ _payments_response([{"id": "p1"}], next_cursor="cur_1", has_more=True),
+ _payments_response([{"id": "p2"}], next_cursor="cur_2", has_more=False),
+ ],
+ )
+
+ manager = _make_manager()
+ rows = _rows(_source("payments", manager))
+
+ assert [r["id"] for r in rows] == ["p1", "p2"]
+ # /payments takes no page-size param, so sending one would be undocumented.
+ assert "limit" not in params[0]
+ assert "cursor" not in params[0]
+ assert params[1]["cursor"] == "cur_1"
+ assert manager.save_state.call_args_list == [mock.call(DeelResumeConfig(cursor="cur_1"))]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_stops_when_has_more_is_false_despite_an_echoed_cursor(self, MockSession):
+ session = MockSession.return_value
+ _wire(session, [_payments_response([{"id": "p1"}], next_cursor="cur_stale", has_more=False)])
+
+ manager = _make_manager()
+ rows = _rows(_source("payments", manager))
+
+ assert [r["id"] for r in rows] == ["p1"]
+ assert session.send.call_count == 1
+ manager.save_state.assert_not_called()
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_stops_when_has_more_is_true_but_the_cursor_is_unchanged(self, MockSession):
+ # A buggy or exhausted keyset can echo the same cursor back while still claiming
+ # more pages exist. Without an equality check the walk would re-request that page
+ # forever instead of stopping.
+ session = MockSession.return_value
+ _wire(
+ session,
+ [
+ _payments_response([{"id": "p1"}], next_cursor="cur_1", has_more=True),
+ _payments_response([{"id": "p1"}], next_cursor="cur_1", has_more=True),
+ ],
+ )
+
+ manager = _make_manager()
+ rows = _rows(_source("payments", manager))
+
+ assert [r["id"] for r in rows] == ["p1", "p1"]
+ assert session.send.call_count == 2
+ manager.save_state.assert_called_once_with(DeelResumeConfig(cursor="cur_1"))
+
+
+class TestTimeOffsPagination:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_walks_next_token_with_page_size_param(self, MockSession):
+ session = MockSession.return_value
+ params = _wire(
+ session,
+ [
+ _time_offs_response([{"id": "t1"}], next_token="tok_1", has_next=True),
+ _time_offs_response([{"id": "t2"}], has_next=False),
+ ],
+ )
+
+ manager = _make_manager()
+ rows = _rows(_source("time_offs", manager))
+
+ assert [r["id"] for r in rows] == ["t1", "t2"]
+ # Time off sizes pages with `page_size`, not `limit`.
+ assert params[0]["page_size"] == PAGE_SIZE
+ assert "limit" not in params[0]
+ assert params[1]["next"] == "tok_1"
+
+
+class TestLegalEntitiesPagination:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_sends_cursor_param_and_explicit_sort_order(self, MockSession):
+ # Legal entities page on `cursor`, not the `after_cursor` contracts use.
+ session = MockSession.return_value
+ params = _wire(session, [_response([{"id": "le1"}], cursor="cur_le"), _response([{"id": "le2"}])])
+
+ manager = _make_manager()
+ rows = _rows(_source("legal_entities", manager))
+
+ assert [r["id"] for r in rows] == ["le1", "le2"]
+ assert params[0]["sort_order"] == "ASC"
+ assert params[0]["limit"] == PAGE_SIZE
+ assert params[1]["cursor"] == "cur_le"
+ assert "after_cursor" not in params[1]
+
+
+class TestFanoutEndpoints:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_payment_breakdowns_carry_their_payment_id(self, MockSession):
+ session = MockSession.return_value
+ _params, urls = _wire_capture(
+ session,
+ [
+ _payments_response([{"id": "pay_1"}, {"id": "pay_2"}]),
+ _wrapped_response({"data": [{"contract_id": "c1", "invoice_id": "i1"}]}),
+ _wrapped_response({"data": [{"contract_id": "c2", "invoice_id": "i2"}]}),
+ ],
+ )
+
+ rows = _rows(_source("payment_breakdowns", _make_manager()))
+
+ assert urls[1:] == [
+ "https://api.letsdeel.com/rest/v2/payments/pay_1/breakdown",
+ "https://api.letsdeel.com/rest/v2/payments/pay_2/breakdown",
+ ]
+ # The parent id is renamed off `_payments_id` because it is part of the primary key.
+ assert [(r["payment_id"], r["contract_id"]) for r in rows] == [("pay_1", "c1"), ("pay_2", "c2")]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_cost_centers_carry_their_legal_entity_id(self, MockSession):
+ session = MockSession.return_value
+ _params, urls = _wire_capture(
+ session,
+ [
+ _response([{"id": "le_1"}]),
+ _wrapped_response({"data": [{"id": 7, "cost_center_name": "R&D"}]}),
+ ],
+ )
+
+ rows = _rows(_source("cost_centers", _make_manager()))
+
+ assert urls[1] == "https://api.letsdeel.com/rest/v2/legal-entities/le_1/cost-centers"
+
+ assert rows == [{"id": 7, "cost_center_name": "R&D", "legal_entity_id": "le_1"}]
+
+
+class TestTimeOffEvents:
+ @mock.patch(DEEL_SESSION_PATCH)
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_fans_out_over_people_by_query_param(self, MockClientSession, MockDeelSession):
+ _wire(MockClientSession.return_value, [_response([{"id": "prof_1"}, {"id": "prof_2"}])])
+ child_session = MockDeelSession.return_value
+ child_session.get.side_effect = [
+ _wrapped_response({"data": [{"id": "ev_1", "hris_profile_id": "prof_1"}]}),
+ _wrapped_response({"data": [{"id": "ev_2"}]}),
+ ]
+
+ rows = _rows(_source("time_off_events", _make_manager()))
+
+ assert [call.args[0] for call in child_session.get.call_args_list] == [
+ "https://api.letsdeel.com/rest/v2/time_offs/time-off-events"
+ ] * 2
+ assert [call.kwargs["params"]["hris_profile_id"] for call in child_session.get.call_args_list] == [
+ "prof_1",
+ "prof_2",
+ ]
+ # Deel omits hris_profile_id from some rows; it is half the primary key, so backfill it.
+ assert [(r["id"], r["hris_profile_id"]) for r in rows] == [("ev_1", "prof_1"), ("ev_2", "prof_2")]
+
+ @mock.patch(DEEL_SESSION_PATCH)
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_skips_a_person_that_disappeared_between_the_listing_and_the_fetch(
+ self, MockClientSession, MockDeelSession
+ ):
+ _wire(MockClientSession.return_value, [_response([{"id": "prof_1"}, {"id": "prof_2"}])])
+ gone = Response()
+ gone.status_code = 404
+ gone._content = b"{}"
+ MockDeelSession.return_value.get.side_effect = [
+ gone,
+ _wrapped_response({"data": [{"id": "ev_2", "hris_profile_id": "prof_2"}]}),
+ ]
+
+ rows = _rows(_source("time_off_events", _make_manager()))
+
+ assert [r["id"] for r in rows] == ["ev_2"]