: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(factorial): sync worked times, project time records, compensations and allowance stats (#107277)
Tom Owersdbd5b3b474ba
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 1bdeec2cea86..062943c1978c 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@@ -2990,14 +2990,14 @@ Note: Endpoint list extracted from the \*.api URLs on the developers page. Also## Factorial — **thin**-Today (17): `allowances`, `applications`, `attendance_shifts`, `candidates`, `contract_versions`, `employees`, `expenses`, `flexible_time_records`, `job_postings`, `leave_types`, `leaves`, `legal_entities`, `locations`, `payroll_supplements`, `projects`, `team_memberships`, `teams`+Today (21): `allowance_stats`, `allowances`, `applications`, `attendance_shifts`, `candidates`, `compensations`, `contract_versions`, `employees`, `expenses`, `flexible_time_records`, `job_postings`, `leave_types`, `leaves`, `legal_entities`, `locations`, `payroll_supplements`, `projects`, `team_memberships`, `teams`, `time_records`, `worked_times`Diffed against: <https://apidoc.factorialhr.com/reference>-- [ ] `attendance/worked_times` — aggregated worked time per employee and day - the headline attendance metric, currently only raw shifts are synced (high)-- [ ] `project_management/time_records` — time booked against projects; projects are synced but the time booked to them is not (high)-- [ ] `contracts/compensations` — salary and compensation amounts attached to contract versions we already sync (high)-- [ ] `timeoff/allowance_stats` — consumed vs remaining balance per employee and allowance - the number leave reporting actually needs (high)+- [x] `attendance/worked_times` — aggregated worked time per employee and day - the headline attendance metric, currently only raw shifts are synced (high)+- [x] `project_management/time_records` — time booked against projects; projects are synced but the time booked to them is not (high)+- [x] `contracts/compensations` — salary and compensation amounts attached to contract versions we already sync (high)+- [x] `timeoff/allowance_stats` — consumed vs remaining balance per employee and allowance - the number leave reporting actually needs (high)- [ ] `ats/hiring_stages and ats/application_phases` — lookup tables resolving the stage/phase id carried on every synced application (high)- [ ] `finance/cost_centers` — lookup table for cost allocation across employees, expenses and projects (high)- [ ] `employee_updates/terminations` — attrition events with dates and reasons; headcount churn is not derivable from the employees snapshot (high)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/factorial/api_inventory.md b/products/warehouse_sources/backend/temporal/data_imports/sources/factorial/api_inventory.mdindex c91da9cd6eda..ef107092b8cc 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/factorial/api_inventory.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/factorial/api_inventory.md@@ -38,9 +38,11 @@ Source-local notes for the Factorial (HRIS) connector. See the official referenc## Incremental sync- Server-side `updated_after` is documented for only a narrow set of resources —- `project_management/flexible_time_records` and `project_management/subprojects`. It is **not** documented- on the higher-value people / time-off / attendance streams (Airbyte's connector confirms this: it filters- `updated_at` client-side everywhere except `shifts`).+ `project_management/flexible_time_records`, `project_management/time_records` and+ `project_management/subprojects`. It is **not** documented on the higher-value people / time-off /+ attendance streams (Airbyte's connector confirms this: it filters `updated_at` client-side everywhere+ except `shifts`). `time_records` accepts the filter but its response carries no `updated_at` column, so+ there is no cursor the pipeline could advance a watermark on — it stays full refresh regardless.- Per the implementing-warehouse-sources guidance, a client-side cursor that still walks every page is notincremental, and the two `updated_after` endpoints can't be curl-verified without a live API key. So everyendpoint currently ships **full refresh** (`INCREMENTAL_FIELDS = {}`). Promote `flexible_time_records` /@@ -58,13 +60,17 @@ Source-local notes for the Factorial (HRIS) connector. See the official referenc| locations | `/resources/locations/locations` | — || legal_entities | `/resources/companies/legal_entities` | — || contract_versions | `/resources/contracts/contract_versions` | created_at |+| compensations | `/resources/contracts/compensations` | — || leaves | `/resources/timeoff/leaves` | created_at || leave_types | `/resources/timeoff/leave_types` | — || allowances | `/resources/timeoff/allowances` | — |+| allowance_stats | `/resources/timeoff/allowance_stats` | — || attendance_shifts | `/resources/attendance/shifts` | created_at |+| worked_times | `/resources/attendance/worked_times` | — || expenses | `/resources/expenses/expenses` | created_at || payroll_supplements | `/resources/payroll/supplements` | created_at || flexible_time_records | `/resources/project_management/flexible_time_records` | created_at |+| time_records | `/resources/project_management/time_records` | — || projects | `/resources/project_management/projects` | — || candidates | `/resources/ats/candidates` | created_at || job_postings | `/resources/ats/job_postings` | — |@@ -72,7 +78,9 @@ Source-local notes for the Factorial (HRIS) connector. See the official referencPrimary key is the `id` column on every list resource. It is serialized as an integer on `2025-04-01` and`2026-04-01`, and as an opaque string on `2026-07-01` (see Identifier serialization above), so the column type is-left to inference. Partition keys are `created_at` where the field is reliably present on every row+left to inference. Three resources key on a composite string the API builds for them and documents as unique:+`worked_times` on `<employee_id>_<date>`, `allowance_stats` on `<employee_id>/<allowance_id>/<reference_date>`,+and `time_records` on its own record id. Partition keys are `created_at` where the field is reliably present on every row(transactional records); lookup/config resources are left unpartitioned.## Rate limits@@ -80,9 +88,30 @@ left to inference. Partition keys are `created_at` where the field is reliably p- POST is documented at 200 req/min on `2025-*` endpoints. GET limits and rate-limit response headers are notpublicly documented. The tracked session's default retry handles transient `429`/`5xx`.+## Endpoint-specific notes++- **`attendance/worked_times`** aggregates worked minutes per employee and day; `attendance/shifts` carries+ the raw clock in/out rows the aggregate is built from. The spec marks `include_time_range_category` and+ `include_non_attendable_employees` required, so both are sent on every page (see `settings.py`). Both are+ sent as `"false"`: excluding non-attendable employees keeps the table to the people Factorial tracks+ attendance for, rather than emitting an all-zero row per employee per day for everyone else.+- **`project_management/time_records`** is the time booked against projects, joined to a `project_worker_id`+ and an `attendance_shift_id`. Only available to companies with the `projects_management` feature enabled;+ for everyone else the endpoint is a permission failure, which `get_non_retryable_errors` already maps.+- **`contracts/compensations`** holds the salary and pay-concept lines hanging off a `contract_version_id`+ we already sync. `amount` is in the smallest currency unit.+- **`timeoff/allowance_stats`** is a computed snapshot, not a stored record: it recalculates against a+ `reference_date` that defaults to today, so each full-refresh sync replaces the table with the balances as+ of that run. Its `id` embeds the reference date and the docs state it cannot be used to re-fetch the row.+ The source pins one `reference_date` for the whole walk and carries it in the resume state, so a run that+ crosses midnight or resumes the next day cannot write two as-of dates into the same table.+## Verification statusEndpoint paths, pagination, and the `updated_after` coverage were cross-referenced against the official docs-and the Airbyte/Fivetran connector stream lists. They were **not** curl-verified against a live account (no+and the Airbyte/Fivetran connector stream lists. The four endpoints added most recently — `worked_times`,+`time_records`, `compensations`, `allowance_stats` — were checked against the OpenAPI document the reference+site serves for `2026-07-01` and `2026-04-01`: each is a GET list route returning the+`{"meta": _paged_index_meta, "data": [...]}` envelope, so they page exactly like the existing tables. They were **not** curl-verified against a live account (noAPI key available). The connection (host, version path, `x-api-key`, 401-on-bad-key) was confirmed with anunauthenticated curl returning `401`.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/factorial/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/factorial/canonical_descriptions.pyindex f656e20c6eb5..b33dea31cd70 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/factorial/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/factorial/canonical_descriptions.py@@ -91,6 +91,30 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"updated_at": "Time at which the contract version was last updated.",},},+ "compensations": {+ "description": "Salary and compensation lines attached to a contract version, one row per pay concept.",+ "docs_url": _DOCS,+ "columns": {+ "id": "Unique identifier for the compensation.",+ "contract_version_id": "Identifier of the contract version the compensation belongs to.",+ "contracts_taxonomy_id": "Identifier of the compensation taxonomy (pay concept) this line uses.",+ "description": "Free-text description of the compensation, for example 'Yearly variable'.",+ "compensation_type": "How the amount is applied: fixed, undefined, up_to, per_worked_day or per_worked_hour.",+ "amount": "Value paid on each recurrence, in the smallest currency unit (for example cents).",+ "unit": "Unit the compensation is paid in.",+ "currency": "Currency the compensation is paid in.",+ "recurrence": "How often the employee is paid (monthly, yearly, one_time). Can be empty.",+ "recurrence_count": "Number of months between payments when `recurrence` is empty; 12 means yearly.",+ "starts_on": "Date the compensation starts applying.",+ "first_payment_on": "Date of the first payout, which can be later than `starts_on`.",+ "calculation": "Human-readable hint about the payroll formula used.",+ "payroll_policy_id": "Identifier of the payroll policy the compensation follows.",+ "sync_with_supplements": "Whether the compensation is kept in sync with payroll supplements.",+ "time_condition": "Time condition the compensation applies under: full_day, half_day or custom.",+ "minimum_amount_of_hours": "Minimum hours that must be worked for the compensation to apply.",+ "minimum_amount_of_hours_in_cents": "Minimum hours for the compensation, in cents.",+ },+ },"leaves": {"description": "Individual time-off / absence records for employees.","docs_url": _DOCS,@@ -125,6 +149,33 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"name": "Name of the allowance.",},},+ "allowance_stats": {+ "description": "Time-off counters per employee and allowance: how much is accrued, used, carried over and still available at the reference date.",+ "docs_url": _DOCS,+ "columns": {+ "id": "Virtual identifier composed of employee_id, allowance_id and reference date. It cannot be used to fetch the record again.",+ "allowance_id": "Identifier of the allowance these counters belong to.",+ "employee_id": "Identifier of the employee these counters belong to.",+ "year": "Calendar year the cycle calculations are scoped to.",+ "cycles": "Accrual periods that make up the allowance.",+ "cycle_carry_overs": "Carry-over entries between cycles.",+ "accumulated_carry_over": "Units carried over from previous cycles.",+ "used_carry_over": "Carried-over units already used.",+ "available_days": "Units still usable at the reference date, after usage, carry-over and adjustments.",+ "used_days": "Units used in the current cycle.",+ "used_units_until_reference_date": "Units used up to the reference date.",+ "outstanding_units": "Units still owed to the employee.",+ "total_accrued_units": "Units accrued up to the reference date.",+ "total": "Total entitlement for the cycle, including accrual, carry over and incidences.",+ "total_in_decimal": "Total entitlement in decimal form.",+ "policy_allowance": "Base entitlement from the policy, before proration and adjustments.",+ "prorated_allowance_days": "Entitlement after proration for tenure or configuration.",+ "max_balance_cap": "Maximum balance the policy allows, or null when uncapped.",+ "incidences": "Sum of adjustment units applied to the allowance.",+ "accrued_incidences": "Adjustment units scoped to the accrued balance.",+ "available_incidences": "Adjustment units scoped to the available balance.",+ },+ },"attendance_shifts": {"description": "Attendance shifts: clock-in/clock-out records for employees.","docs_url": _DOCS,@@ -138,6 +189,23 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"updated_at": "Time at which the shift was last updated.",},},+ "worked_times": {+ "description": "Worked time aggregated per employee and day, including tracked, pending and multiplied minutes.",+ "docs_url": _DOCS,+ "columns": {+ "id": "Identifier of the worked time, composed of the employee id and the date.",+ "employee_id": "Identifier of the employee the worked time belongs to.",+ "company_id": "Identifier of the company.",+ "date": "Day the worked time is counted for.",+ "minutes": "Worked minutes counted for the day.",+ "tracked_minutes": "Minutes tracked by the employee for the day.",+ "pending_minutes": "Minutes still pending approval.",+ "multiplied_minutes": "Minutes after multipliers such as overtime rates are applied.",+ "time_unit": "Unit the worked time is measured in: minute, half_day or none.",+ "day_type": "Type of day: workday, saturday, sunday or bank_holiday.",+ "worked_time_blocks": "Individual blocks of time that make up the day's worked time.",+ },+ },"expenses": {"description": "Employee expenses submitted for reimbursement.","docs_url": _DOCS,@@ -175,6 +243,21 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"updated_at": "Time at which the record was last updated.",},},+ "time_records": {+ "description": "Time booked against projects, linking an attendance shift to the project worker and subproject it was spent on.",+ "docs_url": _DOCS,+ "columns": {+ "id": "Unique identifier for the time record.",+ "project_worker_id": "Identifier of the project worker the time is booked for.",+ "attendance_shift_id": "Identifier of the attendance shift the time record belongs to.",+ "subproject_id": "Identifier of the subproject the time is booked against, if any.",+ "date": "Reference date of the shift.",+ "imputed_minutes": "Minutes between the clock in and the clock out.",+ "clock_in": "Time the employee clocked in.",+ "clock_out": "Time the employee clocked out.",+ "observations": "Free-text comment on the time record.",+ },+ },"projects": {"description": "Projects used for time tracking.","docs_url": _DOCS,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/factorial/factorial.py b/products/warehouse_sources/backend/temporal/data_imports/sources/factorial/factorial.pyindex adb7ee99d66f..c8faa3069a3f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/factorial/factorial.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/factorial/factorial.py@@ -1,4 +1,5 @@import dataclasses+from datetime import UTC, datetimefrom typing import Any, Optionalfrom requests import Request, Response@@ -9,7 +10,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resrest_api_resource,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import BasePaginator-from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import EndpointResource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ Endpoint,+ EndpointResource,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.factorial.settings import FACTORIAL_ENDPOINTS@@ -36,10 +40,13 @@ def base_url(api_version: str) -> str:PAGE_SIZE = 100[email protected](frozen=True)class FactorialResumeConfig:# Opaque forward cursor (`meta.end_cursor`) passed back as `after_id` to fetch the next page.after_id: str+ # Date the run pinned for a `date_param` endpoint, so a resumed walk keeps the earlier pages'+ # as-of date instead of recomputing against the day it resumes on.+ reference_date: Optional[str] = Noneclass FactorialCursorPaginator(BasePaginator):@@ -98,18 +105,20 @@ class FactorialCursorPaginator(BasePaginator):self._has_next_page = True-def get_resource(endpoint: str) -> EndpointResource:+def get_resource(endpoint: str, params: Optional[dict[str, str]] = None) -> EndpointResource:config = FACTORIAL_ENDPOINTS[endpoint]+ endpoint_params: dict[str, Any] = dict(config.params if params is None else params)+ endpoint_def: Endpoint = {+ # Every list endpoint wraps its records under a top-level `data` key.+ "data_selector": "data",+ "path": config.path,+ "params": endpoint_params,+ }return {"name": config.name,"table_name": config.name,"write_disposition": "replace",- "endpoint": {- # Every list endpoint wraps its records under a top-level `data` key.- "data_selector": "data",- "path": config.path,- "params": {},- },+ "endpoint": endpoint_def,"table_format": "delta",}@@ -124,6 +133,19 @@ def factorial_source() -> SourceResponse:endpoint_config = FACTORIAL_ENDPOINTS[endpoint]+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None++ params = dict(endpoint_config.params)+ reference_date: Optional[str] = None+ if endpoint_config.date_param:+ # The endpoint recomputes against the date it receives and defaults that to today, so one+ # date is pinned for the whole walk. Without it a run that crosses midnight, or resumes the+ # next day, writes two different as-of dates into the same table.+ reference_date = (resume_config.reference_date if resume_config else None) or datetime.now(+ UTC+ ).date().isoformat()+ params[endpoint_config.date_param] = reference_date+rest_config: RESTAPIConfig = {"client": {"base_url": base_url(api_version),@@ -141,21 +163,21 @@ def factorial_source("resource_defaults": {"write_disposition": "replace",},- "resources": [get_resource(endpoint)],+ "resources": [get_resource(endpoint, params)],}initial_paginator_state: Optional[dict[str, Any]] = None- if resumable_source_manager.can_resume():- resume_config = resumable_source_manager.load_state()- if resume_config is not None:- initial_paginator_state = {"after_id": resume_config.after_id}+ if resume_config is not None:+ initial_paginator_state = {"after_id": resume_config.after_id}def save_checkpoint(state: Optional[dict[str, Any]]) -> None:# Persist only when there's a next page to resume to; the Redis TTL handles cleanup once the# sync finishes. Saving happens after each page is yielded, so a crash re-fetches the last# page rather than skipping it (merge dedupes the re-pulled rows on the primary key).if state and state.get("after_id"):- resumable_source_manager.save_state(FactorialResumeConfig(after_id=str(state["after_id"])))+ resumable_source_manager.save_state(+ FactorialResumeConfig(after_id=str(state["after_id"]), reference_date=reference_date)+ )resource = rest_api_resource(rest_config,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/factorial/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/factorial/settings.pyindex c891e1abbe24..99fb09b5b1e1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/factorial/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/factorial/settings.py@@ -4,7 +4,7 @@ from typing import Optionalfrom products.warehouse_sources.backend.types import IncrementalField-@dataclass+@dataclass(frozen=True)class FactorialEndpointConfig:name: str# Path under the versioned base URL (e.g. "/resources/employees/employees"). Factorial groups@@ -16,6 +16,12 @@ class FactorialEndpointConfig:# (employees, leaves, shifts, expenses, …) but not on every lookup/config resource.partition_key: Optional[str] = Noneprimary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Static query params sent on every page. Booleans are serialized as the strings Factorial+ # expects, since `requests` would otherwise render Python's `True` as the literal "True".+ params: dict[str, str] = field(default_factory=dict)+ # Query param naming the date the endpoint computes against, for resources that default it to+ # today. Set it and the whole walk is pinned to one date (see `factorial.py`).+ date_param: Optional[str] = Noneshould_sync_default: bool = True@@ -49,6 +55,10 @@ FACTORIAL_ENDPOINTS: dict[str, FactorialEndpointConfig] = {path="/resources/contracts/contract_versions",partition_key="created_at",),+ "compensations": FactorialEndpointConfig(+ name="compensations",+ path="/resources/contracts/compensations",+ ),"leaves": FactorialEndpointConfig(name="leaves",path="/resources/timeoff/leaves",@@ -62,11 +72,24 @@ FACTORIAL_ENDPOINTS: dict[str, FactorialEndpointConfig] = {name="allowances",path="/resources/timeoff/allowances",),+ "allowance_stats": FactorialEndpointConfig(+ name="allowance_stats",+ path="/resources/timeoff/allowance_stats",+ date_param="reference_date",+ ),"attendance_shifts": FactorialEndpointConfig(name="attendance_shifts",path="/resources/attendance/shifts",partition_key="created_at",),+ "worked_times": FactorialEndpointConfig(+ name="worked_times",+ path="/resources/attendance/worked_times",+ # Both flags are required by the endpoint. Excluding non-attendable employees keeps the+ # table to people Factorial actually tracks attendance for, instead of emitting an+ # all-zero row per employee per day for everyone else.+ params={"include_time_range_category": "false", "include_non_attendable_employees": "false"},+ ),"expenses": FactorialEndpointConfig(name="expenses",path="/resources/expenses/expenses",@@ -82,6 +105,10 @@ FACTORIAL_ENDPOINTS: dict[str, FactorialEndpointConfig] = {path="/resources/project_management/flexible_time_records",partition_key="created_at",),+ "time_records": FactorialEndpointConfig(+ name="time_records",+ path="/resources/project_management/time_records",+ ),"projects": FactorialEndpointConfig(name="projects",path="/resources/project_management/projects",@@ -104,12 +131,14 @@ FACTORIAL_ENDPOINTS: dict[str, FactorialEndpointConfig] = {ENDPOINTS = tuple(FACTORIAL_ENDPOINTS.keys())-# Full refresh only. Factorial documents a server-side `updated_after` filter on only two of the-# endpoints we sync — `project_management/flexible_time_records` and `project_management/subprojects`-# — and not on the higher-value people/time-off/attendance streams (Airbyte's connector confirms this:-# it filters `updated_at` client-side everywhere except `shifts`). Per the implementing-warehouse-sources-# guidance, a "client-side cursor" that still walks every page is not incremental, so we ship every-# endpoint as full refresh. The two `updated_after`-capable endpoints could be promoted to incremental+# Full refresh only. Factorial documents a server-side `updated_after` filter on only a few of the+# endpoints we sync — `project_management/flexible_time_records`, `project_management/time_records`+# and `project_management/subprojects` — and not on the higher-value people/time-off/attendance+# streams (Airbyte's connector confirms this: it filters `updated_at` client-side everywhere except+# `shifts`). Per the implementing-warehouse-sources guidance, a "client-side cursor" that still walks+# every page is not incremental, so we ship every endpoint as full refresh. `time_records` cannot be+# incremental at all: its response carries no `updated_at` column, so there is no cursor for the+# pipeline to advance the watermark on. `flexible_time_records` / `subprojects` could be promoted# after curl-verifying (with a future-date cutoff) that the filter actually narrows results against a# live account — which requires a Factorial API key we don't have here.INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/factorial/tests/test_factorial.py b/products/warehouse_sources/backend/temporal/data_imports/sources/factorial/tests/test_factorial.pyindex 3197d3e824b0..36915f0e2053 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/factorial/tests/test_factorial.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/factorial/tests/test_factorial.py@@ -1,5 +1,6 @@import jsonfrom collections.abc import Iterable+from datetime import UTC, datetimefrom typing import Any, castimport pytest@@ -25,9 +26,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.factorial.FACTORIAL_ENDPOINTS,)-_SESSION_FACTORY = (- "products.warehouse_sources.backend.temporal.data_imports.sources.factorial.factorial.make_tracked_session"-)+_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.factorial.factorial"+_SESSION_FACTORY = f"{_MODULE}.make_tracked_session"# Paginator logic ignores the request URL (it only touches params), so any supported base is fine here._BASE_URL = base_url(API_VERSION_2026_04_01)@@ -175,54 +175,56 @@ def _make_http_response(body: dict[str, Any], status_code: int = 200) -> Responsreturn resp-class TestFactorialSourceResumeBehavior:- """End-to-end resume behaviour of ``factorial_source`` via ``rest_api_resource``."""-- def _drive(- self,- endpoint: str,- manager: MagicMock,- responses: list[Response],- api_version: str = API_VERSION_2026_04_01,- ) -> tuple[list[dict[str, Any]], list[str]]:- sent_params: list[dict[str, Any]] = []- sent_urls: list[str] = []- response_iter = iter(responses)-- def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:- sent_params.append(dict(request.params or {}))- sent_urls.append(request.url)- return next(response_iter)-- with patch(_SESSION_FACTORY) as MockSession:- mock_session = MockSession.return_value- mock_session.headers = {}- mock_session.prepare_request.side_effect = lambda req: req- mock_session.send.side_effect = fake_send+def _drive(+ endpoint: str,+ manager: MagicMock,+ responses: list[Response],+ api_version: str = API_VERSION_2026_04_01,+) -> tuple[list[dict[str, Any]], list[str]]:+ """Run ``factorial_source`` to exhaustion against canned pages, capturing every request."""+ sent_params: list[dict[str, Any]] = []+ sent_urls: list[str] = []+ response_iter = iter(responses)++ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:+ sent_params.append(dict(request.params or {}))+ sent_urls.append(request.url)+ return next(response_iter)++ with patch(_SESSION_FACTORY) as MockSession:+ mock_session = MockSession.return_value+ mock_session.headers = {}+ mock_session.prepare_request.side_effect = lambda req: req+ mock_session.send.side_effect = fake_send++ source = factorial_source(+ api_key="test-key",+ endpoint=endpoint,+ team_id=123,+ job_id="test_job",+ resumable_source_manager=manager,+ api_version=api_version,+ )+ list(cast(Iterable[Any], source.items()))+ return sent_params, sent_urls+++def _page_body(items: list[dict[str, Any]], meta: dict[str, Any]) -> dict[str, Any]:+ return {"data": items, "meta": meta}- source = factorial_source(- api_key="test-key",- endpoint=endpoint,- team_id=123,- job_id="test_job",- resumable_source_manager=manager,- api_version=api_version,- )- list(cast(Iterable[Any], source.items()))- return sent_params, sent_urls- def _page_body(self, items: list[dict[str, Any]], meta: dict[str, Any]) -> dict[str, Any]:- return {"data": items, "meta": meta}+class TestFactorialSourceResumeBehavior:+ """End-to-end resume behaviour of ``factorial_source`` via ``rest_api_resource``."""def test_fresh_run_saves_cursor_after_each_non_terminal_page(self) -> None:manager = MagicMock(spec=ResumableSourceManager)manager.can_resume.return_value = Falseresponses = [- _make_http_response(self._page_body(_full_page(), {"has_next_page": True, "end_cursor": "Mjc="})),- _make_http_response(self._page_body([{"id": 999}], {"has_next_page": False, "end_cursor": None})),+ _make_http_response(_page_body(_full_page(), {"has_next_page": True, "end_cursor": "Mjc="})),+ _make_http_response(_page_body([{"id": 999}], {"has_next_page": False, "end_cursor": None})),]- sent_params, _ = self._drive("employees", manager, responses)+ sent_params, _ = _drive("employees", manager, responses)# First request starts without a cursor; the second carries the advanced after_id.assert "after_id" not in sent_params[0]@@ -238,9 +240,9 @@ class TestFactorialSourceResumeBehavior:manager.load_state.return_value = FactorialResumeConfig(after_id="MTY=")responses = [- _make_http_response(self._page_body([{"id": 17}], {"has_next_page": False, "end_cursor": None})),+ _make_http_response(_page_body([{"id": 17}], {"has_next_page": False, "end_cursor": None})),]- sent_params, _ = self._drive("employees", manager, responses)+ sent_params, _ = _drive("employees", manager, responses)assert sent_params[0].get("after_id") == "MTY="manager.load_state.assert_called_once()@@ -251,9 +253,9 @@ class TestFactorialSourceResumeBehavior:manager = MagicMock(spec=ResumableSourceManager)manager.can_resume.return_value = Falseresponses = [- _make_http_response(self._page_body([{"id": 1}], {"has_next_page": False, "end_cursor": None})),+ _make_http_response(_page_body([{"id": 1}], {"has_next_page": False, "end_cursor": None})),]- _, sent_urls = self._drive("employees", manager, responses, api_version=api_version)+ _, sent_urls = _drive("employees", manager, responses, api_version=api_version)assert sent_urlsassert all(url.startswith(f"{base_url(api_version)}/resources/employees/employees") for url in sent_urls)@@ -263,9 +265,9 @@ class TestFactorialSourceResumeBehavior:manager.can_resume.return_value = Falseresponses = [- _make_http_response(self._page_body([{"id": 1}], {"has_next_page": False, "end_cursor": None})),+ _make_http_response(_page_body([{"id": 1}], {"has_next_page": False, "end_cursor": None})),]- self._drive("employees", manager, responses)+ _drive("employees", manager, responses)manager.save_state.assert_not_called()@@ -274,13 +276,79 @@ class TestFactorialSourceResumeBehavior:manager.can_resume.return_value = Falseresponses = [- _make_http_response(self._page_body([{"id": 1}], {"has_next_page": False, "end_cursor": None})),+ _make_http_response(_page_body([{"id": 1}], {"has_next_page": False, "end_cursor": None})),]- self._drive("employees", manager, responses)+ _drive("employees", manager, responses)manager.load_state.assert_not_called()+class TestEndpointParams:+ """Static endpoint params must survive both the paginator and the page walk."""++ def test_worked_times_sends_required_include_flags_on_every_page(self) -> None:+ # Factorial rejects `attendance/worked_times` without these two flags, and the paginator+ # rewrites the request in place between pages — so page two must still carry them.+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [+ _make_http_response(_page_body(_full_page(), {"has_next_page": True, "end_cursor": "Mjc="})),+ _make_http_response(_page_body([{"id": "1_2024-07-02"}], {"has_next_page": False, "end_cursor": None})),+ ]+ sent_params, _ = _drive("worked_times", manager, responses)++ assert len(sent_params) == 2+ for params in sent_params:+ assert params["include_time_range_category"] == "false"+ assert params["include_non_attendable_employees"] == "false"++ def test_endpoint_without_params_sends_pagination_params_only(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [+ _make_http_response(_page_body([{"id": "1"}], {"has_next_page": False, "end_cursor": None})),+ ]+ sent_params, _ = _drive("time_records", manager, responses)++ assert sent_params == [{"limit": PAGE_SIZE}]++ def test_allowance_stats_pins_one_reference_date_across_pages(self) -> None:+ # Factorial recomputes allowance_stats against the date it receives, defaulting to today,+ # so a walk that crosses midnight would otherwise mix two as-of dates into one table.+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [+ _make_http_response(_page_body(_full_page(), {"has_next_page": True, "end_cursor": "Mjc="})),+ _make_http_response(_page_body([{"id": "1/2/x"}], {"has_next_page": False, "end_cursor": None})),+ ]+ with patch(f"{_MODULE}.datetime") as mock_datetime:+ mock_datetime.now.return_value = datetime(2026, 5, 4, 23, 59, tzinfo=UTC)+ sent_params, _ = _drive("allowance_stats", manager, responses)++ assert [p["reference_date"] for p in sent_params] == ["2026-05-04", "2026-05-04"]+ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert saved == [FactorialResumeConfig(after_id="Mjc=", reference_date="2026-05-04")]++ def test_allowance_stats_resume_reuses_the_saved_reference_date(self) -> None:+ # A resumed walk must keep the earlier pages' as-of date, not the day it resumes on.+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = True+ manager.load_state.return_value = FactorialResumeConfig(after_id="MTY=", reference_date="2026-05-04")++ responses = [+ _make_http_response(_page_body([{"id": "1/2/x"}], {"has_next_page": False, "end_cursor": None})),+ ]+ with patch(f"{_MODULE}.datetime") as mock_datetime:+ mock_datetime.now.return_value = datetime(2026, 5, 5, 0, 1, tzinfo=UTC)+ sent_params, _ = _drive("allowance_stats", manager, responses)++ assert sent_params[0]["reference_date"] == "2026-05-04"+ assert sent_params[0]["after_id"] == "MTY="++class TestValidateCredentials:@pytest.mark.parametrize(("status_code", "expected_valid"),