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 firstpromoter report and referral link tables (#120222)

Tom Owers523ab0fde03e
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
index 5919573152b3..86754a7e23a3 100644
--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
@@ -543,8 +543,6 @@
1 products/warehouse_sources/backend/temporal/data_imports/sources/firehydrant/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/fireworks_ai/fireworks_ai.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/fireworks_ai/settings.py
-1 products/warehouse_sources/backend/temporal/data_imports/sources/first_promoter/first_promoter.py
-1 products/warehouse_sources/backend/temporal/data_imports/sources/first_promoter/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/fleetio/fleetio.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/fleetio/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/float_app/float_app.py
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 60e1e4f0846c..920f5cc62324 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
@@ -4738,11 +4738,11 @@ Today (6): `commissions`, `payouts`, `promo_codes`, `promoter_campaigns`, `promo
Diffed against: <https://docs.firstpromoter.com/llms.txt>
-- [ ] `Get reports for overview (GET /api/v2/company/reports/overview)` — measure affiliate clicks, conversion rates, earnings per click, and churn over time (high)
-- [ ] `Get reports for campaigns (GET /api/v2/company/reports/campaigns)` — compare campaign clicks, conversions, and revenue by period, beyond current promoter campaign snapshots (high)
-- [ ] `Get reports for traffic sources (GET /api/v2/company/reports/traffic_sources)` — compare referral channels by traffic, conversion rates, and attributed revenue (medium)
+- [x] `Get reports for overview (GET /api/v2/company/reports/overview)` — measure affiliate clicks, conversion rates, earnings per click, and churn over time (high)
+- [x] `Get reports for campaigns (GET /api/v2/company/reports/campaigns)` — compare campaign clicks, conversions, and revenue by period, beyond current promoter campaign snapshots (high)
+- [x] `Get reports for traffic sources (GET /api/v2/company/reports/traffic_sources)` — compare referral channels by traffic, conversion rates, and attributed revenue (medium)
- [ ] `Get reports for URLs (GET /api/v2/company/reports/urls)` — find landing pages that generate affiliate traffic and paying customers (medium)
-- [ ] `Get promoter referral links (GET /api/v2/company/promoters/{id}/referral_links)` — identify custom referral links and sub-IDs beyond the default campaign link (medium)
+- [x] `Get promoter referral links (GET /api/v2/company/promoters/{id}/referral_links)` — identify custom referral links and sub-IDs beyond the default campaign link (medium)
Note: Parsed the official documentation index and the embedded OpenAPI definitions on the V2 report and referral-link pages. Reports need date windows and metric selection; referral links need promoter fan-out. Campaign metadata already appears inside promoter_campaigns, so a separate campaign lookup is not a gap. Excluded tracking writes, batch progress, and payout summaries that repeat synced data.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/first_promoter/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/first_promoter/canonical_descriptions.py
index 5d7ab4917cdc..393c1f81b7f4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/first_promoter/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/first_promoter/canonical_descriptions.py
@@ -2,6 +2,33 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.can
CanonicalDescriptions,
)
+_METRIC_COLUMNS = {
+ "period": "Month the metrics cover.",
+ "clicks_count": "Referral link clicks in the period.",
+ "referrals_count": "Referrals (leads and signups) tracked in the period.",
+ "customers_count": "Referrals that became paying customers in the period.",
+ "sales_count": "Sales tracked in the period.",
+ "refunds_count": "Refunds tracked in the period.",
+ "cancelled_customers_count": "Referred customers who cancelled in the period.",
+ "revenue_amount": "Revenue from referred customers in the period.",
+ "promoter_earnings_amount": "Commissions promoters earned in the period.",
+ "referrals_to_customers_cr": "Share of referrals that converted to customers.",
+ "clicks_to_customers_cr": "Share of clicks that converted to customers.",
+ "clicks_to_referrals_cr": "Share of clicks that converted to referrals.",
+}
+
+_PROGRAM_METRIC_COLUMNS = {
+ **_METRIC_COLUMNS,
+ "active_customers": "Referred customers active in the period.",
+ "monthly_churn": "Share of referred customers who churned in the period.",
+ "net_revenue_amount": "Revenue from referred customers in the period, net of refunds.",
+ "non_link_customers": "Customers attributed without a referral link click, for example through a coupon.",
+ "3m_epc": "Earnings per click over the trailing three months.",
+ "6m_epc": "Earnings per click over the trailing six months.",
+ "promoter_paid_amount": "Commissions paid out to promoters in the period.",
+ "signups_count": "Referred signups in the period.",
+}
+
CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"commissions": {
"description": "Commissions earned by promoters for the sales and events they referred.",
@@ -144,4 +171,37 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"created_at": "When the referral was first tracked.",
},
},
+ "promoter_referral_links": {
+ "description": "Referral links of each promoter: the default link plus any campaign or custom links.",
+ "docs_url": "https://docs.firstpromoter.com/api-reference-v2/api-admin/promoters/get-promoter-referral-links",
+ "columns": {
+ "promoter_id": "Identifier of the promoter the link belongs to.",
+ "id": "Identifier of the link, when it has one.",
+ "name": "Display name of the link.",
+ "url": "The referral link URL.",
+ "is_default": "Whether this is the promoter's default link.",
+ "source": "Where the link comes from: campaign or promoter.",
+ "sub_id": "Sub-ID appended to the link, for custom links.",
+ "campaign": "Campaign the link belongs to, with its id and name.",
+ },
+ },
+ "reports_overview": {
+ "description": "Program-wide affiliate metrics for each month.",
+ "docs_url": "https://docs.firstpromoter.com/api-reference-v2/api-admin/reports/get-reports-for-overview",
+ "columns": _PROGRAM_METRIC_COLUMNS,
+ },
+ "reports_campaigns": {
+ "description": "Affiliate metrics for each campaign and month.",
+ "docs_url": "https://docs.firstpromoter.com/api-reference-v2/api-admin/reports/get-reports-for-campaigns",
+ "columns": {
+ **_PROGRAM_METRIC_COLUMNS,
+ "campaign_id": "Identifier of the campaign.",
+ "campaign_name": "Name of the campaign.",
+ },
+ },
+ "reports_traffic_sources": {
+ "description": "Affiliate metrics for each referral traffic source and month.",
+ "docs_url": "https://docs.firstpromoter.com/api-reference-v2/api-admin/reports/get-reports-for-traffic-sources",
+ "columns": {**_METRIC_COLUMNS, "source": "Traffic source the clicks came from."},
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/first_promoter/first_promoter.py b/products/warehouse_sources/backend/temporal/data_imports/sources/first_promoter/first_promoter.py
index 3f29104bb3c7..0a1ba35ce378 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/first_promoter/first_promoter.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/first_promoter/first_promoter.py
@@ -1,6 +1,7 @@
import logging
import dataclasses
from collections.abc import Callable, Iterable
+from datetime import UTC, datetime
from functools import partial
from typing import Any, Optional
@@ -14,8 +15,12 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
RESTAPIConfig,
rest_api_resource,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ build_dependent_resource,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
PageNumberPaginator,
+ SinglePagePaginator,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
ClientConfig,
@@ -28,14 +33,17 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typ
from products.warehouse_sources.backend.temporal.data_imports.sources.first_promoter.settings import (
DEFAULT_PAGE_SIZE,
FIRST_PROMOTER_ENDPOINTS,
+ REPORTS_GROUP_BY,
+ REPORTS_START_DATE,
FirstPromoterEndpointConfig,
+ FirstPromoterReportConfig,
base_url,
)
logger = logging.getLogger(__name__)
[email protected](frozen=True)
class FirstPromoterResumeConfig:
page: int
@@ -132,6 +140,46 @@ def _drop_fields(row: dict[str, Any], fields: tuple[str, ...]) -> dict[str, Any]
return row
+def _report_metrics(bucket: dict[str, Any]) -> dict[str, Any]:
+ return {"period": bucket.get("period"), **(bucket.get("data") or {})}
+
+
+def _report_dimension(row: dict[str, Any], dimension: str) -> dict[str, Any]:
+ value = row.get(dimension)
+ if isinstance(value, dict):
+ return {f"{dimension}_id": value.get("id"), f"{dimension}_name": value.get("name")}
+ return {dimension: value}
+
+
+def _report_row_mapper(
+ report: FirstPromoterReportConfig,
+) -> Callable[[dict[str, Any]], dict[str, Any] | list[dict[str, Any]]]:
+ """Shape report rows into one row per period, with the metrics as top-level columns.
+
+ The overview already returns one bucket per period. Grouped reports return one row per
+ dimension value, carrying whole-window totals in `data` and the per-period buckets in
+ `sub_data`; the totals are dropped since they're the sum of the buckets.
+ """
+ dimension = report.dimension
+ if dimension is None:
+ return _report_metrics
+
+ def _explode(row: dict[str, Any]) -> list[dict[str, Any]]:
+ identity = _report_dimension(row, dimension)
+ return [{**identity, **_report_metrics(bucket)} for bucket in row.get("sub_data") or []]
+
+ return _explode
+
+
+def _report_params(report: FirstPromoterReportConfig) -> dict[str, Any]:
+ return {
+ "columns[]": list(report.columns),
+ "group_by": REPORTS_GROUP_BY,
+ "start_date": REPORTS_START_DATE,
+ "end_date": datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ"),
+ }
+
+
def rest_api_client_config(api_key: str, account_id: str, api_version: str) -> ClientConfig:
return {
"base_url": base_url(api_version),
@@ -158,6 +206,22 @@ def get_resource(
) -> EndpointResource:
config = FIRST_PROMOTER_ENDPOINTS[endpoint]
+ if config.report is not None:
+ # Reports return the whole window in one response and document no `page` param.
+ return {
+ "name": config.name,
+ "table_name": config.name,
+ "write_disposition": "replace",
+ "endpoint": {
+ "path": config.path,
+ "params": _report_params(config.report),
+ "paginator": SinglePagePaginator(),
+ "data_selector_required": True,
+ },
+ "table_format": "delta",
+ "data_map": _report_row_mapper(config.report),
+ }
+
endpoint_config: Endpoint = {
"path": config.path,
"params": dict(config.extra_params),
@@ -193,6 +257,7 @@ def get_resource(
def _make_source_response(
endpoint_config: FirstPromoterEndpointConfig,
items_fn: Callable[[], Iterable[Any]],
+ supports_resume: bool = True,
) -> SourceResponse:
return SourceResponse(
name=endpoint_config.name,
@@ -205,9 +270,44 @@ def _make_source_response(
partition_mode="datetime" if endpoint_config.partition_key else None,
partition_format="month" if endpoint_config.partition_key else None,
partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,
+ supports_resume=supports_resume,
)
+def _dependent_source_response(
+ api_key: str,
+ account_id: str,
+ endpoint_config: FirstPromoterEndpointConfig,
+ team_id: int,
+ job_id: str,
+ api_version: str,
+) -> SourceResponse:
+ if endpoint_config.fanout is None:
+ raise ValueError(f"{endpoint_config.name} is not a fan-out endpoint")
+ parent_config = FIRST_PROMOTER_ENDPOINTS[endpoint_config.fanout.parent_name]
+ parent_endpoint_extra: Endpoint = {"paginator": FirstPromoterPaginator(parent_config.page_size)}
+ if parent_config.data_selector:
+ parent_endpoint_extra["data_selector"] = parent_config.data_selector
+
+ # Full refresh with no resume: the child has no server-side time filter, and the fan-out's
+ # resume state has a different shape from the page cursor the other endpoints save.
+ resource = build_dependent_resource(
+ endpoint_configs=FIRST_PROMOTER_ENDPOINTS,
+ child_endpoint=endpoint_config.name,
+ fanout=endpoint_config.fanout,
+ client_config=rest_api_client_config(api_key, account_id, api_version),
+ path_format_values={},
+ team_id=team_id,
+ job_id=job_id,
+ db_incremental_field_last_value=None,
+ # FirstPromoterPaginator sends `per_page` on the parent; the child takes no page params.
+ page_size_param=None,
+ parent_endpoint_extra=parent_endpoint_extra,
+ child_endpoint_extra={"paginator": SinglePagePaginator()},
+ )
+ return _make_source_response(endpoint_config, lambda: resource, supports_resume=False)
+
+
def first_promoter_source(
api_key: str,
account_id: str,
@@ -222,6 +322,9 @@ def first_promoter_source(
) -> SourceResponse:
endpoint_config = FIRST_PROMOTER_ENDPOINTS[endpoint]
+ if endpoint_config.fanout is not None:
+ return _dependent_source_response(api_key, account_id, endpoint_config, team_id, job_id, api_version)
+
config: RESTAPIConfig = {
"client": rest_api_client_config(api_key, account_id, api_version),
"resource_defaults": {},
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/first_promoter/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/first_promoter/settings.py
index 370fcdbee6e9..d54b1430539e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/first_promoter/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/first_promoter/settings.py
@@ -1,5 +1,9 @@
from dataclasses import dataclass, field
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ DependentEndpointConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ResponseAction
from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
from products.warehouse_sources.backend.types import IncrementalField
@@ -16,11 +20,68 @@ DEFAULT_PAGE_SIZE = 100
COMMISSIONS_INCREMENTAL_LOOKBACK_SECONDS = 30 * 24 * 60 * 60
+# Reports require an explicit window. Starting before FirstPromoter existed covers an account's whole
+# history; the months before its first activity just come back with zeroed metrics.
+REPORTS_START_DATE = "2014-01-01T00:00:00Z"
+# Monthly buckets keep a whole-history response small. The current month is partial and is
+# re-read by the next full refresh.
+REPORTS_GROUP_BY = "month"
+
+# Every metric the overview and campaign reports accept in `columns[]`.
+PROGRAM_REPORT_COLUMNS: tuple[str, ...] = (
+ "active_customers",
+ "monthly_churn",
+ "clicks_count",
+ "net_revenue_amount",
+ "revenue_amount",
+ "referrals_count",
+ "customers_count",
+ "sales_count",
+ "refunds_count",
+ "cancelled_customers_count",
+ "promoter_earnings_amount",
+ "non_link_customers",
+ "referrals_to_customers_cr",
+ "3m_epc",
+ "6m_epc",
+ "clicks_to_customers_cr",
+ "clicks_to_referrals_cr",
+ "promoter_paid_amount",
+ "signups_count",
+)
+
+# The traffic sources report accepts a smaller metric set than the overview and campaign reports.
+TRAFFIC_SOURCES_REPORT_COLUMNS: tuple[str, ...] = (
+ "clicks_count",
+ "revenue_amount",
+ "promoter_earnings_amount",
+ "referrals_count",
+ "customers_count",
+ "sales_count",
+ "refunds_count",
+ "cancelled_customers_count",
+ "referrals_to_customers_cr",
+ "clicks_to_customers_cr",
+ "clicks_to_referrals_cr",
+)
+
+# A promoter deleted between the /promoters listing and its child fetch must not fail the fan-out.
+_DELETED_PROMOTER_IGNORE: list[ResponseAction] = [{"status_code": 404, "action": "ignore"}]
+
+
def base_url(api_version: str) -> str:
return f"{FIRST_PROMOTER_HOST}/api/{api_version}/company"
-@dataclass
+@dataclass(frozen=True)
+class FirstPromoterReportConfig:
+ columns: tuple[str, ...]
+ # Top-level response field each row is grouped by (e.g. `campaign`), or None for the
+ # program-wide overview. Grouped reports nest their per-period buckets under `sub_data`.
+ dimension: str | None = None
+
+
+@dataclass(frozen=True)
class FirstPromoterEndpointConfig:
name: str
path: str
@@ -42,6 +103,9 @@ class FirstPromoterEndpointConfig:
# access could read one.
redact_fields: tuple[str, ...] = ()
description: str | None = None
+ page_size: int = DEFAULT_PAGE_SIZE
+ report: FirstPromoterReportConfig | None = None
+ fanout: DependentEndpointConfig | None = None
FIRST_PROMOTER_ENDPOINTS: dict[str, FirstPromoterEndpointConfig] = {
@@ -104,6 +168,43 @@ FIRST_PROMOTER_ENDPOINTS: dict[str, FirstPromoterEndpointConfig] = {
# long as the customer is around.
description="Leads and customers referred by promoters, with their state and attribution.",
),
+ "promoter_referral_links": FirstPromoterEndpointConfig(
+ name="promoter_referral_links",
+ path="/promoters/{promoter_id}/referral_links",
+ # A link's own `id` is nullable, so the url identifies it within its promoter.
+ primary_key=["promoter_id", "url"],
+ fanout=DependentEndpointConfig(
+ parent_name="promoters",
+ resolve_param="promoter_id",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "promoter_id"},
+ parent_params={"sorting[joined_at]": "asc"},
+ child_response_actions=_DELETED_PROMOTER_IGNORE,
+ ),
+ description="Every referral link of each promoter: the default link plus campaign and custom links with their sub-IDs.",
+ ),
+ "reports_overview": FirstPromoterEndpointConfig(
+ name="reports_overview",
+ path="/reports/overview",
+ primary_key=["period"],
+ report=FirstPromoterReportConfig(columns=PROGRAM_REPORT_COLUMNS),
+ description="Program-wide monthly metrics: clicks, referrals, customers, revenue, earnings per click and churn.",
+ ),
+ "reports_campaigns": FirstPromoterEndpointConfig(
+ name="reports_campaigns",
+ path="/reports/campaigns",
+ primary_key=["campaign_id", "period"],
+ report=FirstPromoterReportConfig(columns=PROGRAM_REPORT_COLUMNS, dimension="campaign"),
+ description="Monthly clicks, conversions and revenue per campaign.",
+ ),
+ "reports_traffic_sources": FirstPromoterEndpointConfig(
+ name="reports_traffic_sources",
+ path="/reports/traffic_sources",
+ primary_key=["source", "period"],
+ report=FirstPromoterReportConfig(columns=TRAFFIC_SOURCES_REPORT_COLUMNS, dimension="source"),
+ description="Monthly traffic, conversion rates and attributed revenue per referral traffic source.",
+ ),
}
ENDPOINTS = tuple(FIRST_PROMOTER_ENDPOINTS)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/first_promoter/tests/test_first_promoter.py b/products/warehouse_sources/backend/temporal/data_imports/sources/first_promoter/tests/test_first_promoter.py
index 23b8eac09383..1287f33f8f8d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/first_promoter/tests/test_first_promoter.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/first_promoter/tests/test_first_promoter.py
@@ -9,6 +9,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.tes
ScriptedResponse,
SourceDriver,
always,
+ route,
scripted_network,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.first_promoter.first_promoter import (
@@ -19,7 +20,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.first_prom
get_resource,
validate_credentials,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.first_promoter.settings import DEFAULT_PAGE_SIZE
+from products.warehouse_sources.backend.temporal.data_imports.sources.first_promoter.settings import (
+ DEFAULT_PAGE_SIZE,
+ PROGRAM_REPORT_COLUMNS,
+ TRAFFIC_SOURCES_REPORT_COLUMNS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.first_promoter.source import FirstPromoterSource
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.firstpromoter import (
FirstPromoterSourceConfig,
@@ -234,3 +239,108 @@ class TestFirstPromoterTransport:
assert response.partition_keys == expected_partition_keys
# Partitioning on a field that never changes once set; never on a mutating one.
assert response.partition_mode == ("datetime" if expected_partition_keys else None)
+
+ @parameterized.expand(
+ [
+ (
+ "reports_overview",
+ PROGRAM_REPORT_COLUMNS,
+ [
+ {"period": "2026-01", "id": "2026-01", "data": {"clicks_count": 10, "3m_epc": 1.5}},
+ {"period": "2026-02", "id": "2026-02", "data": {"clicks_count": 4, "3m_epc": 0.5}},
+ ],
+ [
+ {"period": "2026-01", "clicks_count": 10, "3m_epc": 1.5},
+ {"period": "2026-02", "clicks_count": 4, "3m_epc": 0.5},
+ ],
+ ),
+ (
+ # Grouped reports nest the per-period buckets under each campaign; the whole-window
+ # totals in `data` must not become a row of their own.
+ "reports_campaigns",
+ PROGRAM_REPORT_COLUMNS,
+ [
+ {
+ "campaign": {"id": 7, "name": "Partners", "color": "#fff"},
+ "id": 7,
+ "data": {"clicks_count": 14},
+ "sub_data": [
+ {"period": "2026-01", "id": "2026-01", "data": {"clicks_count": 10}},
+ {"period": "2026-02", "id": "2026-02", "data": {"clicks_count": 4}},
+ ],
+ },
+ {"campaign": {"id": 8, "name": "Empty"}, "id": 8, "data": {}, "sub_data": []},
+ ],
+ [
+ {"campaign_id": 7, "campaign_name": "Partners", "period": "2026-01", "clicks_count": 10},
+ {"campaign_id": 7, "campaign_name": "Partners", "period": "2026-02", "clicks_count": 4},
+ ],
+ ),
+ (
+ "reports_traffic_sources",
+ TRAFFIC_SOURCES_REPORT_COLUMNS,
+ [
+ {
+ "source": "youtube.com",
+ "id": "youtube.com",
+ "data": {"clicks_count": 3},
+ "sub_data": [{"period": "2026-01", "id": "2026-01", "data": {"clicks_count": 3}}],
+ }
+ ],
+ [{"source": "youtube.com", "period": "2026-01", "clicks_count": 3}],
+ ),
+ ]
+ )
+ def test_report_is_one_windowed_request_flattened_to_one_row_per_period(
+ self,
+ endpoint: str,
+ expected_columns: tuple[str, ...],
+ payload: list[dict[str, Any]],
+ expected_rows: list[dict[str, Any]],
+ ) -> None:
+ result = _driver().run(endpoint, [ScriptedResponse(json=payload)])
+
+ assert result.raised is None
+ assert result.rows == expected_rows
+ assert len(result.requests) == 1
+ query = result.queries[0]
+ assert query["columns[]"] == expected_columns
+ assert query["group_by"] == ("month",)
+ assert query["start_date"] == ("2014-01-01T00:00:00Z",)
+ assert "end_date" in query
+ assert "page" not in query
+
+ def test_referral_links_fan_out_over_promoters(self) -> None:
+ result = _driver().run(
+ "promoter_referral_links",
+ route(
+ {
+ "/promoters": [
+ ScriptedResponse(
+ json={"data": [{"id": 1, "password_setup_url": "https://fp/setup"}, {"id": 2}]}
+ )
+ ],
+ "/promoters/1/referral_links": [
+ ScriptedResponse(
+ json=[
+ {"id": None, "url": "https://example.com/?fpr=a", "is_default": True},
+ {"id": "5", "url": "https://example.com/?fpr=a&fp_sid=x", "sub_id": "x"},
+ ]
+ )
+ ],
+ # A promoter deleted after the listing must not fail the whole fan-out.
+ "/promoters/2/referral_links": [ScriptedResponse(status=404, json={"code": "not_found"})],
+ }
+ ),
+ )
+
+ assert result.raised is None
+ assert result.rows == [
+ {"id": None, "url": "https://example.com/?fpr=a", "is_default": True, "promoter_id": 1},
+ {"id": "5", "url": "https://example.com/?fpr=a&fp_sid=x", "sub_id": "x", "promoter_id": 1},
+ ]
+ assert result.queries[0] == {
+ "page": ("1",),
+ "per_page": (str(DEFAULT_PAGE_SIZE),),
+ "sorting[joined_at]": ("asc",),
+ }