:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(warehouse-sources): add deel org, payroll, lifecycle and lookup tables (#106637)
Tom Owers11dcf0306930
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.mdindex d4ea575efa39..16c135e930f5 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@@ -2381,7 +2381,7 @@ Note: docs.decagon.ai is a fully client-rendered Mintlify site that returns the## Deel — **thin**-Today (11): `contracts`, `cost_centers`, `invoice_adjustments`, `invoices`, `legal_entities`, `payment_breakdowns`, `payments`, `people`, `time_off_events`, `time_offs`, `timesheets`+Today (23): `contracts`, `cost_centers`, `countries`, `currencies`, `departments`, `groups`, `invoice_adjustments`, `invoices`, `job_titles`, `legal_entities`, `offboarding_tracker`, `onboarding_tracker`, `payment_breakdowns`, `payments`, `payroll_cycles`, `payroll_gross_to_net`, `payroll_reports`, `people`, `seniorities`, `teams`, `time_off_events`, `time_offs`, `timesheets`Diffed against: <https://api.letsdeel.com/openapi/rest/definitions>@@ -2389,17 +2389,18 @@ Diffed against: <https://api.letsdeel.com/openapi/rest/definitions>- [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)+- [x] `/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)-- [ ] `/reports/payroll/cycles/{cycle_id}/gross-to-net (and /gp/legal-entities/{id}/reports)` — gross-to-net payroll report — the canonical payroll cost breakdown (medium)+- [x] `/reports/payroll/cycles/{cycle_id}/gross-to-net (and /gp/legal-entities/{id}/reports)` — gross-to-net payroll report — the canonical payroll cost breakdown (medium)- [ ] `/contracts/{contract_id}/amendments (and /eor/contracts/{id}/amendments)` — contract change history: comp changes over time rather than only current state (medium)-- [ ] `/onboarding/tracker and /offboarding/tracker` — worker lifecycle state so joiner/leaver funnels can be measured (medium)-- [ ] `/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)+- [x] `/onboarding/tracker and /offboarding/tracker` — worker lifecycle state so joiner/leaver funnels can be measured (medium)+- [x] `/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 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.+Sub-endpoints of the ticked lines that were deliberately not given their own table: `/contracts/{contract_id}/timesheets` returns the same rows as `/timesheets` filtered to one contract; `/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; and `/lookups/time-off-types` returns a bare array of enum strings with no object shape or row identity, and those same values already arrive on `/time_offs` rows.+The gross-to-net line added a third table, `payroll_cycles` (`/legal-entities/{id}/payroll-events`): the report is keyed by payroll cycle and cycles are only listed per legal entity, so the cycle listing is both the path to the report and the table that dates it.## Deepgram — gapsdiff --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.pyindex 64292cc91264..d15f796f56ce 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@@ -206,4 +206,139 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"time_off_type_id": "Identifier of the time-off type the event applies to.",},},+ "departments": {+ "description": "A department in the organization's structure, used to group workers on people rows.",+ "docs_url": "https://developer.deel.com/reference/getdepartments",+ "columns": {+ "id": "Unique identifier for the department.",+ "name": "The name of the department.",+ "parent": "Identifier of the parent department, if the department is nested.",+ },+ },+ "teams": {+ "description": "A team within the organization, used to group workers on people rows.",+ "docs_url": "https://developer.deel.com/reference/getteams",+ "columns": {+ "id": "Unique identifier of the team within the organization.",+ "name": "The name of the team.",+ },+ },+ "groups": {+ "description": "A group in the organization, used to organize workers and assign managers.",+ "docs_url": "https://developer.deel.com/reference/getgroups",+ "columns": {+ "id": "Unique identifier of the group.",+ "name": "The name of the group.",+ "status": "Current status of the group (active or archived).",+ "managers": "Number of managers associated with the group.",+ "created_at": "Time at which the group was created.",+ "updated_at": "Time at which the group was last updated.",+ "archived_at": "Time at which the group was archived, if applicable.",+ "external_metadata": "Extra information stored against the group.",+ },+ },+ "onboarding_tracker": {+ "description": "The onboarding state of a worker joining the organization.",+ "docs_url": "https://developer.deel.com/reference/listonboardingemployees",+ "columns": {+ "name": "Name of the person being onboarded.",+ "contract": "The contract associated with the onboarding, and its effective date.",+ "progress": "Progress of the onboarding, including status and due date.",+ "unique_id": "Identifier for the tracker entry.",+ "hiring_type": "Type of hiring (e.g. contractor, eor, direct_employee).",+ "hris_profile": "Worker profile being onboarded.",+ "app_experience": "Whether the person meets the minimal experience requirements.",+ },+ },+ "offboarding_tracker": {+ "description": "The offboarding state of a worker leaving the organization.",+ "docs_url": "https://developer.deel.com/reference/retrieveoffboardinglist",+ "columns": {+ "name": "Name of the person being offboarded.",+ "contract": "The contract associated with the offboarding.",+ "progress": "Progress of the offboarding, including status and reference date.",+ "unique_id": "Identifier for the tracker entry.",+ "hiring_type": "Type of hiring (e.g. contractor, eor, direct_employee).",+ "hris_profile": "Worker profile being offboarded.",+ "app_experience": "Whether the person meets the minimal experience requirements.",+ "termination_id": "Identifier of the termination, if the person has been terminated.",+ "offboarding_type": "Type of offboarding (TERMINATION, RESIGNATION or ENDING_CONTRACT).",+ },+ },+ "payroll_cycles": {+ "description": "A payroll cycle run for a legal entity, and whether a gross-to-net report exists for it.",+ "docs_url": "https://developer.deel.com/reference/listpayrollcycles",+ "columns": {+ "id": "Identifier for the payroll cycle, unique within its legal entity.",+ "type": "Type of payroll cycle (REGULAR or OFFCYCLE).",+ "date_end": "End date of the payroll cycle.",+ "date_start": "Start date of the payroll cycle.",+ "has_g2n_report": "Whether a gross-to-net report is available for this cycle.",+ "legal_entity_id": "Identifier of the legal entity the cycle belongs to.",+ "payroll_group_id": "Identifier of the payroll group the cycle belongs to.",+ },+ },+ "payroll_reports": {+ "description": "A global payroll event for a legal entity, with the period it covers and its status.",+ "docs_url": "https://developer.deel.com/reference/listpayrolleventsbylegalentity",+ "columns": {+ "id": "Identifier for the payroll event, unique within its legal entity.",+ "status": "Status of the payroll event (e.g. OPEN, CLOSED).",+ "end_date": "End date of the payroll event.",+ "lock_date": "Date the payroll event is locked, if applicable.",+ "start_date": "Start date of the payroll event.",+ "legal_entity_id": "Identifier of the legal entity the payroll event belongs to.",+ },+ },+ "payroll_gross_to_net": {+ "description": "The gross-to-net cost breakdown for one contract in a payroll cycle.",+ "docs_url": "https://developer.deel.com/reference/getsg2nreportdataforagivenpayrollcyclebyitsid",+ "columns": {+ "items": "Payroll line items, each with a label, value, category and category group "+ "(ADDITIONS, DEDUCTIONS, BENEFITS, INFOS, CONTRIBUTIONS or TOTALS).",+ "currency": "Currency the payroll amounts are denominated in.",+ "cycle_id": "Identifier of the payroll cycle the breakdown belongs to.",+ "contract_oid": "Identifier of the contract the breakdown is for.",+ "payment_data": "Payment currency and conversion rate applied, if the payment currency differs.",+ "legal_entity_id": "Identifier of the legal entity that ran the payroll cycle.",+ },+ },+ "countries": {+ "description": "A country Deel supports, and what it supports there — the lookup behind country codes on contracts and people.",+ "docs_url": "https://developer.deel.com/reference/retrievecountrylist",+ "columns": {+ "code": "ISO 3166-1 alpha-2 country code.",+ "name": "Official name of the country.",+ "states": "States or regions within the country, with their codes and names.",+ "state_type": "What the country calls its subdivisions (e.g. state, province).",+ "eor_support": "Whether Deel supports employer of record hiring in the country.",+ "visa_support": "Whether Deel supports visa sponsorship in the country.",+ "default_currency": "Default currency used in the country.",+ },+ },+ "currencies": {+ "description": "A currency Deel supports — the lookup behind currency codes on contracts, invoices and payments.",+ "docs_url": "https://developer.deel.com/reference/retrievesupportedcurrencylist",+ "columns": {+ "code": "ISO 4217 three-letter currency code.",+ "name": "Name of the currency.",+ },+ },+ "job_titles": {+ "description": "A job title Deel recognizes — the lookup behind job title ids on contracts and people.",+ "docs_url": "https://developer.deel.com/reference/jobtitleslist",+ "columns": {+ "id": "Unique identifier of the job title.",+ "name": "The job title.",+ },+ },+ "seniorities": {+ "description": "A seniority level Deel recognizes — the lookup behind seniority ids on contracts.",+ "docs_url": "https://developer.deel.com/reference/retrievesenioritylevels",+ "columns": {+ "id": "Unique identifier for the seniority level.",+ "name": "Name of the seniority level (e.g. 'Mid (Individual Contributor Level 2)').",+ "level": "Hierarchical level, where higher numbers mean greater seniority.",+ },+ },}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.pyindex 0b36c2757915..258e456eb39a 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@@ -2,7 +2,7 @@ from collections.abc import Iterable, Iteratorfrom functools import partialfrom typing import Any, Optional, cast-from requests import Request, Response+from requests import Request, Response, Sessionfrom posthog.dataclasses import frozen@@ -28,6 +28,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.soufrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.deel.settings import (DEEL_ENDPOINTS,+ GROSS_TO_NET_ENDPOINT,+ GROSS_TO_NET_PARENT,+ GROSS_TO_NET_ROOT,TIME_OFF_EVENTS_ENDPOINT,TIME_OFF_EVENTS_PARENT,DeelEndpointConfig,@@ -36,10 +39,20 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.deel.settiDEEL_BASE_URL = "https://api.letsdeel.com/rest/v2"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+# Time-off rows carry absence reasons and family/medical event details, timesheets carry a+# free-text work description plus a reviewer's remarks, the trackers carry worker names and work+# emails, and gross-to-net carries per-worker pay — 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"})+_UNCAPTURED_ENDPOINTS = frozenset(+ {+ "time_offs",+ TIME_OFF_EVENTS_ENDPOINT,+ "timesheets",+ "onboarding_tracker",+ "offboarding_tracker",+ GROSS_TO_NET_ENDPOINT,+ }+)@frozen@@ -49,7 +62,8 @@ class DeelResumeConfig:offset: Optional[int] = Nonecursor: Optional[str] = None# Fan-out endpoints resume per parent — see- # `common.rest_source.__init__._make_paginate_dependent_resource`.+ # `common.rest_source.__init__._make_paginate_dependent_resource`. Gross-to-net reuses+ # `completed` for the payroll cycles it has already emitted.completed: Optional[list[str]] = Nonecurrent: Optional[str] = Nonechild_state: Optional[dict[str, Any]] = None@@ -372,6 +386,91 @@ def _time_off_event_items(yield rows+def _iter_cursor_pages(+ session: Session,+ url: str,+ config: DeelEndpointConfig,+ headers: dict[str, str],+ ignore_statuses: tuple[int, ...] = (),+) -> Iterator[list[dict[str, Any]]]:+ """Walk a Deel keyset endpoint by hand, with the same termination rules as DeelCursorPaginator.++ Used where the endpoint sits too deep for the shared fan-out helper to bind its path params.+ """+ params = _base_params(config)+ cursor: Optional[str] = None++ while True:+ if cursor is not None:+ params[config.cursor_param] = cursor+ response = session.get(url, params=params, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)+ if response.status_code in ignore_statuses:+ return+ response.raise_for_status()+ body = response.json()++ rows = _find(body, tuple(config.data_selector.split(".")))+ if not rows:+ return+ yield rows++ if config.has_more_path is not None and not _find(body, config.has_more_path):+ return+ next_cursor = _find(body, config.cursor_path)+ if not next_cursor or str(next_cursor) == cursor:+ return+ cursor = str(next_cursor)+++def _gross_to_net_items(+ config: DeelEndpointConfig,+ api_token: str,+ resumable_source_manager: ResumableSourceManager[DeelResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ """Yield gross-to-net rows per payroll cycle.++ Hand-rolled because the cycle ids are two hops from a top-level listing: legal entities+ carry payroll cycles, and the shared fan-out helper binds a single level of path params.+ Resume is per cycle rather than per page, so an interrupted sync re-walks the cheap+ listings and skips straight to the reports it had not reached.+ """+ root_config = DEEL_ENDPOINTS[GROSS_TO_NET_ROOT]+ cycle_config = DEEL_ENDPOINTS[GROSS_TO_NET_PARENT]++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ # Keyed by legal entity and cycle together, because a cycle id is only unique within its+ # entity — the same reason payroll_cycles takes a composite primary key.+ completed: list[str] = list(resume.completed) if resume is not None and resume.completed else []+ done = set(completed)++ session = make_tracked_session(redact_values=(api_token,), capture=False)+ headers = {"Authorization": f"Bearer {api_token}", "Accept": "application/json"}++ for entity_page in _iter_cursor_pages(session, f"{DEEL_BASE_URL}{root_config.path}", root_config, headers):+ for entity in entity_page:+ legal_entity_id = entity.get("id")+ if legal_entity_id is None:+ continue+ cycles_url = f"{DEEL_BASE_URL}{cycle_config.path.replace('{legal_entity_id}', str(legal_entity_id))}"+ for cycle_page in _iter_cursor_pages(session, cycles_url, cycle_config, headers, ignore_statuses=(404,)):+ for cycle in cycle_page:+ cycle_id = cycle.get("id")+ if cycle_id is None:+ continue+ cycle_key = f"{legal_entity_id}:{cycle_id}"+ # Deel only publishes a report for a cycle it flags; the rest 404.+ if not cycle.get("has_g2n_report") or cycle_key in done:+ continue+ report_url = f"{DEEL_BASE_URL}{config.path.replace('{cycle_id}', str(cycle_id))}"+ for rows in _iter_cursor_pages(session, report_url, config, headers, ignore_statuses=(404,)):+ yield [+ {**row, "cycle_id": str(cycle_id), "legal_entity_id": str(legal_entity_id)} for row in rows+ ]+ completed.append(cycle_key)+ done.add(cycle_key)+ resumable_source_manager.save_state(DeelResumeConfig(completed=list(completed)))++def deel_source(api_token: str,endpoint: str,@@ -393,6 +492,8 @@ def deel_source(job_id,resumable_source_manager,)+ elif endpoint == GROSS_TO_NET_ENDPOINT:+ items = partial(_gross_to_net_items, config, api_token, resumable_source_manager)else:builder = _fanout_items if config.fanout is not None else _top_level_itemsresource = builder(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.pyindex 541723577d33..f568cfe3dedc 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@@ -143,6 +143,120 @@ DEEL_ENDPOINTS: dict[str, DeelEndpointConfig] = {primary_keys=["hris_profile_id", "id"],page_size_param=None,),+ "departments": DeelEndpointConfig(+ name="departments",+ path="/departments",+ pagination="none",+ page_size_param=None,+ ),+ "teams": DeelEndpointConfig(+ name="teams",+ path="/teams",+ pagination="none",+ page_size_param=None,+ ),+ "groups": DeelEndpointConfig(+ name="groups",+ path="/groups",+ pagination="cursor",+ cursor_param="cursor",+ params={"sort_order": "ASC"},+ partition_key="created_at",+ ),+ "onboarding_tracker": DeelEndpointConfig(+ name="onboarding_tracker",+ path="/onboarding/tracker",+ pagination="cursor",+ cursor_param="cursor",+ # One row per worker being onboarded; the tracker carries no id of its own.+ primary_keys=["unique_id"],+ params={"sort_order": "ASC"},+ ),+ "offboarding_tracker": DeelEndpointConfig(+ name="offboarding_tracker",+ path="/offboarding/tracker",+ pagination="cursor",+ cursor_param="cursor",+ primary_keys=["unique_id"],+ # Without `ignore_date_range` Deel returns only the last 45 days of terminations.+ params={"sort_order": "ASC", "ignore_date_range": "true"},+ ),+ "payroll_cycles": DeelEndpointConfig(+ name="payroll_cycles",+ path="/legal-entities/{legal_entity_id}/payroll-events",+ pagination="cursor",+ cursor_path=("next_cursor",),+ cursor_param="cursor",+ has_more_path=("has_more",),+ # Deel does not document the cycle id as unique outside its legal entity.+ primary_keys=["legal_entity_id", "id"],+ 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"},+ child_params={"limit": PAGE_SIZE},+ ),+ ),+ "payroll_reports": DeelEndpointConfig(+ name="payroll_reports",+ path="/gp/legal-entities/{legal_entity_id}/reports",+ pagination="none",+ # Global payroll events sit in their own id space; scope them to their 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"},+ ),+ ),+ "payroll_gross_to_net": DeelEndpointConfig(+ name="payroll_gross_to_net",+ path="/reports/payroll/cycles/{cycle_id}/gross-to-net",+ pagination="cursor",+ cursor_path=("next_cursor",),+ cursor_param="cursor",+ has_more_path=("has_more",),+ # One row per contract in a payroll cycle. The cycle is only unique within its legal+ # entity, so the entity leads the key here the same way it does on payroll_cycles.+ primary_keys=["legal_entity_id", "cycle_id", "contract_oid"],+ ),+ "countries": DeelEndpointConfig(+ name="countries",+ path="/lookups/countries",+ pagination="none",+ primary_keys=["code"],+ page_size_param=None,+ ),+ "currencies": DeelEndpointConfig(+ name="currencies",+ path="/lookups/currencies",+ pagination="none",+ primary_keys=["code"],+ page_size_param=None,+ ),+ "job_titles": DeelEndpointConfig(+ name="job_titles",+ path="/lookups/job-titles",+ pagination="cursor",+ # Job titles echo a cursor even past the last page, so the walk ends on the empty page+ # that cursor returns rather than on a missing cursor.+ cursor_param="after_cursor",+ # /lookups/job-titles accepts no page-size param.+ page_size_param=None,+ ),+ "seniorities": DeelEndpointConfig(+ name="seniorities",+ path="/lookups/seniorities",+ pagination="none",+ page_size_param=None,+ ),}# `/time_offs/time-off-events` takes its worker profile as a query param, which the shared fan-out@@ -150,4 +264,10 @@ DEEL_ENDPOINTS: dict[str, DeelEndpointConfig] = {TIME_OFF_EVENTS_ENDPOINT = "time_off_events"TIME_OFF_EVENTS_PARENT = "people"+# Gross-to-net is keyed by payroll cycle, and cycles are only listed per legal entity, so this+# endpoint is two hops from a top-level listing — one more than the shared fan-out helper binds.+GROSS_TO_NET_ENDPOINT = "payroll_gross_to_net"+GROSS_TO_NET_PARENT = "payroll_cycles"+GROSS_TO_NET_ROOT = "legal_entities"+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.pyindex 03fa0269d17a..7457182d68e7 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 (`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.""",+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`, `groups:read`, `global-payroll:read`, `payslips: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.pyindex 09a369ac7cef..0ff572a6160d 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@@ -58,6 +58,13 @@ def _time_offs_response(return _wrapped_response({"data": items, "next": next_token, "has_next_page": has_next})+def _payroll_response(+ items: list[dict[str, Any]], *, next_cursor: str | None = None, has_more: bool = False+) -> Response:+ # Payroll cycles and gross-to-net put both the cursor and the flag at the top level.+ return _wrapped_response({"data": items, "has_more": has_more, "next_cursor": next_cursor})++def _make_manager(resume_state: DeelResumeConfig | None = None) -> mock.MagicMock:manager = mock.MagicMock()manager.can_resume.return_value = resume_state is not None@@ -434,3 +441,185 @@ class TestTimeOffEvents:rows = _rows(_source("time_off_events", _make_manager()))assert [r["id"] for r in rows] == ["ev_2"]+++class TestTrackerEndpoints:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_offboarding_asks_for_every_termination(self, MockSession):+ # Deel defaults the offboarding tracker to the last 45 days; without this the table+ # silently loses every older leaver.+ session = MockSession.return_value+ params = _wire(session, [_response([{"unique_id": "off_1"}])])++ rows = _rows(_source("offboarding_tracker", _make_manager()))++ assert [r["unique_id"] for r in rows] == ["off_1"]+ assert params[0]["ignore_date_range"] == "true"+ assert params[0]["sort_order"] == "ASC"++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_onboarding_pages_on_cursor(self, MockSession):+ session = MockSession.return_value+ params = _wire(+ session, [_response([{"unique_id": "on_1"}], cursor="cur_1"), _response([{"unique_id": "on_2"}])]+ )++ rows = _rows(_source("onboarding_tracker", _make_manager()))++ assert [r["unique_id"] for r in rows] == ["on_1", "on_2"]+ assert "ignore_date_range" not in params[0]+ assert params[1]["cursor"] == "cur_1"+++class TestLookupEndpoints:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_job_titles_page_on_after_cursor_without_a_page_size(self, MockSession):+ session = MockSession.return_value+ # Deel echoes a cursor past the last page, so the empty page is what ends the walk.+ params = _wire(+ session,+ [_response([{"id": 1}], cursor="cur_1"), _response([], cursor="cur_2")],+ )++ rows = _rows(_source("job_titles", _make_manager()))++ assert [r["id"] for r in rows] == [1]+ assert "limit" not in params[0]+ assert params[1]["after_cursor"] == "cur_1"+ assert session.send.call_count == 2++ @pytest.mark.parametrize(+ "endpoint, path",+ [+ ("departments", "https://api.letsdeel.com/rest/v2/departments"),+ ("teams", "https://api.letsdeel.com/rest/v2/teams"),+ ("countries", "https://api.letsdeel.com/rest/v2/lookups/countries"),+ ("currencies", "https://api.letsdeel.com/rest/v2/lookups/currencies"),+ ("seniorities", "https://api.letsdeel.com/rest/v2/lookups/seniorities"),+ ],+ )+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_unpaginated_lookups_send_one_request_with_no_page_size(self, MockSession, endpoint, path):+ session = MockSession.return_value+ params, urls = _wire_capture(session, [_response([{"code": "US"}])])++ _rows(_source(endpoint, _make_manager()))++ assert urls == [path]+ assert params[0] == {}+ assert session.send.call_count == 1+++class TestPayrollEndpoints:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_payroll_cycles_fan_out_and_carry_their_legal_entity(self, MockSession):+ session = MockSession.return_value+ params, urls = _wire_capture(+ session,+ [+ _response([{"id": "le_1"}]),+ _payroll_response([{"id": "cy_1"}], next_cursor="cur_1", has_more=True),+ _payroll_response([{"id": "cy_2"}], has_more=False),+ ],+ )++ rows = _rows(_source("payroll_cycles", _make_manager()))++ assert urls[1:] == ["https://api.letsdeel.com/rest/v2/legal-entities/le_1/payroll-events"] * 2+ assert params[2]["cursor"] == "cur_1"+ assert params[1]["limit"] == PAGE_SIZE+ assert [(r["id"], r["legal_entity_id"]) for r in rows] == [("cy_1", "le_1"), ("cy_2", "le_1")]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_payroll_reports_carry_their_legal_entity(self, MockSession):+ session = MockSession.return_value+ _params, urls = _wire_capture(+ session,+ [+ _response([{"id": "le_1"}]),+ _wrapped_response({"data": [{"id": "ev_1", "status": "CLOSED"}]}),+ ],+ )++ rows = _rows(_source("payroll_reports", _make_manager()))++ assert urls[1] == "https://api.letsdeel.com/rest/v2/gp/legal-entities/le_1/reports"+ assert rows == [{"id": "ev_1", "status": "CLOSED", "legal_entity_id": "le_1"}]+++class TestGrossToNet:+ @mock.patch(DEEL_SESSION_PATCH)+ def test_walks_legal_entities_then_cycles_then_reports(self, MockSession):+ session = MockSession.return_value+ session.get.side_effect = [+ _response([{"id": "le_1"}]),+ _payroll_response([{"id": "cy_1", "has_g2n_report": True}, {"id": "cy_2", "has_g2n_report": False}]),+ _payroll_response([{"contract_oid": "con_1"}]),+ ]++ manager = _make_manager()+ rows = _rows(_source("payroll_gross_to_net", manager))++ assert [call.args[0] for call in session.get.call_args_list] == [+ "https://api.letsdeel.com/rest/v2/legal-entities",+ "https://api.letsdeel.com/rest/v2/legal-entities/le_1/payroll-events",+ # cy_2 publishes no report, so it is never requested.+ "https://api.letsdeel.com/rest/v2/reports/payroll/cycles/cy_1/gross-to-net",+ ]+ assert rows == [{"contract_oid": "con_1", "cycle_id": "cy_1", "legal_entity_id": "le_1"}]+ assert rows[0]["legal_entity_id"] == "le_1"+ # The cycle is checkpointed once its rows are out, so a resume skips it. A cycle id is+ # only unique within its legal entity, so the checkpoint carries both.+ manager.save_state.assert_called_once_with(DeelResumeConfig(completed=["le_1:cy_1"]))++ @mock.patch(DEEL_SESSION_PATCH)+ def test_resume_skips_cycles_already_emitted(self, MockSession):+ session = MockSession.return_value+ session.get.side_effect = [+ _response([{"id": "le_1"}]),+ _payroll_response([{"id": "cy_1", "has_g2n_report": True}, {"id": "cy_2", "has_g2n_report": True}]),+ _payroll_response([{"contract_oid": "con_2"}]),+ ]++ manager = _make_manager(DeelResumeConfig(completed=["le_1:cy_1"]))+ rows = _rows(_source("payroll_gross_to_net", manager))++ assert [call.args[0] for call in session.get.call_args_list][-1] == (+ "https://api.letsdeel.com/rest/v2/reports/payroll/cycles/cy_2/gross-to-net"+ )+ assert [r["cycle_id"] for r in rows] == ["cy_2"]+ assert manager.save_state.call_args.args[0] == DeelResumeConfig(completed=["le_1:cy_1", "le_1:cy_2"])++ @mock.patch(DEEL_SESSION_PATCH)+ def test_skips_a_cycle_whose_report_went_away(self, MockSession):+ # A cycle can flag a report that 404s by the time we ask for it; that must not fail+ # the whole sync.+ gone = Response()+ gone.status_code = 404+ gone._content = b"{}"+ session = MockSession.return_value+ session.get.side_effect = [+ _response([{"id": "le_1"}]),+ _payroll_response([{"id": "cy_1", "has_g2n_report": True}, {"id": "cy_2", "has_g2n_report": True}]),+ gone,+ _payroll_response([{"contract_oid": "con_2"}]),+ ]++ rows = _rows(_source("payroll_gross_to_net", _make_manager()))++ assert [r["contract_oid"] for r in rows] == ["con_2"]++ @mock.patch(DEEL_SESSION_PATCH)+ def test_stops_a_report_that_keeps_echoing_the_same_cursor(self, MockSession):+ session = MockSession.return_value+ session.get.side_effect = [+ _response([{"id": "le_1"}]),+ _payroll_response([{"id": "cy_1", "has_g2n_report": True}]),+ _payroll_response([{"contract_oid": "con_1"}], next_cursor="cur_1", has_more=True),+ _payroll_response([{"contract_oid": "con_1"}], next_cursor="cur_1", has_more=True),+ ]++ rows = _rows(_source("payroll_gross_to_net", _make_manager()))++ assert [r["contract_oid"] for r in rows] == ["con_1", "con_1"]+ assert session.get.call_count == 4