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): implement onepagecrm import source (#69370)

Tom Owers80cc104a604e
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 1ac5cce6ce8e..32ac31bbda68 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -253,6 +253,7 @@ the row lists both.
| notion | HTTP | requests | ✅ |
| omnisend | HTTP | requests | ✅ |
| oncehub | HTTP | requests | ✅ |
+| onepagecrm | HTTP | requests | ✅ |
| onfleet | HTTP (cursor pagination) | requests | ✅ |
| open_exchange_rates | HTTP | requests | ✅ |
| opinion_stage | HTTP | requests | ✅ |
@@ -621,7 +622,6 @@ doesn't conflict with concurrent PRs.
- nylas
- onedrive
- onehundredms
-- onepagecrm
- onesignal
- open_data_dc
- openrouter
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index 482ddd00cf01..deda57cae7ef 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
@@ -2353,7 +2353,8 @@ class OneSignalSourceConfig(config.Config):
@config.config
class OnepagecrmSourceConfig(config.Config):
- pass
+ user_id: str
+ api_key: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/onepagecrm/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/onepagecrm/canonical_descriptions.py
new file mode 100644
index 000000000000..94406b9a0202
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/onepagecrm/canonical_descriptions.py
@@ -0,0 +1,174 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Sourced from the OnePageCRM API v3 reference (https://developer.onepagecrm.com/api/).
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "contacts": {
+ "description": "People in the CRM — the core record actions, deals, notes, calls, and meetings hang off.",
+ "docs_url": "https://developer.onepagecrm.com/api/",
+ "columns": {
+ "id": "Unique identifier of the contact.",
+ "first_name": "First name of the contact.",
+ "last_name": "Last name of the contact.",
+ "job_title": "Job title of the contact.",
+ "company_id": "ID of the company the contact belongs to.",
+ "company_name": "Name of the company the contact belongs to.",
+ "starred": "Whether the contact is starred.",
+ "phones": "List of the contact's phone numbers with their types.",
+ "emails": "List of the contact's email addresses with their types.",
+ "address_list": "List of the contact's postal addresses.",
+ "status": "Text of the contact's status.",
+ "status_id": "ID of the contact's status.",
+ "tags": "List of tags assigned to the contact.",
+ "lead_source_id": "ID of the contact's lead source.",
+ "background": "Background information about the contact.",
+ "owner_id": "ID of the user who owns the contact.",
+ "custom_fields": "List of custom field values set on the contact.",
+ "pending_deal": "Whether the contact has a pending deal.",
+ "created_at": "Time the contact was created.",
+ "modified_at": "Time the contact was last modified.",
+ },
+ },
+ "companies": {
+ "description": "Organizations that contacts belong to.",
+ "docs_url": "https://developer.onepagecrm.com/api/",
+ "columns": {
+ "id": "Unique identifier of the company.",
+ "name": "Name of the company.",
+ "description": "Description of the company.",
+ "phone": "Phone number of the company.",
+ "url": "Website URL of the company.",
+ "address": "Postal address of the company.",
+ "company_fields": "List of custom company field values.",
+ "contacts_count": "Number of contacts linked to the company.",
+ "won_deals_count": "Number of won deals for the company.",
+ "total_won_amount": "Total amount of won deals for the company.",
+ "pending_deals_count": "Number of pending deals for the company.",
+ "total_pending_amount": "Total amount of pending deals for the company.",
+ "created_at": "Time the company was created.",
+ "modified_at": "Time the company was last modified.",
+ },
+ },
+ "deals": {
+ "description": "Sales opportunities attached to contacts, tracked through pipeline stages.",
+ "docs_url": "https://developer.onepagecrm.com/api/",
+ "columns": {
+ "id": "Unique identifier of the deal.",
+ "contact_id": "ID of the contact the deal is attached to.",
+ "owner_id": "ID of the user who owns the deal.",
+ "pipeline_id": "ID of the pipeline the deal is in.",
+ "name": "Name of the deal.",
+ "text": "Description of the deal.",
+ "stage": "Pipeline stage of the deal.",
+ "status": "Status of the deal (pending, won, or lost).",
+ "expected_close_date": "Date the deal is expected to close.",
+ "close_date": "Date the deal was closed.",
+ "date": "Date the deal was created or applies to.",
+ "amount": "Monthly amount of the deal.",
+ "months": "Number of months the deal amount applies for.",
+ "total_amount": "Total amount of the deal.",
+ "cost": "Cost associated with the deal.",
+ "created_at": "Time the deal was created.",
+ "modified_at": "Time the deal was last modified.",
+ },
+ },
+ "actions": {
+ "description": "Next actions and queued tasks assigned to users for specific contacts.",
+ "docs_url": "https://developer.onepagecrm.com/api/",
+ "columns": {
+ "id": "Unique identifier of the action.",
+ "assignee_id": "ID of the user the action is assigned to.",
+ "contact_id": "ID of the contact the action is for.",
+ "text": "Text of the action.",
+ "status": "Status of the action (e.g. asap, queued, date-based).",
+ "date": "Date the action is due.",
+ "exact_time": "Exact time the action is due, as a UNIX timestamp.",
+ "done": "Whether the action has been completed.",
+ "done_at": "Time the action was completed.",
+ "created_at": "Time the action was created.",
+ "modified_at": "Time the action was last modified.",
+ },
+ },
+ "notes": {
+ "description": "Notes logged against contacts, optionally linked to deals.",
+ "docs_url": "https://developer.onepagecrm.com/api/",
+ "columns": {
+ "id": "Unique identifier of the note.",
+ "contact_id": "ID of the contact the note belongs to.",
+ "text": "Text content of the note.",
+ "date": "Date of the note.",
+ "linked_deal_id": "ID of the deal the note is linked to.",
+ "author": "ID of the user who wrote the note.",
+ "created_at": "Time the note was created.",
+ "modified_at": "Time the note was last modified.",
+ },
+ },
+ "calls": {
+ "description": "Call records logged against contacts, including results and notes.",
+ "docs_url": "https://developer.onepagecrm.com/api/",
+ "columns": {
+ "id": "Unique identifier of the call.",
+ "contact_id": "ID of the contact the call was with.",
+ "text": "Notes recorded for the call.",
+ "call_result": "Result of the call (e.g. interested, left message).",
+ "call_time_int": "Time of the call as a UNIX timestamp.",
+ "via": "How the call record was created.",
+ "phone_number": "Phone number the call was made to.",
+ "recording_link": "URL of the call recording.",
+ "author": "ID of the user who logged the call.",
+ "created_at": "Time the call record was created.",
+ "modified_at": "Time the call record was last modified.",
+ },
+ },
+ "meetings": {
+ "description": "Meeting records logged against contacts.",
+ "docs_url": "https://developer.onepagecrm.com/api/",
+ "columns": {
+ "id": "Unique identifier of the meeting.",
+ "contact_id": "ID of the contact the meeting was with.",
+ "text": "Notes recorded for the meeting.",
+ "meeting_time_int": "Time of the meeting as a UNIX timestamp.",
+ "place": "Location of the meeting.",
+ "author": "ID of the user who logged the meeting.",
+ "created_at": "Time the meeting record was created.",
+ "modified_at": "Time the meeting record was last modified.",
+ },
+ },
+ "users": {
+ "description": "Users on the OnePageCRM account.",
+ "docs_url": "https://developer.onepagecrm.com/api/",
+ "columns": {
+ "id": "Unique identifier of the user.",
+ "first_name": "First name of the user.",
+ "last_name": "Last name of the user.",
+ "email": "Email address of the user.",
+ "company_name": "Company name on the user's account.",
+ "account_rights": "Account permissions granted to the user.",
+ "bcc_email": "BCC email address used to log emails against contacts.",
+ },
+ },
+ "statuses": {
+ "description": "Contact statuses configured on the account, with per-status contact counts.",
+ "docs_url": "https://developer.onepagecrm.com/api/",
+ "columns": {
+ "id": "Unique identifier of the status.",
+ "status": "Machine name of the status.",
+ "text": "Display text of the status.",
+ "description": "Description of the status.",
+ "color": "Display color of the status.",
+ "counts": "Number of the API user's contacts with this status.",
+ "total_count": "Number of contacts across the account with this status.",
+ },
+ },
+ "lead_sources": {
+ "description": "Lead sources configured on the account, with per-source contact counts.",
+ "docs_url": "https://developer.onepagecrm.com/api/",
+ "columns": {
+ "id": "Unique identifier of the lead source.",
+ "text": "Display text of the lead source.",
+ "counts": "Number of the API user's contacts with this lead source.",
+ "total_count": "Number of contacts across the account with this lead source.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/onepagecrm/onepagecrm.py b/products/warehouse_sources/backend/temporal/data_imports/sources/onepagecrm/onepagecrm.py
new file mode 100644
index 000000000000..a4ed6b1ceee2
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/onepagecrm/onepagecrm.py
@@ -0,0 +1,296 @@
+import base64
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+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.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.onepagecrm.settings import (
+ ONEPAGECRM_ENDPOINTS,
+ OnepagecrmEndpointConfig,
+)
+
+ONEPAGECRM_BASE_URL = "https://app.onepagecrm.com/api/v3"
+# List endpoints accept a `per_page` of up to 100; the largest page minimises round trips.
+PAGE_SIZE = 100
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRIES = 5
+# Cheap endpoint used to confirm the user ID / API key pair is genuine. The key grants read access
+# to the whole account, so one probe validates access to every list endpoint.
+DEFAULT_PROBE_PATH = "/contacts"
+
+
+class OnepagecrmRetryableError(Exception):
+ pass
+
+
+class OnepagecrmResumeConfig:
+ # Next page to fetch (1-based). Page numbering is only stable for a fixed query, so the
+ # `modified_since` anchor the run started with is persisted alongside it — resuming with a
+ # fresher watermark would renumber the pages and skip rows.
+ page: int = 1
+ modified_since: str | None = None
+
+
+def _basic_auth_token(user_id: str, api_key: str) -> str:
+ return base64.b64encode(f"{user_id}:{api_key}".encode("ascii")).decode("ascii")
+
+
+def _headers(user_id: str, api_key: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Basic {_basic_auth_token(user_id, api_key)}",
+ "Accept": "application/json",
+ }
+
+
+def _make_session(user_id: str, api_key: str) -> requests.Session:
+ # Redact the derived Basic token as well as the raw key so neither survives in
+ # tracked-transport logs or captured samples if an upstream ever reflects it back.
+ return make_tracked_session(
+ headers=_headers(user_id, api_key),
+ redact_values=(api_key, _basic_auth_token(user_id, api_key)),
+ )
+
+
+def _to_epoch(value: Any) -> Optional[int]:
+ """Coerce an incremental cursor value to a UNIX timestamp for the `modified_since` filter.
+
+ OnePageCRM returns `modified_at` as an ISO 8601 string, so the persisted watermark can be a
+ string or a parsed datetime depending on how the column was typed; ints are accepted
+ defensively.
+ """
+ if value is None or isinstance(value, bool):
+ return None
+ if isinstance(value, int):
+ return value
+ if isinstance(value, float):
+ return int(value)
+ if isinstance(value, datetime):
+ dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
+ return int(dt.timestamp())
+ if isinstance(value, date):
+ return int(datetime.combine(value, datetime.min.time(), tzinfo=UTC).timestamp())
+ if isinstance(value, str):
+ try:
+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
+ except ValueError:
+ try:
+ return int(value)
+ except ValueError:
+ return None
+ if parsed.tzinfo is None:
+ parsed = parsed.replace(tzinfo=UTC)
+ return int(parsed.timestamp())
+ return None
+
+
+def modified_since_anchor(db_incremental_field_last_value: Any) -> str | None:
+ """Compute the `modified_since` value for an incremental run.
+
+ The anchor is backed off by one second: the API doesn't document whether the filter is
+ inclusive, and re-fetching the boundary second is free (merge dedupes on `id`) while missing
+ it would drop rows.
+ """
+ epoch = _to_epoch(db_incremental_field_last_value)
+ if epoch is None:
+ return None
+ return str(max(0, epoch - 1))
+
+
+def _build_params(
+ config: OnepagecrmEndpointConfig,
+ page: int,
+ modified_since: str | None,
+ should_use_incremental_field: bool,
+) -> dict[str, Any]:
+ params: dict[str, Any] = {}
+ if config.paginated:
+ params["page"] = page
+ params["per_page"] = PAGE_SIZE
+ if config.supports_sort:
+ # Incremental runs sort by the cursor field so the per-batch watermark advances
+ # monotonically (sort_mode="asc"). Full-refresh runs sort by the immutable created_at so
+ # rows never shift into already-fetched pages mid-sync.
+ params["sort_by"] = "modified_at" if should_use_incremental_field else "created_at"
+ params["order"] = "asc"
+ if modified_since is not None:
+ params["modified_since"] = modified_since
+ return params
+
+
+def _unwrap_items(config: OnepagecrmEndpointConfig, raw_items: list[Any]) -> list[dict[str, Any]]:
+ # Paginated list responses wrap each record under its singular resource name
+ # (e.g. {"contact": {...}, "next_actions": [...]}); config endpoints vary — users/statuses wrap,
+ # lead_sources doesn't.
+ items: list[dict[str, Any]] = []
+ for raw in raw_items:
+ if not isinstance(raw, dict):
+ continue
+ if config.item_key is not None and isinstance(raw.get(config.item_key), dict):
+ items.append(raw[config.item_key])
+ else:
+ items.append(raw)
+ return items
+
+
+def get_rows(
+ user_id: str,
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[OnepagecrmResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = ONEPAGECRM_ENDPOINTS[endpoint]
+ session = _make_session(user_id, api_key)
+
+ @retry(
+ retry=retry_if_exception_type((OnepagecrmRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRIES),
+ wait=wait_exponential_jitter(initial=1, max=60),
+ reraise=True,
+ )
+ def fetch_page(params: dict[str, Any]) -> dict[str, Any]:
+ response = session.get(
+ f"{ONEPAGECRM_BASE_URL}{config.path}",
+ params=params,
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise OnepagecrmRetryableError(
+ f"OnePageCRM API error (retryable): status={response.status_code}, path={config.path}"
+ )
+
+ if not response.ok:
+ logger.error(
+ f"OnePageCRM API error: status={response.status_code}, body={response.text}, path={config.path}"
+ )
+ response.raise_for_status()
+
+ body = response.json()
+ if not isinstance(body, dict):
+ raise OnepagecrmRetryableError(
+ f"OnePageCRM returned an unexpected payload for {config.path}: {type(body).__name__}"
+ )
+ return body
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume is not None:
+ page = resume.page
+ modified_since = resume.modified_since
+ logger.debug(f"OnePageCRM: resuming {endpoint} from page {page} (modified_since={modified_since})")
+ else:
+ page = 1
+ modified_since = (
+ modified_since_anchor(db_incremental_field_last_value) if should_use_incremental_field else None
+ )
+
+ if not config.paginated:
+ body = fetch_page(_build_params(config, page, modified_since, should_use_incremental_field))
+ raw_items = body.get("data")
+ if not isinstance(raw_items, list):
+ raise OnepagecrmRetryableError(
+ f"OnePageCRM returned an unexpected 'data' field for {config.path}: {type(raw_items).__name__}"
+ )
+ items = _unwrap_items(config, raw_items)
+ if items:
+ yield items
+ return
+
+ while True:
+ body = fetch_page(_build_params(config, page, modified_since, should_use_incremental_field))
+ data = body.get("data")
+ if not isinstance(data, dict) or not isinstance(data.get(config.data_key), list):
+ raise OnepagecrmRetryableError(
+ f"OnePageCRM returned an unexpected 'data' field for {config.path}: {type(data).__name__}"
+ )
+
+ items = _unwrap_items(config, data[config.data_key])
+ if items:
+ yield items
+
+ # `max_page` marks the last page of the filtered listing; an empty or short page also
+ # terminates defensively in case it's ever missing.
+ max_page = data.get("max_page")
+ if not items:
+ break
+ if isinstance(max_page, int) and page >= max_page:
+ break
+ if not isinstance(max_page, int) and len(items) < PAGE_SIZE:
+ break
+
+ page += 1
+ # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages are
+ # persisted); merge dedupes the re-pulled page on the primary key.
+ resumable_source_manager.save_state(OnepagecrmResumeConfig(page=page, modified_since=modified_since))
+
+
+def onepagecrm_source(
+ user_id: str,
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[OnepagecrmResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = ONEPAGECRM_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ user_id=user_id,
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ primary_keys=config.primary_keys,
+ sort_mode="asc",
+ 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,
+ )
+
+
+def check_access(user_id: str, api_key: str, path: str = DEFAULT_PROBE_PATH) -> tuple[int, Optional[str]]:
+ """Probe a single endpoint to validate the user ID / API key pair.
+
+ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a
+ connection problem, other HTTP status otherwise.
+ """
+ session = _make_session(user_id, api_key)
+ try:
+ response = session.get(f"{ONEPAGECRM_BASE_URL}{path}", params={"per_page": 1}, timeout=15)
+ except Exception as e:
+ return 0, f"Could not connect to OnePageCRM: {e}"
+
+ if response.status_code in (401, 403):
+ return response.status_code, None
+
+ if not response.ok:
+ return response.status_code, f"OnePageCRM returned HTTP {response.status_code}"
+
+ return 200, None
+
+
+def validate_credentials(user_id: str, api_key: str) -> tuple[bool, str | None]:
+ status, message = check_access(user_id, api_key)
+ if status == 200:
+ return True, None
+ if status in (401, 403):
+ return False, "Invalid OnePageCRM user ID or API key"
+ return False, message or "Could not validate OnePageCRM credentials"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/onepagecrm/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/onepagecrm/settings.py
new file mode 100644
index 000000000000..b53935ff8a1a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/onepagecrm/settings.py
@@ -0,0 +1,136 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# OnePageCRM timestamps are ISO 8601 strings (e.g. "2018-05-16T11:52:09Z"); the `modified_since`
+# list filter accepts a UNIX timestamp and returns only resources modified since that time.
+MODIFIED_AT_INCREMENTAL_FIELD: IncrementalField = {
+ "label": "modified_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "modified_at",
+ "field_type": IncrementalFieldType.DateTime,
+}
+
+
+@dataclass
+class OnepagecrmEndpointConfig:
+ name: str
+ path: str
+ # Key the record list is nested under in the response's `data` object (e.g.
+ # {"data": {"contacts": [...]}}). None means `data` itself is the list (users, statuses,
+ # lead_sources).
+ data_key: Optional[str]
+ # Singular key each record is wrapped under (e.g. {"contact": {...}}); None if records are
+ # returned unwrapped (lead_sources).
+ item_key: Optional[str]
+ # OnePageCRM object IDs are BSON ids unique across the account, so `id` is a safe primary key.
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # Whether the endpoint accepts page/per_page params. Config endpoints (users, statuses,
+ # lead_sources) return the full list in one response.
+ paginated: bool = True
+ # Whether the endpoint accepts sort_by/order params (every sortable endpoint here allows both
+ # created_at and modified_at).
+ supports_sort: bool = False
+ # Non-empty only where the API exposes the server-side `modified_since` filter.
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Stable creation-time field used for datetime partitioning. Never modified_at, which would
+ # rewrite partitions on every sync.
+ partition_key: Optional[str] = None
+
+
+# OnePageCRM API v3 list endpoints (https://developer.onepagecrm.com/api/). Contacts, deals,
+# actions, notes, calls, and meetings support incremental sync via the server-side
+# `modified_since` UNIX-timestamp filter; companies documents no `modified_since`, and the config
+# endpoints (users, statuses, lead_sources) are small unpaginated lists — all full refresh only.
+ONEPAGECRM_ENDPOINTS: dict[str, OnepagecrmEndpointConfig] = {
+ "contacts": OnepagecrmEndpointConfig(
+ name="contacts",
+ path="/contacts",
+ data_key="contacts",
+ item_key="contact",
+ supports_sort=True,
+ incremental_fields=[MODIFIED_AT_INCREMENTAL_FIELD],
+ partition_key="created_at",
+ ),
+ "companies": OnepagecrmEndpointConfig(
+ name="companies",
+ path="/companies",
+ data_key="companies",
+ item_key="company",
+ supports_sort=True,
+ partition_key="created_at",
+ ),
+ "deals": OnepagecrmEndpointConfig(
+ name="deals",
+ path="/deals",
+ data_key="deals",
+ item_key="deal",
+ supports_sort=True,
+ incremental_fields=[MODIFIED_AT_INCREMENTAL_FIELD],
+ partition_key="created_at",
+ ),
+ "actions": OnepagecrmEndpointConfig(
+ name="actions",
+ path="/actions",
+ data_key="actions",
+ item_key="action",
+ supports_sort=True,
+ incremental_fields=[MODIFIED_AT_INCREMENTAL_FIELD],
+ partition_key="created_at",
+ ),
+ "notes": OnepagecrmEndpointConfig(
+ name="notes",
+ path="/notes",
+ data_key="notes",
+ item_key="note",
+ supports_sort=True,
+ incremental_fields=[MODIFIED_AT_INCREMENTAL_FIELD],
+ partition_key="created_at",
+ ),
+ "calls": OnepagecrmEndpointConfig(
+ name="calls",
+ path="/calls",
+ data_key="calls",
+ item_key="call",
+ supports_sort=True,
+ incremental_fields=[MODIFIED_AT_INCREMENTAL_FIELD],
+ partition_key="created_at",
+ ),
+ "meetings": OnepagecrmEndpointConfig(
+ name="meetings",
+ path="/meetings",
+ data_key="meetings",
+ item_key="meeting",
+ supports_sort=True,
+ incremental_fields=[MODIFIED_AT_INCREMENTAL_FIELD],
+ partition_key="created_at",
+ ),
+ "users": OnepagecrmEndpointConfig(
+ name="users",
+ path="/users",
+ data_key=None,
+ item_key="user",
+ paginated=False,
+ ),
+ "statuses": OnepagecrmEndpointConfig(
+ name="statuses",
+ path="/statuses",
+ data_key=None,
+ item_key="status",
+ paginated=False,
+ ),
+ "lead_sources": OnepagecrmEndpointConfig(
+ name="lead_sources",
+ path="/lead_sources",
+ data_key=None,
+ item_key=None,
+ paginated=False,
+ ),
+}
+
+ENDPOINTS = tuple(ONEPAGECRM_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in ONEPAGECRM_ENDPOINTS.items() if config.incremental_fields
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/onepagecrm/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/onepagecrm/source.py
index d67cd7caaa6b..03a1f865b478 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/onepagecrm/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/onepagecrm/source.py
@@ -1,19 +1,43 @@
-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.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+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
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import OnepagecrmSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.onepagecrm.onepagecrm import (
+ OnepagecrmResumeConfig,
+ onepagecrm_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.onepagecrm.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ ONEPAGECRM_ENDPOINTS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class OnepagecrmSource(SimpleSource[OnepagecrmSourceConfig]):
+class OnepagecrmSource(ResumableSource[OnepagecrmSourceConfig, OnepagecrmResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.ONEPAGECRM
@@ -23,8 +47,100 @@ class OnepagecrmSource(SimpleSource[OnepagecrmSourceConfig]):
return SourceConfig(
name=SchemaExternalDataSourceType.ONEPAGECRM,
category=DataWarehouseSourceCategory.CRM,
- label="Onepagecrm",
+ label="OnePageCRM",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your OnePageCRM API credentials to pull your CRM data into the PostHog Data warehouse.
+
+You can find your User ID and API key in [OnePageCRM](https://app.onepagecrm.com) under **Apps & Integrations → API**. The key grants read access to your contacts, companies, deals, actions, notes, calls, meetings, users, statuses, and lead sources.
+""",
iconPath="/static/services/onepagecrm.png",
- fields=cast(list[FieldType], []),
+ docsUrl="https://posthog.com/docs/cdp/sources/onepagecrm",
+ keywords=["crm", "one page crm"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="user_id",
+ label="User ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
unreleasedSource=True,
)
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.onepagecrm.canonical_descriptions import ( # noqa: PLC0415
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://app.onepagecrm.com": "Your OnePageCRM user ID or API key is invalid or has been revoked. Check both under Apps & Integrations → API, then reconnect.",
+ "403 Client Error: Forbidden for url: https://app.onepagecrm.com": "Your OnePageCRM API key does not have access to this data. Check the key owner's account permissions, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: OnepagecrmSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=INCREMENTAL_FIELDS.get(endpoint) is not None,
+ supports_append=INCREMENTAL_FIELDS.get(endpoint) is not None,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ )
+ for endpoint in ENDPOINTS
+ ]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: OnepagecrmSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ # The API key grants account-wide read access, so a single probe validates every schema.
+ return validate_credentials(config.user_id, config.api_key)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[OnepagecrmResumeConfig]:
+ return ResumableSourceManager[OnepagecrmResumeConfig](inputs, OnepagecrmResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: OnepagecrmSourceConfig,
+ resumable_source_manager: ResumableSourceManager[OnepagecrmResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ if inputs.schema_name not in ONEPAGECRM_ENDPOINTS:
+ raise ValueError(f"Unknown OnePageCRM schema '{inputs.schema_name}'")
+
+ return onepagecrm_source(
+ user_id=config.user_id,
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ 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,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/onepagecrm/tests/test_onepagecrm.py b/products/warehouse_sources/backend/temporal/data_imports/sources/onepagecrm/tests/test_onepagecrm.py
new file mode 100644
index 000000000000..30ae2f448aef
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/onepagecrm/tests/test_onepagecrm.py
@@ -0,0 +1,261 @@
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+
+from unittest import mock
+
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.onepagecrm.onepagecrm import (
+ OnepagecrmResumeConfig,
+ _build_params,
+ _to_epoch,
+ get_rows,
+ modified_since_anchor,
+ onepagecrm_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.onepagecrm.settings import (
+ ENDPOINTS,
+ ONEPAGECRM_ENDPOINTS,
+)
+
+MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.onepagecrm.onepagecrm"
+
+
+def _make_manager(resume_state: OnepagecrmResumeConfig | 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 _response(body: dict[str, Any], status_code: int = 200) -> mock.MagicMock:
+ resp = mock.MagicMock()
+ resp.status_code = status_code
+ resp.ok = status_code < 400
+ resp.json.return_value = body
+ return resp
+
+
+def _list_page(
+ data_key: str,
+ item_key: str,
+ records: list[dict[str, Any]],
+ page: int,
+ max_page: Optional[int],
+) -> dict[str, Any]:
+ return {
+ "status": 0,
+ "message": "OK",
+ "data": {
+ data_key: [{item_key: record} for record in records],
+ "total_count": len(records),
+ "page": page,
+ "per_page": 100,
+ "max_page": max_page,
+ },
+ }
+
+
+class TestToEpoch:
+ @parameterized.expand(
+ [
+ (None, None),
+ (True, None),
+ (1700000000, 1700000000),
+ (1700000000.9, 1700000000),
+ ("1700000000", 1700000000),
+ ("2023-11-14T22:13:20Z", 1700000000),
+ ("2023-11-14T22:13:20+00:00", 1700000000),
+ (datetime(2023, 11, 14, 22, 13, 20, tzinfo=UTC), 1700000000),
+ (datetime(2023, 11, 14, 22, 13, 20), 1700000000),
+ (date(2023, 11, 15), int(datetime(2023, 11, 15, tzinfo=UTC).timestamp())),
+ ("not-a-timestamp", None),
+ ],
+ )
+ def test_to_epoch_values(self, value, expected):
+ assert _to_epoch(value) == expected
+
+ def test_anchor_backs_off_one_second(self):
+ assert modified_since_anchor(1700000000) == "1699999999"
+ assert modified_since_anchor(None) is None
+
+
+class TestBuildParams:
+ def test_incremental_run_sorts_by_cursor_and_filters(self):
+ params = _build_params(
+ ONEPAGECRM_ENDPOINTS["contacts"], page=3, modified_since="1699999999", should_use_incremental_field=True
+ )
+ assert params == {
+ "page": 3,
+ "per_page": 100,
+ "sort_by": "modified_at",
+ "order": "asc",
+ "modified_since": "1699999999",
+ }
+
+ def test_full_refresh_sorts_by_stable_creation_field(self):
+ params = _build_params(
+ ONEPAGECRM_ENDPOINTS["contacts"], page=1, modified_since=None, should_use_incremental_field=False
+ )
+ assert params == {"page": 1, "per_page": 100, "sort_by": "created_at", "order": "asc"}
+
+ def test_unpaginated_config_endpoint_sends_no_params(self):
+ params = _build_params(
+ ONEPAGECRM_ENDPOINTS["users"], page=1, modified_since=None, should_use_incremental_field=False
+ )
+ assert params == {}
+
+
+class TestGetRows:
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_paginates_until_max_page_and_unwraps_records(self, mock_session):
+ pages = [
+ _list_page("contacts", "contact", [{"id": "a1"}, {"id": "a2"}], page=1, max_page=2),
+ _list_page("contacts", "contact", [{"id": "a3"}], page=2, max_page=2),
+ ]
+ mock_session.return_value.get.side_effect = [_response(p) for p in pages]
+
+ manager = _make_manager()
+ batches = list(get_rows("uid", "key", "contacts", mock.MagicMock(), manager))
+
+ assert [item["id"] for batch in batches for item in batch] == ["a1", "a2", "a3"]
+ assert mock_session.return_value.get.call_count == 2
+ manager.save_state.assert_called_once_with(OnepagecrmResumeConfig(page=2, modified_since=None))
+
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_incremental_run_pins_anchor_across_pages(self, mock_session):
+ pages = [
+ _list_page("deals", "deal", [{"id": "d1"}], page=1, max_page=2),
+ _list_page("deals", "deal", [{"id": "d2"}], page=2, max_page=2),
+ ]
+ mock_session.return_value.get.side_effect = [_response(p) for p in pages]
+
+ manager = _make_manager()
+ list(
+ get_rows(
+ "uid",
+ "key",
+ "deals",
+ mock.MagicMock(),
+ manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=1700000000,
+ )
+ )
+
+ for call in mock_session.return_value.get.call_args_list:
+ assert call.kwargs["params"]["modified_since"] == "1699999999"
+ manager.save_state.assert_called_once_with(OnepagecrmResumeConfig(page=2, modified_since="1699999999"))
+
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_resumes_from_saved_page_and_saved_anchor(self, mock_session):
+ mock_session.return_value.get.return_value = _response(
+ _list_page("deals", "deal", [{"id": "d9"}], page=5, max_page=5)
+ )
+ manager = _make_manager(OnepagecrmResumeConfig(page=5, modified_since="1600000000"))
+
+ list(
+ get_rows(
+ "uid",
+ "key",
+ "deals",
+ mock.MagicMock(),
+ manager,
+ should_use_incremental_field=True,
+ # A fresher watermark must NOT replace the saved anchor: page numbers are only
+ # stable for the query the run started with.
+ db_incremental_field_last_value=1700000000,
+ )
+ )
+
+ params = mock_session.return_value.get.call_args.kwargs["params"]
+ assert params["page"] == 5
+ assert params["modified_since"] == "1600000000"
+
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_short_page_terminates_when_max_page_missing(self, mock_session):
+ body = _list_page("contacts", "contact", [{"id": "a1"}], page=1, max_page=None)
+ body["data"].pop("max_page")
+ mock_session.return_value.get.return_value = _response(body)
+
+ manager = _make_manager()
+ batches = list(get_rows("uid", "key", "contacts", mock.MagicMock(), manager))
+
+ assert [item["id"] for batch in batches for item in batch] == ["a1"]
+ assert mock_session.return_value.get.call_count == 1
+ manager.save_state.assert_not_called()
+
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_empty_first_page_stops_without_state(self, mock_session):
+ mock_session.return_value.get.return_value = _response(_list_page("contacts", "contact", [], 1, 1))
+
+ manager = _make_manager()
+ assert list(get_rows("uid", "key", "contacts", mock.MagicMock(), manager)) == []
+ manager.save_state.assert_not_called()
+
+ @parameterized.expand(
+ [
+ ("users", {"data": [{"user": {"id": "u1"}}, {"user": {"id": "u2"}}]}, ["u1", "u2"]),
+ ("statuses", {"data": [{"status": {"id": "s1"}}]}, ["s1"]),
+ ("lead_sources", {"data": [{"id": "advertisement"}, {"id": "web"}]}, ["advertisement", "web"]),
+ ]
+ )
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_config_endpoints_yield_bare_array_records(self, endpoint, body, expected_ids, mock_session):
+ mock_session.return_value.get.return_value = _response(body)
+
+ manager = _make_manager()
+ batches = list(get_rows("uid", "key", endpoint, mock.MagicMock(), manager))
+
+ assert [item["id"] for batch in batches for item in batch] == expected_ids
+ assert mock_session.return_value.get.call_count == 1
+
+
+class TestValidateCredentials:
+ @parameterized.expand(
+ [
+ (200, True, None),
+ (401, False, "Invalid OnePageCRM user ID or API key"),
+ (403, False, "Invalid OnePageCRM user ID or API key"),
+ (500, False, "OnePageCRM returned HTTP 500"),
+ ]
+ )
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_status_mapping(self, status_code, expected_valid, expected_message, mock_session):
+ mock_session.return_value.get.return_value = _response({}, status_code=status_code)
+
+ valid, message = validate_credentials("uid", "key")
+
+ assert valid is expected_valid
+ assert message == expected_message
+
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_connection_error_reports_failure(self, mock_session):
+ mock_session.return_value.get.side_effect = Exception("boom")
+
+ valid, message = validate_credentials("uid", "key")
+
+ assert valid is False
+ assert message is not None and "Could not connect to OnePageCRM" in message
+
+
+class TestOnepagecrmSourceResponse:
+ @parameterized.expand([(endpoint,) for endpoint in ENDPOINTS])
+ def test_response_metadata_per_endpoint(self, endpoint):
+ config = ONEPAGECRM_ENDPOINTS[endpoint]
+ response = onepagecrm_source("uid", "key", endpoint, mock.MagicMock(), _make_manager())
+
+ assert response.name == endpoint
+ assert response.primary_keys == config.primary_keys
+ assert response.sort_mode == "asc"
+ if config.partition_key:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [config.partition_key]
+ else:
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+
+ @parameterized.expand([(name,) for name, c in ONEPAGECRM_ENDPOINTS.items() if c.partition_key])
+ def test_partition_keys_are_stable_creation_fields(self, endpoint):
+ assert ONEPAGECRM_ENDPOINTS[endpoint].partition_key == "created_at"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/onepagecrm/tests/test_onepagecrm_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/onepagecrm/tests/test_onepagecrm_source.py
new file mode 100644
index 000000000000..590e4fb4c967
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/onepagecrm/tests/test_onepagecrm_source.py
@@ -0,0 +1,146 @@
+import pytest
+from unittest import mock
+
+from parameterized import parameterized
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import OnepagecrmSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.onepagecrm.onepagecrm import (
+ OnepagecrmResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.onepagecrm.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.onepagecrm.source import OnepagecrmSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestOnepagecrmSource:
+ def setup_method(self) -> None:
+ self.source = OnepagecrmSource()
+ self.team_id = 123
+ self.config = OnepagecrmSourceConfig(user_id="uid-1", api_key="key-1")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.ONEPAGECRM
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+ assert config.name.value == "Onepagecrm"
+ assert config.label == "OnePageCRM"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/onepagecrm"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["user_id", "api_key"]
+
+ def test_api_key_field_is_secret_password(self) -> None:
+ config = self.source.get_source_config
+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+ assert field.secret is True
+ assert field.required is True
+
+ def test_no_connection_host_fields(self) -> None:
+ # The user ID is only a Basic-auth username against the hardcoded API host, so there is no
+ # field an editor could retarget to reuse a preserved key against another server.
+ assert self.source.connection_host_fields == []
+
+ def test_lists_tables_without_credentials(self) -> None:
+ assert self.source.lists_tables_without_credentials is True
+
+ def test_get_schemas_advertises_incremental_only_where_filterable(self) -> None:
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+ assert set(schemas) == set(ENDPOINTS)
+ for name, schema in schemas.items():
+ if name in INCREMENTAL_FIELDS:
+ assert schema.supports_incremental is True
+ assert [f["field"] for f in schema.incremental_fields] == ["modified_at"]
+ else:
+ assert schema.supports_incremental is False
+ assert schema.incremental_fields == []
+ # companies has no modified_since filter; config lists aren't filterable either.
+ assert schemas["companies"].supports_incremental is False
+ assert schemas["contacts"].supports_incremental is True
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["deals", "nope"])
+ assert [s.name for s in schemas] == ["deals"]
+
+ def test_documented_tables_render_for_public_docs(self) -> None:
+ tables = self.source.get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+
+ @parameterized.expand(
+ [
+ ("401 Client Error: Unauthorized for url: https://app.onepagecrm.com/api/v3/contacts",),
+ ("403 Client Error: Forbidden for url: https://app.onepagecrm.com/api/v3/deals",),
+ ]
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable)
+
+ @parameterized.expand(
+ [
+ ("500 Server Error: Internal Server Error for url: https://app.onepagecrm.com/api/v3/contacts",),
+ ("429 Client Error: Too Many Requests for url: https://app.onepagecrm.com/api/v3/deals",),
+ ]
+ )
+ def test_non_retryable_errors_ignore_transient(self, unrelated_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert not any(key in unrelated_error for key in non_retryable)
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.onepagecrm.source.validate_credentials"
+ )
+ def test_validate_credentials_delegates_to_shared_helper(self, mock_validate: mock.MagicMock) -> None:
+ mock_validate.return_value = (False, "Invalid OnePageCRM user ID or API key")
+ result = self.source.validate_credentials(self.config, self.team_id)
+ assert result == (False, "Invalid OnePageCRM user ID or API key")
+ mock_validate.assert_called_once_with("uid-1", "key-1")
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is OnepagecrmResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.onepagecrm.source.onepagecrm_source")
+ def test_source_for_pipeline_plumbs_incremental_arguments(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "contacts"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = 1700000000
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["user_id"] == "uid-1"
+ assert kwargs["api_key"] == "key-1"
+ assert kwargs["endpoint"] == "contacts"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == 1700000000
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.onepagecrm.source.onepagecrm_source")
+ def test_source_for_pipeline_drops_watermark_on_full_refresh(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "contacts"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = 1700000000
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["should_use_incremental_field"] is False
+ assert kwargs["db_incremental_field_last_value"] is None
+
+ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "not_a_table"
+ with pytest.raises(ValueError, match="Unknown OnePageCRM schema 'not_a_table'"):
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)