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 four missing float tables (#108302)

Tom Owersacbd8b684def
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 ccf9f4279991..a21c9e153053 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
@@ -3256,19 +3256,19 @@ Note: The Flexmail public API is contact-management only - it exposes no campaig
## FloatApp — gaps
-Today (20): `accounts`, `clients`, `currencies`, `deleted_logged_time`, `deleted_tasks`, `deleted_timeoffs`, `departments`, `holidays`, `logged_time`, `milestones`, `people`, `phases`, `project_tasks`, `projects`, `rate_cards`, `roles`, `status`, `tasks`, `timeoff_types`, `timeoffs`
+Today (24): `accounts`, `clients`, `currencies`, `deleted_logged_time`, `deleted_tasks`, `deleted_timeoffs`, `departments`, `holidays`, `logged_time`, `milestones`, `people`, `phases`, `project_expenses`, `project_stages`, `project_tasks`, `projects`, `public_holidays`, `rate_cards`, `reports_people`, `roles`, `status`, `tasks`, `timeoff_types`, `timeoffs`
Diffed against: <https://developer.float.com/swagger-api-v3.yaml>
-- [ ] `/project-stages` — lookup table resolving the stage IDs carried on the projects we already sync (high)
+- [x] `/project-stages` — lookup table resolving the stage IDs carried on the projects we already sync (high)
- [x] `/rate-cards` — lookup for the rate card IDs on people/projects; required to turn logged hours into billable value (high)
-- [ ] `/reports/people` — Float's headline utilization/capacity report per person, pre-aggregated (high)
+- [x] `/reports/people` — Float's headline utilization/capacity report per person, pre-aggregated (high)
- [ ] `/reports/projects` — per-project scheduled vs logged vs billable breakdown (medium)
-- [ ] `/project-expenses` — non-labor project cost, needed for true project margin alongside logged_time (medium)
-- [ ] `/public-holidays` — region public holidays; distinct from the team /holidays table already synced, needed for correct capacity math (medium)
+- [x] `/project-expenses` — non-labor project cost, needed for true project margin alongside logged_time (medium)
+- [x] `/public-holidays` — region public holidays; distinct from the team /holidays table already synced, needed for correct capacity math (medium)
- [x] `/currencies` — lookup for currency codes on rate cards and project budgets (low)
-Note: Machine-readable OpenAPI at /swagger-api-v3.yaml enumerates 26 resources; PostHog covers 20. /project-templates was excluded as config.
+Note: Machine-readable OpenAPI at /swagger-api-v3.yaml enumerates 26 resources; PostHog covers 24. /project-templates was excluded as config.
## Flowlu — **thin**
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/float_app/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/float_app/canonical_descriptions.py
index c70f6f30a6e6..c2bb2c617665 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/float_app/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/float_app/canonical_descriptions.py
@@ -82,6 +82,23 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"modified": "Time at which the project was last modified.",
},
},
+ "project_stages": {
+ "description": "A stage a project can sit in, pairing a workspace-defined label with the underlying project status.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier for the project stage.",
+ "name": "The stage's name, unique across all stages.",
+ "description": "A description of the project stage.",
+ "project_status": "The project status behind the stage: 0 = draft, 1 = tentative, 2 = confirmed, 3 = completed, 4 = canceled.",
+ "active": "Whether the stage is active (1) or archived (0).",
+ "sort_order": "The stage's position in the display order.",
+ "color": "Hex color for the stage; falls back to the project status default when unset.",
+ "created": "Time at which the stage was created.",
+ "modified": "Time at which the stage was last modified.",
+ "created_by": "Account id of the person who created the stage.",
+ "modified_by": "Account id of the person who last modified the stage.",
+ },
+ },
"phases": {
"description": "A phase within a project, bounding a date range with its own budget and rate.",
"docs_url": _DOCS_URL,
@@ -117,6 +134,26 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"description": "A named task defined on a project (the reusable task names allocations can use).",
"docs_url": _DOCS_URL,
},
+ "project_expenses": {
+ "description": "A non-labor cost booked against a project, the other half of project margin alongside logged time.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier for the project expense.",
+ "name": "The expense's name, unique within its project.",
+ "date": "The date of the expense.",
+ "cost": "The cost of the expense, as a decimal string.",
+ "project_id": "The project the expense belongs to.",
+ "phase_id": "The phase the expense belongs to, if any.",
+ "billable": "Whether the expense is billable (1) or not (0).",
+ "markup": "The markup applied to a billable expense, as a decimal string.",
+ "markup_type": "How the markup is applied: 0 = percentage, 1 = fixed amount.",
+ "quantity": "The quantity of this expense.",
+ "created": "Time at which the expense was created.",
+ "modified": "Time at which the expense was last modified.",
+ "created_by": "Account id of the person who created the expense.",
+ "modified_by": "Account id of the person who last modified the expense.",
+ },
+ },
"milestones": {
"description": "A milestone marking a key date on a project.",
"docs_url": _DOCS_URL,
@@ -200,6 +237,16 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"end_date": "The holiday's end date.",
},
},
+ "public_holidays": {
+ "description": "A public holiday for a region, distinct from the workspace's own team holidays. Holidays reduce a person's capacity.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Identifier for the holiday within its region.",
+ "name": "The name of the holiday.",
+ "region": "Id of the region the holiday belongs to.",
+ "dates": "The dates the holiday falls on, as YYYY-MM-DD strings.",
+ },
+ },
"rate_cards": {
"description": "A rate card defining bill rates by role, applied to projects to turn scheduled hours into billable value.",
"docs_url": _DOCS_URL,
@@ -221,6 +268,26 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"fx_rate": "The exchange rate from the source currency to the target currency.",
},
},
+ "reports_people": {
+ "description": "Float's per-person utilization report, aggregated over one calendar month. One row per person per month.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "start_date": "First day of the month the figures cover.",
+ "end_date": "Last day of the month the figures cover.",
+ "people_id": "The person the figures are for.",
+ "name": "The person's name.",
+ "department_id": "The department the person belongs to.",
+ "department": "The name of that department.",
+ "people_type_id": "Employment type: 1 = employee, 2 = contractor, 3 = placeholder, 4 = role placeholder.",
+ "capacity": "Work hours available in the month, after time off and holidays.",
+ "timeoff": "Time off hours scheduled in the month.",
+ "scheduled": "Allocated hours in the month (billable plus non-billable).",
+ "billable": "Billable allocated hours in the month.",
+ "nonBillable": "Non-billable allocated hours in the month.",
+ "overtime": "Overtime hours allocated in the month.",
+ "unscheduled": "Unscheduled hours in the month (capacity plus overtime, less scheduled).",
+ },
+ },
"deleted_tasks": {
"description": "Tombstone log of deleted allocations (tasks), for reconciling deletions since a cursor.",
"docs_url": _DOCS_URL,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/float_app/float_app.posthog.com.md b/products/warehouse_sources/backend/temporal/data_imports/sources/float_app/float_app.posthog.com.md
index 249d2fa9e57b..e790e509dbae 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/float_app/float_app.posthog.com.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/float_app/float_app.posthog.com.md
@@ -15,10 +15,10 @@ import AlphaRelease from "../\_snippets/alpha-release.mdx"
<AlphaRelease />
[Float](https://www.float.com/) is a resource-management and team-scheduling platform for capacity
-planning. This source syncs your people, accounts, clients, departments, projects, phases,
-allocations, milestones, logged time, time off, holidays, rate cards, and currencies into the
-PostHog data warehouse so you can join scheduling and capacity data with your product and revenue
-data.
+planning. This source syncs your people, accounts, clients, departments, projects, project stages,
+phases, allocations, milestones, project expenses, logged time, time off, holidays, public holidays,
+rate cards, currencies, and Float's per-person utilization report into the PostHog data warehouse so
+you can join scheduling and capacity data with your product and revenue data.
## Prerequisites
@@ -44,6 +44,12 @@ modified-since filter on its core resources, so there is no reliable incremental
against. The Delete Log tables (`deleted_tasks`, `deleted_timeoffs`, `deleted_logged_time`) are
tombstone logs for reconciling deletions and are **not** selected by default.
+`reports_people` is Float's utilization report rather than a plain list endpoint: it takes a date
+range and returns one aggregate row per person. PostHog requests it one calendar month at a time
+over the last 12 months, so the table holds one row per person per month. `public_holidays` covers
+the 3 years before and the year after the current one, because Float otherwise returns the current
+year alone.
+
## Configuration
<SourceParameters />
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/float_app/float_app.py b/products/warehouse_sources/backend/temporal/data_imports/sources/float_app/float_app.py
index cf83bc0b2edc..b362b096cd5f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/float_app/float_app.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/float_app/float_app.py
@@ -1,14 +1,18 @@
-import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime, timedelta
from typing import Any, Optional
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.paginators import BasePaginator
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import 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
@@ -16,20 +20,27 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.float_app.
DELETE_LOG_LIMIT,
FLOAT_ENDPOINTS,
PER_PAGE,
+ PUBLIC_HOLIDAY_YEARS_AHEAD,
+ PUBLIC_HOLIDAY_YEARS_BACK,
+ REPORT_LOOKBACK_MONTHS,
+ FloatEndpointConfig,
)
FLOAT_BASE_URL = "https://api.float.com/v3"
+REQUEST_TIMEOUT_SECONDS = 60
# Float rejects requests without a User-Agent that identifies the app and a contact email. This is a
# static integration identifier, not user data, so it's hardcoded rather than surfaced as a form field.
USER_AGENT = "PostHog Data Warehouse ([email protected])"
+@frozen
class FloatAppResumeConfig:
# Page-number endpoints resume from `next_page` (1-indexed); Delete Log endpoints resume from the
- # opaque `next_cursor`. Only one is set per endpoint. None means "start from the beginning".
+ # opaque `next_cursor`; report endpoints resume from the first day of the next unfetched month.
+ # Only one is set per endpoint. None means "start from the beginning".
next_page: int | None = None
next_cursor: str | None = None
+ next_window_start: str | None = None
def _non_auth_headers() -> dict[str, str]:
@@ -150,6 +161,90 @@ class FloatCursorPaginator(BasePaginator):
self._has_next_page = True
+def _auth_headers(api_key: str) -> dict[str, str]:
+ return {"Authorization": f"Bearer {api_key}", **_non_auth_headers()}
+
+
+def _public_holiday_window(today: date) -> dict[str, Any]:
+ start = date(today.year - PUBLIC_HOLIDAY_YEARS_BACK, 1, 1)
+ end = date(today.year + PUBLIC_HOLIDAY_YEARS_AHEAD, 12, 31)
+ return {"start_date": start.isoformat(), "end_date": end.isoformat()}
+
+
+@frozen
+class ReportWindow:
+ start: str
+ end: str
+
+
+def _month_windows(today: date, month_count: int) -> list[ReportWindow]:
+ """The latest `month_count` calendar months, including this month, oldest first."""
+ month_index = today.year * 12 + (today.month - 1)
+ windows: list[ReportWindow] = []
+ for offset in range(max(month_count - 1, 0), -1, -1):
+ year, month = divmod(month_index - offset, 12)
+ start = date(year, month + 1, 1)
+ next_year, next_month = divmod(month_index - offset + 1, 12)
+ end = date(next_year, next_month + 1, 1) - timedelta(days=1)
+ windows.append(ReportWindow(start=start.isoformat(), end=end.isoformat()))
+ return windows
+
+
+def _report_window_pages(
+ api_key: str,
+ config: FloatEndpointConfig,
+ resumable_source_manager: ResumableSourceManager[FloatAppResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ """Walk an unpaginated report endpoint one calendar month at a time.
+
+ Float's report endpoints take a required `start_date`/`end_date`, return the aggregate over that
+ window under a single envelope key, and expose no pagination. Each window is one request, so the
+ resume cursor is the next month still to fetch.
+ """
+ windows = _month_windows(datetime.now(UTC).date(), REPORT_LOOKBACK_MONTHS)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume is not None and resume.next_window_start is not None:
+ windows = [window for window in windows if window.start >= resume.next_window_start]
+
+ # The envelope key matches the last path segment, e.g. `/reports/people` -> {"people": [...]}.
+ envelope_key = config.path.rsplit("/", 1)[-1]
+ session = make_tracked_session(redact_values=(api_key,))
+ headers = _auth_headers(api_key)
+
+ for index, window in enumerate(windows):
+ response = session.get(
+ f"{FLOAT_BASE_URL}{config.path}",
+ headers=headers,
+ params={"start_date": window.start, "end_date": window.end},
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+ response.raise_for_status()
+ payload = response.json()
+ rows = payload.get(envelope_key) if isinstance(payload, dict) else None
+ # A month with no people is a valid empty list. A missing or non-list envelope is a changed
+ # response shape, and this table is full refresh, so treating it as empty drops the month.
+ if not isinstance(rows, list):
+ raise ValueError(f"Float returned no `{envelope_key}` list for {config.path} {window.start}")
+
+ # Stamp the window on every row: the figures are an aggregate over it, so without these the
+ # months are indistinguishable and every row collides on the primary key.
+ for row in rows:
+ row["start_date"] = window.start
+ row["end_date"] = window.end
+
+ if rows:
+ yield rows
+
+ remaining = windows[index + 1 :]
+ if remaining:
+ resumable_source_manager.save_state(FloatAppResumeConfig(next_window_start=remaining[0].start))
+ else:
+ # A retry after the last window would otherwise resume from the stale cursor and skip
+ # every earlier month.
+ resumable_source_manager.clear_state()
+
+
def float_app_source(
api_key: str,
endpoint: str,
@@ -160,12 +255,32 @@ def float_app_source(
) -> SourceResponse:
config = FLOAT_ENDPOINTS[endpoint]
+ if config.pagination == "report_window":
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: _report_window_pages(api_key, config, resumable_source_manager),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime",
+ partition_format="month",
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
+
paginator: BasePaginator
if config.pagination == "cursor":
paginator = FloatCursorPaginator(limit=DELETE_LOG_LIMIT)
else:
paginator = FloatPagePaginator(per_page=PER_PAGE)
+ endpoint_config: Endpoint = {
+ "path": config.path,
+ # Float list endpoints return a bare JSON array; the whole body is the row list.
+ "data_selector": None,
+ }
+ if config.date_window:
+ endpoint_config["params"] = _public_holiday_window(datetime.now(UTC).date())
+
rest_config: RESTAPIConfig = {
"client": {
"base_url": FLOAT_BASE_URL,
@@ -176,11 +291,7 @@ def float_app_source(
"resources": [
{
"name": endpoint,
- "endpoint": {
- "path": config.path,
- # Float list endpoints return a bare JSON array; the whole body is the row list.
- "data_selector": None,
- },
+ "endpoint": endpoint_config,
}
],
}
@@ -236,5 +347,5 @@ def validate_credentials(api_key: str) -> tuple[bool, int | None]:
return validate_via_probe(
lambda: make_tracked_session(redact_values=(api_key,)),
f"{FLOAT_BASE_URL}/accounts?per-page=1",
- headers={"Authorization": f"Bearer {api_key}", **_non_auth_headers()},
+ headers=_auth_headers(api_key),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/float_app/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/float_app/settings.py
index 8cb4146bff18..f4a702c54293 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/float_app/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/float_app/settings.py
@@ -1,6 +1,7 @@
-from dataclasses import dataclass
from typing import Literal
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.types import IncrementalField
# Float caps `per-page` at 200 (default 50). Always request the max to minimise round trips.
@@ -8,10 +9,21 @@ PER_PAGE = 200
# The Delete Log endpoints use cursor pagination and accept a `limit` of up to 500.
DELETE_LOG_LIMIT = 500
-PaginationMode = Literal["page", "cursor"]
+# `/public-holidays` defaults to the current year alone, which would hide the holidays behind any
+# historical logged time. `start_date`/`end_date` override that default, so span a fixed window
+# around today instead.
+PUBLIC_HOLIDAY_YEARS_BACK = 3
+PUBLIC_HOLIDAY_YEARS_AHEAD = 1
+
+# The report endpoints require a `start_date`/`end_date` and return the aggregate over it with no
+# pagination, so `/reports/people` is walked one calendar month at a time to give the table a
+# monthly grain instead of a single window whose meaning shifts every sync.
+REPORT_LOOKBACK_MONTHS = 12
+PaginationMode = Literal["page", "cursor", "report_window"]
-@dataclass
+
+@frozen
class FloatEndpointConfig:
name: str
# Path under the `/v3` base, e.g. "/people". Verified to exist against the live API (401 behind
@@ -25,9 +37,12 @@ class FloatEndpointConfig:
# Stable creation-time field to partition by. Only set where Float is known to return a `created`
# timestamp on every row — an absent partition column would fail the write. None disables partitioning.
partition_key: str | None = None
- # Core resources use page-number pagination (`page`/`per-page` + `X-Pagination-*` headers). Only the
- # Delete Log endpoints use cursor pagination (`cursor`/`limit` + `X-Pagination-Next-Cursor`).
+ # Core resources use page-number pagination (`page`/`per-page` + `X-Pagination-*` headers). The
+ # Delete Log endpoints use cursor pagination (`cursor`/`limit` + `X-Pagination-Next-Cursor`), and
+ # the report endpoints are unpaginated windows walked a month at a time.
pagination: PaginationMode = "page"
+ # Send an explicit `start_date`/`end_date` instead of accepting the endpoint's default range.
+ date_window: bool = False
should_sync_default: bool = True
@@ -43,9 +58,15 @@ FLOAT_ENDPOINTS: dict[str, FloatEndpointConfig] = {
"projects": FloatEndpointConfig(
name="projects", path="/projects", primary_keys=["project_id"], partition_key="created"
),
+ "project_stages": FloatEndpointConfig(
+ name="project_stages", path="/project-stages", primary_keys=["id"], partition_key="created"
+ ),
"phases": FloatEndpointConfig(name="phases", path="/phases", primary_keys=["phase_id"]),
"tasks": FloatEndpointConfig(name="tasks", path="/tasks", primary_keys=["task_id"], partition_key="created"),
"project_tasks": FloatEndpointConfig(name="project_tasks", path="/project-tasks", primary_keys=["task_meta_id"]),
+ "project_expenses": FloatEndpointConfig(
+ name="project_expenses", path="/project-expenses", primary_keys=["id"], partition_key="created"
+ ),
"milestones": FloatEndpointConfig(name="milestones", path="/milestones", primary_keys=["milestone_id"]),
"timeoffs": FloatEndpointConfig(
name="timeoffs", path="/timeoffs", primary_keys=["timeoff_id"], partition_key="created"
@@ -57,8 +78,23 @@ FLOAT_ENDPOINTS: dict[str, FloatEndpointConfig] = {
"status": FloatEndpointConfig(name="status", path="/status", primary_keys=["status_id"]),
"roles": FloatEndpointConfig(name="roles", path="/roles", primary_keys=["id"]),
"holidays": FloatEndpointConfig(name="holidays", path="/holidays", primary_keys=["holiday_id"]),
+ "public_holidays": FloatEndpointConfig(
+ name="public_holidays",
+ path="/public-holidays",
+ # Float documents `id` as the holiday's id *per region*, so it is only unique within a region.
+ primary_keys=["id", "region"],
+ date_window=True,
+ ),
"rate_cards": FloatEndpointConfig(name="rate_cards", path="/rate-cards", primary_keys=["rate_card_id"]),
"currencies": FloatEndpointConfig(name="currencies", path="/currencies", primary_keys=["currency_id"]),
+ "reports_people": FloatEndpointConfig(
+ name="reports_people",
+ path="/reports/people",
+ # One row per person per report window, so `people_id` alone repeats across windows.
+ primary_keys=["people_id", "start_date"],
+ partition_key="start_date",
+ pagination="report_window",
+ ),
# Delete Log endpoints — cursor pagination, append-only tombstones. Niche, so off by default.
"deleted_tasks": FloatEndpointConfig(
name="deleted_tasks",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/float_app/tests/test_float_app.py b/products/warehouse_sources/backend/temporal/data_imports/sources/float_app/tests/test_float_app.py
index e676a6cc73ca..3ca03b223b5a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/float_app/tests/test_float_app.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/float_app/tests/test_float_app.py
@@ -1,6 +1,8 @@
import json
+from datetime import date
from typing import Any
+import pytest
from unittest import mock
from requests import Response
@@ -8,10 +10,18 @@ from requests import Response
from products.warehouse_sources.backend.temporal.data_imports.sources.float_app.float_app import (
DELETE_LOG_LIMIT,
PER_PAGE,
+ REQUEST_TIMEOUT_SECONDS,
FloatAppResumeConfig,
+ ReportWindow,
+ _month_windows,
+ _public_holiday_window,
float_app_source,
validate_credentials,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.float_app.settings import (
+ PUBLIC_HOLIDAY_YEARS_AHEAD,
+ PUBLIC_HOLIDAY_YEARS_BACK,
+)
# 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"
@@ -30,6 +40,13 @@ def _response(items: list[dict[str, Any]], headers: dict[str, str] | None = None
return resp
+def _response_body(body: dict[str, Any] | list[Any]) -> Response:
+ resp = Response()
+ resp.status_code = 200
+ resp._content = json.dumps(body).encode()
+ return resp
+
+
def _make_manager(resume_state: FloatAppResumeConfig | None = None) -> mock.MagicMock:
manager = mock.MagicMock()
manager.can_resume.return_value = resume_state is not None
@@ -229,3 +246,161 @@ class TestValidateCredentials:
def test_transport_error_returns_none_status(self, mock_session) -> None:
mock_session.return_value.get.side_effect = Exception("connection reset")
assert validate_credentials("tok") == (False, None)
+
+
+class TestDateWindowEndpoints:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_public_holidays_sends_a_multi_year_window(self, MockSession) -> None:
+ # Without start_date/end_date Float returns the current year only, which would hide the
+ # holidays behind historical logged time.
+ session = MockSession.return_value
+ params = _wire(session, [_response([{"id": 1, "region": 2}], {"X-Pagination-Pages": "1"})])
+
+ _rows(_source("public_holidays", _make_manager()))
+
+ this_year = date.today().year
+ assert params[0]["start_date"] == f"{this_year - PUBLIC_HOLIDAY_YEARS_BACK}-01-01"
+ assert params[0]["end_date"] == f"{this_year + PUBLIC_HOLIDAY_YEARS_AHEAD}-12-31"
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_paged_endpoints_send_no_date_window(self, MockSession) -> None:
+ session = MockSession.return_value
+ params = _wire(session, [_response([{"id": 1}], {"X-Pagination-Pages": "1"})])
+
+ _rows(_source("project_stages", _make_manager()))
+
+ assert "start_date" not in params[0]
+
+
+class TestPublicHolidayWindow:
+ def test_spans_whole_calendar_years_around_today(self) -> None:
+ assert _public_holiday_window(date(2026, 6, 15)) == {
+ "start_date": f"{2026 - PUBLIC_HOLIDAY_YEARS_BACK}-01-01",
+ "end_date": f"{2026 + PUBLIC_HOLIDAY_YEARS_AHEAD}-12-31",
+ }
+
+
+class TestMonthWindows:
+ def test_walks_whole_months_oldest_first_ending_with_this_month(self) -> None:
+ assert _month_windows(date(2026, 3, 17), 2) == [
+ ReportWindow(start="2026-02-01", end="2026-02-28"),
+ ReportWindow(start="2026-03-01", end="2026-03-31"),
+ ]
+
+ def test_crosses_the_year_boundary(self) -> None:
+ assert _month_windows(date(2026, 1, 5), 2) == [
+ ReportWindow(start="2025-12-01", end="2025-12-31"),
+ ReportWindow(start="2026-01-01", end="2026-01-31"),
+ ]
+
+ def test_handles_a_leap_february(self) -> None:
+ assert _month_windows(date(2028, 2, 9), 0) == [ReportWindow(start="2028-02-01", end="2028-02-29")]
+
+
+class TestReportWindows:
+ WINDOWS = [
+ ReportWindow(start="2026-01-01", end="2026-01-31"),
+ ReportWindow(start="2026-02-01", end="2026-02-28"),
+ ]
+ MONTH_WINDOWS_PATCH = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.float_app.float_app._month_windows"
+ )
+
+ def _wire_reports(
+ self, MockSession: mock.MagicMock, bodies: list[dict[str, Any] | list[Any]]
+ ) -> list[dict[str, Any]]:
+ session = MockSession.return_value
+ captured: list[dict[str, Any]] = []
+
+ def _get(
+ url: str,
+ headers: dict[str, str] | None = None,
+ params: dict[str, str] | None = None,
+ timeout: float | None = None,
+ ) -> Response:
+ captured.append(dict(params or {}))
+ assert timeout == REQUEST_TIMEOUT_SECONDS
+ return _response_body(bodies[len(captured) - 1])
+
+ session.get.side_effect = _get
+ return captured
+
+ @mock.patch(FLOAT_SESSION_PATCH)
+ @mock.patch(MONTH_WINDOWS_PATCH, return_value=WINDOWS)
+ def test_requests_each_month_and_stamps_the_window_on_every_row(self, _windows, MockSession) -> None:
+ params = self._wire_reports(
+ MockSession,
+ [{"people": [{"people_id": 1, "billable": 10}]}, {"people": [{"people_id": 1, "billable": 20}]}],
+ )
+
+ rows = _rows(_source("reports_people", _make_manager()))
+
+ assert [(p["start_date"], p["end_date"]) for p in params] == [(w.start, w.end) for w in self.WINDOWS]
+ # Without the stamp both months carry people_id=1 and collide on the primary key.
+ assert [(r["people_id"], r["start_date"], r["billable"]) for r in rows] == [
+ (1, "2026-01-01", 10),
+ (1, "2026-02-01", 20),
+ ]
+
+ @mock.patch(FLOAT_SESSION_PATCH)
+ @mock.patch(MONTH_WINDOWS_PATCH, return_value=WINDOWS)
+ def test_saves_the_next_month_after_each_yield_except_the_last(self, _windows, MockSession) -> None:
+ self._wire_reports(MockSession, [{"people": [{"people_id": 1}]}, {"people": [{"people_id": 2}]}])
+
+ manager = _make_manager()
+ _rows(_source("reports_people", manager))
+
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [FloatAppResumeConfig(next_window_start="2026-02-01")]
+
+ @mock.patch(FLOAT_SESSION_PATCH)
+ @mock.patch(MONTH_WINDOWS_PATCH, return_value=WINDOWS)
+ def test_resumes_from_the_saved_month(self, _windows, MockSession) -> None:
+ params = self._wire_reports(MockSession, [{"people": [{"people_id": 2}]}])
+
+ rows = _rows(_source("reports_people", _make_manager(FloatAppResumeConfig(next_window_start="2026-02-01"))))
+
+ assert [p["start_date"] for p in params] == ["2026-02-01"]
+ assert [r["people_id"] for r in rows] == [2]
+
+ @mock.patch(FLOAT_SESSION_PATCH)
+ @mock.patch(MONTH_WINDOWS_PATCH, return_value=WINDOWS)
+ def test_a_month_with_no_people_yields_nothing_and_still_advances(self, _windows, MockSession) -> None:
+ self._wire_reports(MockSession, [{"people": []}, {"people": [{"people_id": 2}]}])
+
+ manager = _make_manager()
+ rows = _rows(_source("reports_people", manager))
+
+ assert [r["people_id"] for r in rows] == [2]
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [FloatAppResumeConfig(next_window_start="2026-02-01")]
+
+ @mock.patch(FLOAT_SESSION_PATCH)
+ @mock.patch(MONTH_WINDOWS_PATCH, return_value=WINDOWS)
+ def test_clears_the_cursor_after_the_last_window(
+ self, _windows: mock.MagicMock, MockSession: mock.MagicMock
+ ) -> None:
+ # A retry after the source finished would otherwise resume from the stale cursor and skip
+ # every earlier month.
+ self._wire_reports(MockSession, [{"people": [{"people_id": 1}]}, {"people": [{"people_id": 2}]}])
+
+ manager = _make_manager()
+ _rows(_source("reports_people", manager))
+
+ manager.clear_state.assert_called_once()
+
+ @pytest.mark.parametrize("body", [{}, {"people": None}, {"people": {"1": {}}}, []])
+ @mock.patch(FLOAT_SESSION_PATCH)
+ @mock.patch(MONTH_WINDOWS_PATCH, return_value=WINDOWS)
+ def test_a_changed_envelope_fails_loud(
+ self,
+ _windows: mock.MagicMock,
+ MockSession: mock.MagicMock,
+ body: dict[str, Any] | list[Any],
+ ) -> None:
+ # Silently reading a changed shape as an empty month would drop that month from a table
+ # that is fully replaced every sync.
+ self._wire_reports(MockSession, [body, body])
+
+ with pytest.raises(ValueError, match="people"):
+ _rows(_source("reports_people", _make_manager()))