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(data-warehouse): add Bloomerang import source (#84314)

Tom Owers5b0041163f5c
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bloomerang/bloomerang.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bloomerang/bloomerang.py
new file mode 100644
index 000000000000..bed48d7bcc5d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bloomerang/bloomerang.py
@@ -0,0 +1,180 @@
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.bloomerang.settings import (
+ BLOOMERANG_ENDPOINTS,
+ PAGE_SIZE,
+ BloomerangEndpointConfig,
+)
+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 (
+ OffsetPaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ClientConfig
+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
+
+BASE_URL = "https://api.bloomerang.co/v2"
+
+
+@frozen
+class BloomerangResumeConfig:
+ # Next `skip` value to resume from. Matches OffsetPaginator's own resume-state shape.
+ next_offset: int
+
+
+def _flatten_audit_trail(item: dict[str, Any]) -> dict[str, Any]:
+ """Promote AuditTrail.CreatedDate/LastModifiedDate onto the row root.
+
+ Constituents, Transactions, and Interactions nest their timestamps under an `AuditTrail`
+ object; flattening them makes `CreatedDate` usable as a partition key and `LastModifiedDate`
+ usable as the incremental cursor column.
+ """
+ audit_trail = item.pop("AuditTrail", None)
+ if isinstance(audit_trail, dict):
+ item["CreatedDate"] = audit_trail.get("CreatedDate")
+ item["LastModifiedDate"] = audit_trail.get("LastModifiedDate")
+ return item
+
+
+def _format_last_modified(value: Any) -> str:
+ """Format an incremental cursor as the ISO-8601 UTC string Bloomerang's `lastModified` filter expects."""
+ if isinstance(value, datetime):
+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)
+ return aware.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
+ if isinstance(value, date):
+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
+ return str(value)
+
+
+def _build_params(
+ config: BloomerangEndpointConfig,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Optional[Any],
+) -> dict[str, Any]:
+ if config.supports_incremental and should_use_incremental_field and db_incremental_field_last_value:
+ return {
+ "lastModified": _format_last_modified(db_incremental_field_last_value),
+ "orderBy": "LastModifiedDate",
+ "orderDirection": "Asc",
+ }
+ if config.supports_sort:
+ # Explicit stable sort even for full refresh: Bloomerang's own default order direction
+ # varies by endpoint (Transactions defaults to Desc), so an unstated default can't be
+ # relied on to keep page boundaries stable as rows are inserted mid-sync.
+ return {"orderBy": "Id", "orderDirection": "Asc"}
+ return {}
+
+
+def _client_config(api_key: str) -> ClientConfig:
+ return {
+ "base_url": BASE_URL,
+ "headers": {"Accept": "application/json"},
+ "auth": {"type": "api_key", "name": "X-Api-Key", "api_key": api_key, "location": "header"},
+ # `capture=False`: Constituents, Transactions, and Interactions carry donor PII and
+ # free-form interaction notes that the name-based sample scrubbers can't recognise, so
+ # keep every response body out of HTTP sample storage. Requests stay metered and logged.
+ "session": make_tracked_session(redact_values=(api_key,), capture=False),
+ # `X-Api-Key` isn't the standard Authorization header, which `requests` strips on a
+ # cross-origin redirect, so a hostile redirect could otherwise harvest it — disable
+ # redirects for production syncs the same way the credential probe below already does.
+ "allow_redirects": False,
+ "paginator": OffsetPaginator(
+ limit=PAGE_SIZE,
+ offset_param="skip",
+ limit_param="take",
+ # TotalFiltered reflects whatever filters we send (e.g. lastModified); it equals the
+ # unfiltered Total when we send none.
+ total_path="TotalFiltered",
+ ),
+ }
+
+
+def bloomerang_source(
+ api_key: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[BloomerangResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = BLOOMERANG_ENDPOINTS[endpoint]
+ is_incremental = config.supports_incremental and should_use_incremental_field
+
+ rest_config: RESTAPIConfig = {
+ "client": _client_config(api_key),
+ "resource_defaults": {
+ "write_disposition": {"disposition": "merge", "strategy": "upsert"} if is_incremental else "replace",
+ },
+ "resources": [
+ {
+ "name": endpoint,
+ "table_name": endpoint.lower(),
+ "endpoint": {
+ "path": config.path,
+ "params": _build_params(config, should_use_incremental_field, db_incremental_field_last_value),
+ "data_selector": "Results",
+ },
+ "table_format": "delta",
+ }
+ ],
+ }
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume = resumable_source_manager.load_state()
+ if resume is not None:
+ initial_paginator_state = {"offset": resume.next_offset}
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # Only persist when there's a next page to resume to; the Redis TTL handles cleanup on
+ # completion, and saving after the page is yielded means a crash re-yields (merge dedupes)
+ # rather than skips it.
+ if state and state.get("offset") is not None:
+ resumable_source_manager.save_state(BloomerangResumeConfig(next_offset=int(state["offset"])))
+
+ resource = rest_api_resource(
+ rest_config,
+ team_id,
+ job_id,
+ None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+ if config.has_audit_trail:
+ resource = resource.add_map(_flatten_audit_trail)
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: resource,
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ sort_mode="asc",
+ )
+
+
+def validate_credentials(api_key: str) -> tuple[bool, int | None]:
+ return validate_via_probe(
+ # `capture=False`: the probe hits `/constituents`, which returns the same donor record
+ # shape as the real sync — keep it out of HTTP sample storage too.
+ lambda: make_tracked_session(headers={"Accept": "application/json"}, redact_values=(api_key,), capture=False),
+ f"{BASE_URL}/constituents",
+ headers={"X-Api-Key": api_key},
+ # X-Api-Key isn't the standard Authorization header, which `requests` strips on a
+ # cross-origin redirect; disable redirects so a hostile redirect can't harvest it.
+ allow_redirects=False,
+ ok_statuses=(200,),
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bloomerang/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bloomerang/canonical_descriptions.py
new file mode 100644
index 000000000000..bad7d560da12
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bloomerang/canonical_descriptions.py
@@ -0,0 +1,103 @@
+"""Canonical, documentation-sourced descriptions for Bloomerang v2 endpoints and columns.
+
+Bloomerang's REST API v2 has no public OpenAPI/Swagger page that renders without JavaScript, so
+these descriptions are sourced from the field comments in a maintained third-party client that
+mirrors the vendor's own API reference (https://bloomerang.co/features/integrations/api/rest-api),
+cross-checked against the vendor's own admin help docs (https://bloomerang.com/api). Keyed by the
+resource names in `settings.py` `ENDPOINTS`. Columns absent here fall back to LLM enrichment.
+"""
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+_DOCS_URL = "https://bloomerang.com/api/rest-api"
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "Constituents": {
+ "description": "An individual, household, or organization tracked in the Bloomerang donor database.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "Id": "Unique identifier for the constituent used by the API.",
+ "AccountNumber": "User-friendly account number shown in the Bloomerang CRM UI.",
+ "Type": "Whether the constituent is an Individual or an Organization.",
+ "Status": "Whether the constituent is Active, Inactive, or Deceased.",
+ "FirstName": "Constituent's first name.",
+ "LastName": "Constituent's last name.",
+ "FullName": "Constituent's full display name.",
+ "Employer": "Name of the constituent's employer.",
+ "HouseholdId": "ID of the household this constituent belongs to, if any.",
+ "PrimaryEmail": "The constituent's primary email address record.",
+ "PrimaryPhone": "The constituent's primary phone number record.",
+ "PrimaryAddress": "The constituent's primary mailing address record.",
+ "EngagementScore": "Bloomerang's calculated donor engagement level (Low through High).",
+ "CreatedDate": "When the constituent record was created, flattened from AuditTrail.",
+ "LastModifiedDate": "When the constituent record was last modified, flattened from AuditTrail.",
+ },
+ },
+ "Transactions": {
+ "description": "A donation, pledge, pledge payment, or recurring donation payment recorded against a constituent.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "Id": "Unique identifier for the transaction used by the API.",
+ "TransactionNumber": "User-friendly payment number shown in the Bloomerang CRM UI.",
+ "AccountId": "ID of the constituent the transaction is recorded against.",
+ "Date": "Date the transaction took place.",
+ "Amount": "Transaction amount.",
+ "Method": "Payment method (Cash, Check, CreditCard, Eft, InKind, or None).",
+ "Designations": "The fund/campaign/appeal splits this transaction's amount is allocated across.",
+ "IsRefunded": "Whether the transaction has been refunded (Yes or No).",
+ "CreatedDate": "When the transaction record was created, flattened from AuditTrail.",
+ "LastModifiedDate": "When the transaction record was last modified, flattened from AuditTrail.",
+ },
+ },
+ "Interactions": {
+ "description": "A logged touchpoint with a constituent, such as an email, call, or in-person visit.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "Id": "Unique identifier for the interaction used by the API.",
+ "Date": "Date the interaction took place.",
+ "Note": "Free-text note describing the interaction.",
+ "Channel": "Communication channel used (Email, Phone, Mail, InPerson, and others).",
+ "Purpose": "Reason for the interaction (Acknowledgement, Solicitation, Newsletter, and others).",
+ "Subject": "Subject line or short title of the interaction.",
+ "IsInbound": "Whether the interaction was initiated by the constituent rather than the org.",
+ "AccountId": "ID of the constituent the interaction is recorded against.",
+ "CreatedDate": "When the interaction record was created, flattened from AuditTrail.",
+ "LastModifiedDate": "When the interaction record was last modified, flattened from AuditTrail.",
+ },
+ },
+ "Appeals": {
+ "description": "A fundraising appeal (a specific ask sent to donors) that transactions can be designated to.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "Id": "Unique identifier for the appeal used by the API.",
+ "Name": "Name of the appeal.",
+ "SortIndex": "Manual sort position for the appeal in the Bloomerang CRM UI.",
+ "IsActive": "Whether the appeal is currently active.",
+ },
+ },
+ "Campaigns": {
+ "description": "A fundraising campaign that groups appeals and transactions toward a shared goal.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "Id": "Unique identifier for the campaign used by the API.",
+ "Name": "Name of the campaign.",
+ "Raised": "Total amount raised for this campaign so far.",
+ "Goal": "Fundraising goal amount for the campaign.",
+ "StartDate": "Date the campaign starts.",
+ "EndDate": "Date the campaign ends.",
+ "IsActive": "Whether the campaign is currently active.",
+ },
+ },
+ "Funds": {
+ "description": "A designation fund (general ledger bucket) that transactions can be allocated to.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "Id": "Unique identifier for the fund used by the API.",
+ "Name": "Name of the fund.",
+ "IsDefault": "Whether this is the default fund for undesignated transactions.",
+ "IsActive": "Whether the fund is currently active.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bloomerang/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bloomerang/settings.py
new file mode 100644
index 000000000000..3f31d7c84654
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bloomerang/settings.py
@@ -0,0 +1,98 @@
+from dataclasses import field
+from typing import Optional
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# Bloomerang's v2 list endpoints cap `take` at 50 (confirmed via the Parsons client library, which
+# clamps page_size to this maximum).
+PAGE_SIZE = 50
+
+
+def _last_modified_incremental_fields() -> list[IncrementalField]:
+ # Only endpoints whose rows carry AuditTrail.LastModifiedDate *and* whose list action accepts a
+ # server-side `lastModified` filter get this. See BloomerangEndpointConfig.supports_incremental.
+ return [
+ {
+ "label": "LastModifiedDate",
+ "type": IncrementalFieldType.DateTime,
+ "field": "LastModifiedDate",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ]
+
+
+@frozen
+class BloomerangEndpointConfig:
+ name: str
+ path: str # path under https://api.bloomerang.co/v2
+ # Whether the list action accepts a server-side `lastModified` filter (Constituents only —
+ # Transactions/Interactions accept `orderBy=LastModifiedDate` for sorting but no filter param).
+ supports_incremental: bool
+ # Whether the list action accepts `orderBy`/`orderDirection` at all (Appeals/Campaigns/Funds
+ # accept neither, per the API's own parameter docs).
+ supports_sort: bool
+ # Whether rows carry a nested `AuditTrail` object ({CreatedDate, LastModifiedDate, ...}) that
+ # gets flattened onto the row root. Appeals/Campaigns/Funds have no AuditTrail field.
+ has_audit_trail: bool
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ primary_keys: list[str] = field(default_factory=lambda: ["Id"])
+ # Stable creation-time column to partition by. None when the endpoint has no AuditTrail.
+ partition_key: Optional[str] = "CreatedDate"
+
+
+BLOOMERANG_ENDPOINTS: dict[str, BloomerangEndpointConfig] = {
+ "Constituents": BloomerangEndpointConfig(
+ name="Constituents",
+ path="constituents",
+ supports_incremental=True,
+ supports_sort=True,
+ has_audit_trail=True,
+ incremental_fields=_last_modified_incremental_fields(),
+ ),
+ "Transactions": BloomerangEndpointConfig(
+ name="Transactions",
+ path="transactions",
+ supports_incremental=False,
+ supports_sort=True,
+ has_audit_trail=True,
+ ),
+ "Interactions": BloomerangEndpointConfig(
+ name="Interactions",
+ path="interactions",
+ supports_incremental=False,
+ supports_sort=True,
+ has_audit_trail=True,
+ ),
+ "Appeals": BloomerangEndpointConfig(
+ name="Appeals",
+ path="appeals",
+ supports_incremental=False,
+ supports_sort=False,
+ has_audit_trail=False,
+ partition_key=None,
+ ),
+ "Campaigns": BloomerangEndpointConfig(
+ name="Campaigns",
+ path="campaigns",
+ supports_incremental=False,
+ supports_sort=False,
+ has_audit_trail=False,
+ partition_key=None,
+ ),
+ "Funds": BloomerangEndpointConfig(
+ name="Funds",
+ path="funds",
+ supports_incremental=False,
+ supports_sort=False,
+ has_audit_trail=False,
+ partition_key=None,
+ ),
+}
+
+ENDPOINTS = tuple(BLOOMERANG_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in BLOOMERANG_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bloomerang/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bloomerang/source.py
index ef08ae0ef366..14b60c80ab68 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bloomerang/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bloomerang/source.py
@@ -1,13 +1,34 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.bloomerang.bloomerang import (
+ BloomerangResumeConfig,
+ bloomerang_source,
+ validate_credentials as validate_bloomerang_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.bloomerang.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (
+ SourceSchema,
+ build_endpoint_schemas,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.bloomerang import (
BloomerangSourceConfig,
)
@@ -15,18 +36,99 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class BloomerangSource(SimpleSource[BloomerangSourceConfig]):
+class BloomerangSource(ResumableSource[BloomerangSourceConfig, BloomerangResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
+ # Bloomerang's v2 REST API has no dated/numbered version token to pin (the "v2" is a fixed
+ # path segment, not a documented choice among several) — only the docs link is set.
+ api_docs_url = "https://bloomerang.com/api/rest-api"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.BLOOMERANG
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": "Your Bloomerang API key is invalid or has been revoked. Generate a new private key under User Settings, then reconnect.",
+ "403 Client Error": "Your Bloomerang API key does not have permission to read this data. Check the key's permissions, then reconnect.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.bloomerang.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: BloomerangSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+
+ def validate_credentials(
+ self,
+ config: BloomerangSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ is_valid, status_code = validate_bloomerang_credentials(config.api_key)
+ if is_valid:
+ return True, None
+ if status_code == 401:
+ return False, "Invalid Bloomerang API key"
+ return False, "Could not connect to Bloomerang with the provided API key"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[BloomerangResumeConfig]:
+ return ResumableSourceManager[BloomerangResumeConfig](inputs, BloomerangResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: BloomerangSourceConfig,
+ resumable_source_manager: ResumableSourceManager[BloomerangResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return bloomerang_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.BLOOMERANG,
category=DataWarehouseSourceCategory.CRM,
- label="Bloomerang, LLC",
+ keywords=["donor", "nonprofit", "fundraising"],
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Bloomerang private API key to pull your donor database into the PostHog Data warehouse, including constituents, transactions, interactions, appeals, campaigns, and funds.
+
+Generate a private API key under **Settings → User Settings → API Keys** in your Bloomerang account. This key grants full read/write access to your Bloomerang data, so keep it secret.""",
iconPath="/static/services/bloomerang.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/bloomerang",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bloomerang/tests/test_bloomerang.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bloomerang/tests/test_bloomerang.py
new file mode 100644
index 000000000000..5f63948f9bc0
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bloomerang/tests/test_bloomerang.py
@@ -0,0 +1,361 @@
+import json
+from datetime import UTC, date, datetime
+from typing import Any
+
+from unittest import mock
+
+from parameterized import parameterized
+from requests import Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.bloomerang.bloomerang import (
+ BloomerangResumeConfig,
+ _build_params,
+ _flatten_audit_trail,
+ _format_last_modified,
+ bloomerang_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.bloomerang.settings import BLOOMERANG_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import APIKeyAuth
+
+# The client config and validate_credentials both build their tracked session directly in the
+# bloomerang module (capture=False needs a session built here, not RESTClient's default one).
+BLOOMERANG_SESSION_PATCH = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.bloomerang.bloomerang.make_tracked_session"
+)
+
+
+class TestFlattenAuditTrail:
+ def test_promotes_created_and_last_modified(self) -> None:
+ item = {
+ "Id": 1,
+ "AuditTrail": {"CreatedDate": "2026-01-01T00:00:00Z", "LastModifiedDate": "2026-02-01T00:00:00Z"},
+ }
+
+ result = _flatten_audit_trail(item)
+
+ assert result["CreatedDate"] == "2026-01-01T00:00:00Z"
+ assert result["LastModifiedDate"] == "2026-02-01T00:00:00Z"
+ assert "AuditTrail" not in result
+
+ def test_missing_audit_trail_is_a_no_op(self) -> None:
+ item = {"Id": 1}
+ assert _flatten_audit_trail(item) == {"Id": 1}
+
+ def test_non_dict_audit_trail_is_ignored(self) -> None:
+ item = {"Id": 1, "AuditTrail": None}
+ result = _flatten_audit_trail(item)
+ assert "CreatedDate" not in result
+ assert "AuditTrail" not in result
+
+
+class TestFormatLastModified:
+ @parameterized.expand(
+ [
+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14Z"),
+ ("naive_datetime", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14Z"),
+ ("date_value", date(2026, 3, 4), "2026-03-04T00:00:00Z"),
+ ("string_passthrough", "2026-03-04T02:58:14Z", "2026-03-04T02:58:14Z"),
+ ]
+ )
+ def test_format(self, _name: str, value: Any, expected: str) -> None:
+ result = _format_last_modified(value)
+ assert result == expected
+ assert "+00:00" not in result
+
+
+class TestBuildParams:
+ def test_incremental_endpoint_with_cursor(self) -> None:
+ params = _build_params(
+ BLOOMERANG_ENDPOINTS["Constituents"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),
+ )
+ assert params == {
+ "lastModified": "2026-03-04T02:58:14Z",
+ "orderBy": "LastModifiedDate",
+ "orderDirection": "Asc",
+ }
+
+ def test_incremental_endpoint_without_cursor_falls_back_to_stable_sort(self) -> None:
+ # First-ever sync: no watermark yet, but the endpoint still supports sorting, so page
+ # boundaries must stay stable rather than sending no params at all.
+ params = _build_params(
+ BLOOMERANG_ENDPOINTS["Constituents"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=None,
+ )
+ assert params == {"orderBy": "Id", "orderDirection": "Asc"}
+
+ def test_full_refresh_endpoint_with_sort_support_never_filters(self) -> None:
+ # Transactions has no server-side lastModified filter; a cursor must not leak into the request.
+ params = _build_params(
+ BLOOMERANG_ENDPOINTS["Transactions"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),
+ )
+ assert params == {"orderBy": "Id", "orderDirection": "Asc"}
+
+ def test_endpoint_without_sort_support_sends_no_params(self) -> None:
+ params = _build_params(
+ BLOOMERANG_ENDPOINTS["Appeals"], should_use_incremental_field=False, db_incremental_field_last_value=None
+ )
+ assert params == {}
+
+
+def _response(
+ items: list[dict[str, Any]] | None, *, total_filtered: int | None = None, drop_results: bool = False
+) -> Response:
+ body: dict[str, Any] = {}
+ if not drop_results:
+ body["Results"] = items or []
+ body["Total"] = total_filtered if total_filtered is not None else len(items or [])
+ if total_filtered is not None:
+ body["TotalFiltered"] = total_filtered
+ body["Start"] = 0
+ body["ResultCount"] = len(items or [])
+ resp = Response()
+ resp.status_code = 200
+ resp._content = json.dumps(body).encode()
+ return resp
+
+
+def _make_manager(resume_state: BloomerangResumeConfig | None = None) -> mock.MagicMock:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = resume_state is not None
+ manager.load_state.return_value = resume_state
+ return manager
+
+
+def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:
+ """Wire a mock session and capture each request's params/auth AT SEND TIME."""
+ session.headers = {}
+ snapshots: list[dict[str, Any]] = []
+
+ def _prepare(request: Any) -> mock.MagicMock:
+ snapshots.append({"url": request.url, "params": dict(request.params or {}), "auth": request.auth})
+ return mock.MagicMock()
+
+ session.prepare_request.side_effect = _prepare
+ session.send.side_effect = responses
+ return snapshots
+
+
+def _source(endpoint: str, manager: mock.MagicMock, **kwargs: Any):
+ return bloomerang_source(
+ api_key="key",
+ endpoint=endpoint,
+ team_id=1,
+ job_id="j",
+ resumable_source_manager=manager,
+ **kwargs,
+ )
+
+
+def _rows(source_response) -> list[dict[str, Any]]:
+ return [row for page in source_response.items() for row in page]
+
+
+class TestBloomerangSourceTransport:
+ @mock.patch(BLOOMERANG_SESSION_PATCH)
+ def test_paginates_until_short_page(self, MockSession) -> None:
+ # A full first page (== PAGE_SIZE) signals more rows remain; the paginator only stops once
+ # a page comes back shorter than PAGE_SIZE.
+ session = MockSession.return_value
+ first_page = [{"Id": i} for i in range(1, 51)]
+ snapshots = _wire(
+ session,
+ [
+ _response(first_page, total_filtered=51),
+ _response([{"Id": 51}], total_filtered=51),
+ ],
+ )
+
+ rows = _rows(_source("Appeals", _make_manager()))
+
+ assert [r["Id"] for r in rows] == list(range(1, 52))
+ assert session.send.call_count == 2
+ assert snapshots[0]["params"] == {"skip": 0, "take": 50}
+ assert snapshots[1]["params"] == {"skip": 50, "take": 50}
+
+ @mock.patch(BLOOMERANG_SESSION_PATCH)
+ def test_auth_is_framework_api_key(self, MockSession) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(session, [_response([{"Id": 1}], total_filtered=1)])
+
+ _rows(_source("Appeals", _make_manager()))
+
+ auth = snapshots[0]["auth"]
+ assert isinstance(auth, APIKeyAuth)
+ assert auth.api_key == "key"
+ assert auth.name == "X-Api-Key"
+ assert auth.location == "header"
+
+ @mock.patch(BLOOMERANG_SESSION_PATCH)
+ def test_production_sync_does_not_follow_redirects(self, MockSession) -> None:
+ # `X-Api-Key` isn't the standard Authorization header, so `requests` won't strip it on a
+ # cross-origin redirect — pin `allow_redirects=False` the same way the credential probe does.
+ session = MockSession.return_value
+ _wire(session, [_response([{"Id": 1}], total_filtered=1)])
+
+ _rows(_source("Appeals", _make_manager()))
+
+ assert session.send.call_args.kwargs["allow_redirects"] is False
+
+ @mock.patch(BLOOMERANG_SESSION_PATCH)
+ def test_saves_resume_state_only_while_pages_remain(self, MockSession) -> None:
+ session = MockSession.return_value
+ first_page = [{"Id": i} for i in range(1, 51)]
+ _wire(
+ session,
+ [
+ _response(first_page, total_filtered=51),
+ _response([{"Id": 51}], total_filtered=51),
+ ],
+ )
+
+ manager = _make_manager()
+ _rows(_source("Appeals", manager))
+
+ # State is saved only while more pages remain (offset 0 -> next offset 50), never on the
+ # final (short) page.
+ manager.save_state.assert_called_once()
+ assert manager.save_state.call_args.args[0] == BloomerangResumeConfig(next_offset=50)
+
+ @mock.patch(BLOOMERANG_SESSION_PATCH)
+ def test_resumes_from_saved_offset(self, MockSession) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(session, [_response([{"Id": 51}], total_filtered=51)])
+
+ rows = _rows(_source("Appeals", _make_manager(BloomerangResumeConfig(next_offset=50))))
+
+ assert [r["Id"] for r in rows] == [51]
+ assert session.send.call_count == 1
+ assert snapshots[0]["params"]["skip"] == 50
+
+ @mock.patch(BLOOMERANG_SESSION_PATCH)
+ def test_incremental_cursor_added_to_request(self, MockSession) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(session, [_response([{"Id": 1}], total_filtered=1)])
+
+ _rows(
+ _source(
+ "Constituents",
+ _make_manager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),
+ )
+ )
+
+ assert snapshots[0]["params"]["lastModified"] == "2026-03-04T02:58:14Z"
+ assert snapshots[0]["params"]["orderBy"] == "LastModifiedDate"
+
+ @mock.patch(BLOOMERANG_SESSION_PATCH)
+ def test_audit_trail_endpoint_flattens_rows(self, MockSession) -> None:
+ session = MockSession.return_value
+ _wire(
+ session,
+ [
+ _response(
+ [
+ {
+ "Id": 1,
+ "AuditTrail": {
+ "CreatedDate": "2026-01-01T00:00:00Z",
+ "LastModifiedDate": "2026-01-02T00:00:00Z",
+ },
+ }
+ ],
+ total_filtered=1,
+ )
+ ],
+ )
+
+ rows = _rows(_source("Constituents", _make_manager()))
+
+ assert rows[0]["CreatedDate"] == "2026-01-01T00:00:00Z"
+ assert rows[0]["LastModifiedDate"] == "2026-01-02T00:00:00Z"
+ assert "AuditTrail" not in rows[0]
+
+ @mock.patch(BLOOMERANG_SESSION_PATCH)
+ def test_non_audit_trail_endpoint_leaves_rows_untouched(self, MockSession) -> None:
+ session = MockSession.return_value
+ _wire(session, [_response([{"Id": 1, "Name": "Winter Appeal"}], total_filtered=1)])
+
+ rows = _rows(_source("Appeals", _make_manager()))
+
+ assert rows[0] == {"Id": 1, "Name": "Winter Appeal"}
+
+ @parameterized.expand(
+ [
+ ("Constituents", "merge"),
+ ("Transactions", "replace"),
+ ("Appeals", "replace"),
+ ]
+ )
+ def test_write_disposition_merges_only_for_incremental_sync(self, endpoint, expected_disposition) -> None:
+ resource = _source(
+ endpoint,
+ _make_manager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),
+ ).items()
+
+ write_disposition = resource._hints.get("write_disposition")
+ if expected_disposition == "merge":
+ assert write_disposition == {"disposition": "merge", "strategy": "upsert"}
+ else:
+ assert write_disposition == "replace"
+
+ def test_partition_key_present_only_for_audit_trail_endpoints(self) -> None:
+ constituents = _source("Constituents", _make_manager())
+ appeals = _source("Appeals", _make_manager())
+
+ assert constituents.partition_keys == ["CreatedDate"]
+ assert constituents.partition_mode == "datetime"
+ assert appeals.partition_keys is None
+ assert appeals.partition_mode is None
+
+
+class TestValidateCredentials:
+ @parameterized.expand(
+ [
+ (200, True, 200),
+ (401, False, 401),
+ (403, False, 403),
+ ]
+ )
+ @mock.patch(BLOOMERANG_SESSION_PATCH)
+ def test_status_mapping(self, status_code, expected_valid, expected_status, MockSession) -> None:
+ session = MockSession.return_value
+ response = mock.MagicMock()
+ response.status_code = status_code
+ session.get.return_value = response
+
+ is_valid, returned_status = validate_credentials("key")
+
+ assert is_valid is expected_valid
+ assert returned_status == expected_status
+
+ @mock.patch(BLOOMERANG_SESSION_PATCH)
+ def test_sends_api_key_header_without_following_redirects(self, MockSession) -> None:
+ session = MockSession.return_value
+ response = mock.MagicMock()
+ response.status_code = 200
+ session.get.return_value = response
+
+ validate_credentials("secret-key")
+
+ call_kwargs = session.get.call_args.kwargs
+ assert call_kwargs["headers"] == {"X-Api-Key": "secret-key"}
+ assert call_kwargs["allow_redirects"] is False
+
+ @mock.patch(BLOOMERANG_SESSION_PATCH)
+ def test_network_failure_is_reported_as_invalid(self, MockSession) -> None:
+ session = MockSession.return_value
+ session.get.side_effect = Exception("boom")
+
+ is_valid, status = validate_credentials("key")
+
+ assert is_valid is False
+ assert status is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bloomerang/tests/test_bloomerang_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bloomerang/tests/test_bloomerang_source.py
new file mode 100644
index 000000000000..9276ad841871
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bloomerang/tests/test_bloomerang_source.py
@@ -0,0 +1,158 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.bloomerang.bloomerang import (
+ BloomerangResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.bloomerang.settings import (
+ BLOOMERANG_ENDPOINTS,
+ ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.bloomerang.source import BloomerangSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.bloomerang import (
+ BloomerangSourceConfig,
+)
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+_INCREMENTAL_ENDPOINTS = {"Constituents"}
+_FULL_REFRESH_ENDPOINTS = {"Transactions", "Interactions", "Appeals", "Campaigns", "Funds"}
+
+
+class TestBloomerangSource:
+ def setup_method(self):
+ self.source = BloomerangSource()
+ self.team_id = 123
+ self.config = BloomerangSourceConfig(api_key="key")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.BLOOMERANG
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Bloomerang"
+ assert config.category is not None
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is None
+ assert config.iconPath == "/static/services/bloomerang.png"
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/bloomerang"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["api_key"]
+
+ def test_api_key_field_is_secret_password(self):
+ config = self.source.get_source_config
+ api_key_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")
+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key_field.secret is True
+ assert api_key_field.required is True
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.bloomerang.co/v2/constituents?skip=0&take=50",
+ "403 Client Error: Forbidden for url: https://api.bloomerang.co/v2/transactions?skip=0&take=50",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ @pytest.mark.parametrize(
+ "other_error",
+ [
+ "429 Client Error: Too Many Requests for url: https://api.bloomerang.co/v2/constituents",
+ "500 Server Error: Internal Server Error for url: https://api.bloomerang.co/v2/constituents",
+ "HTTPSConnectionPool(host='api.bloomerang.co', port=443): Read timed out.",
+ ],
+ )
+ def test_non_retryable_errors_do_not_match_transient(self, other_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(key in other_error for key in non_retryable_errors)
+
+ def test_get_schemas_match_endpoints_with_correct_sync_modes(self):
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+
+ assert set(schemas) == set(ENDPOINTS)
+ for name in _INCREMENTAL_ENDPOINTS:
+ assert schemas[name].supports_incremental is True
+ assert schemas[name].supports_append is True
+ assert [f["field"] for f in schemas[name].incremental_fields] == ["LastModifiedDate"]
+ for name in _FULL_REFRESH_ENDPOINTS:
+ assert schemas[name].supports_incremental is False
+ assert schemas[name].supports_append is False
+ assert schemas[name].incremental_fields == []
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["Constituents"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "Constituents"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["Nope"]) == []
+
+ def test_lists_tables_without_credentials_publishes_catalog(self):
+ # Static endpoint catalog (no I/O) — the public docs table list should render.
+ assert self.source.lists_tables_without_credentials is True
+ documented = self.source.get_documented_tables()
+ assert {table["name"] for table in documented} == set(ENDPOINTS)
+
+ def test_canonical_descriptions_cover_every_endpoint(self):
+ canonical = self.source.get_canonical_descriptions()
+ assert set(canonical) == set(BLOOMERANG_ENDPOINTS)
+
+ @pytest.mark.parametrize(
+ "mock_return, expected_valid, expected_message",
+ [
+ ((True, 200), True, None),
+ ((False, 401), False, "Invalid Bloomerang API key"),
+ ((False, 403), False, "Could not connect to Bloomerang with the provided API key"),
+ ((False, None), False, "Could not connect to Bloomerang with the provided API key"),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.bloomerang.source.validate_bloomerang_credentials"
+ )
+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):
+ mock_validate.return_value = mock_return
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is expected_valid
+ assert error_message == expected_message
+ mock_validate.assert_called_once_with("key")
+
+ def test_get_resumable_source_manager_bound_to_resume_config(self):
+ inputs = mock.MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+ assert manager._data_class is BloomerangResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.bloomerang.source.bloomerang_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_bloomerang_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "Constituents"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_bloomerang_source.assert_called_once()
+ kwargs = mock_bloomerang_source.call_args.kwargs
+ assert kwargs["api_key"] == "key"
+ assert kwargs["endpoint"] == "Constituents"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.bloomerang.source.bloomerang_source")
+ def test_source_for_pipeline_omits_cursor_when_not_incremental(self, mock_bloomerang_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "Appeals"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_bloomerang_source.call_args.kwargs["db_incremental_field_last_value"] is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/bloomerang.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/bloomerang.py
index 9e0b11081fe6..9615941164f0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/bloomerang.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/bloomerang.py
@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class BloomerangSourceConfig(config.Config):
- pass
+ api_key: str