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 less_annoying_crm import source (#67836)

Tom Owers79d59b92c4e5
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 ae1c89162b23..35a2b3b348b4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -199,6 +199,7 @@ the row lists both.
| lattice | HTTP | requests | ✅ |
| leadfeeder | HTTP | requests | ✅ |
| lemlist | HTTP | requests | ✅ |
+| less_annoying_crm | HTTP | requests | ✅ |
| lightspeed_retail | HTTP | requests | ✅ |
| linear | HTTP | requests | ✅ |
| lever | HTTP | requests | ✅ |
@@ -508,7 +509,6 @@ doesn't conflict with concurrent PRs.
- kyve
- leexi
- lemon_squeezy
-- less_annoying_crm
- lever
- liana
- lightfield
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 a79e1d4f7462..82d289a906ae 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
@@ -1820,7 +1820,7 @@ class LemonSqueezySourceConfig(config.Config):
@config.config
class LessAnnoyingCRMSourceConfig(config.Config):
- pass
+ api_key: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/less_annoying_crm/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/less_annoying_crm/canonical_descriptions.py
new file mode 100644
index 000000000000..a1d5beeed240
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/less_annoying_crm/canonical_descriptions.py
@@ -0,0 +1,80 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Descriptions taken from the Less Annoying CRM v2 API docs
+# (https://account.lessannoyingcrm.com/api_docs/v2). Keyed by the schema/endpoint name from
+# `get_schemas`. Partial coverage is fine — anything missing falls back to LLM enrichment.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "users": {
+ "description": "Users on the Less Annoying CRM account.",
+ "docs_url": "https://account.lessannoyingcrm.com/api_docs/v2/Settings_Functions/Users",
+ "columns": {
+ "UserId": "Unique identifier for the user.",
+ "FirstName": "The user's first name.",
+ "LastName": "The user's last name.",
+ "Email": "The user's email address.",
+ "Timezone": "The user's configured timezone.",
+ },
+ },
+ "teams": {
+ "description": "Teams configured on the account, used to group and share records between users.",
+ "docs_url": "https://account.lessannoyingcrm.com/api_docs/v2/Core_Functions/Teams",
+ "columns": {
+ "TeamId": "Unique identifier for the team.",
+ "Name": "Display name of the team.",
+ "DateCreated": "When the team was created.",
+ },
+ },
+ "contacts": {
+ "description": "Contacts and companies in the CRM.",
+ "docs_url": "https://account.lessannoyingcrm.com/api_docs/v2/Core_Functions/Contacts",
+ "columns": {
+ "ContactId": "Unique identifier for the contact or company.",
+ "IsCompany": "True when the record is a company rather than an individual contact.",
+ "CompanyId": "Identifier of the company this contact is associated with, if any.",
+ "Name": "Structured name of the contact (first/last and related fields).",
+ "DateCreated": "When the contact was created.",
+ "LastUpdate": "When the contact was last modified.",
+ },
+ },
+ "tasks": {
+ "description": "Tasks (to-dos) tracked in the CRM, optionally linked to a contact.",
+ "docs_url": "https://account.lessannoyingcrm.com/api_docs/v2/Core_Functions/Tasks",
+ "columns": {
+ "TaskId": "Unique identifier for the task.",
+ "Name": "Short description of the task.",
+ "DueDate": "The date the task is due.",
+ "IsCompleted": "Whether the task has been completed.",
+ "DateCompleted": "When the task was completed, if applicable.",
+ "ContactId": "Identifier of the contact the task is linked to, if any.",
+ "AssignedTo": "Identifier of the user the task is assigned to.",
+ "DateCreated": "When the task was created.",
+ },
+ },
+ "notes": {
+ "description": "Notes recorded against contacts and companies in the CRM.",
+ "docs_url": "https://account.lessannoyingcrm.com/api_docs/v2/Core_Functions/Notes",
+ "columns": {
+ "NoteId": "Unique identifier for the note.",
+ "ContactId": "Identifier of the contact the note belongs to.",
+ "Note": "The text body of the note.",
+ "UserId": "Identifier of the user who created the note.",
+ "DateCreated": "When the note was created.",
+ "DateDisplayedInHistory": "The date the note is displayed under in the contact's history.",
+ },
+ },
+ "events": {
+ "description": "Calendar events, optionally linked to contacts.",
+ "docs_url": "https://account.lessannoyingcrm.com/api_docs/v2/Core_Functions/Events",
+ "columns": {
+ "EventId": "Unique identifier for the event.",
+ "Name": "Title of the event.",
+ "Date": "The date of the event.",
+ "StartTime": "Start time of the event.",
+ "EndTime": "End time of the event.",
+ "DateCreated": "When the event was created.",
+ "DateUpdated": "When the event was last modified.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/less_annoying_crm/less_annoying_crm.py b/products/warehouse_sources/backend/temporal/data_imports/sources/less_annoying_crm/less_annoying_crm.py
new file mode 100644
index 000000000000..697b9d9808a5
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/less_annoying_crm/less_annoying_crm.py
@@ -0,0 +1,215 @@
+import dataclasses
+from collections.abc import Iterator
+from typing import Any
+
+import requests
+import structlog
+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.less_annoying_crm.settings import (
+ LESS_ANNOYING_CRM_ENDPOINTS,
+ WIDE_WINDOW_END,
+ WIDE_WINDOW_START,
+ LessAnnoyingCRMEndpointConfig,
+)
+
+# Single flat RPC endpoint — every call is a POST here with a {"Function", "Parameters"} body.
+LESS_ANNOYING_CRM_BASE_URL = "https://api.lessannoyingcrm.com/v2/"
+
+# The API caps MaxNumberOfResults at 10,000. We page at 500 (the API default) so each yielded page
+# stays small; the pipeline batches across pages so a smaller page size costs only extra requests.
+PAGE_SIZE = 500
+
+REQUEST_TIMEOUT_SECONDS = 60
+
+logger = structlog.get_logger(__name__)
+
+
+class LessAnnoyingCRMRetryableError(Exception):
+ """Raised for transient failures (429 / 5xx / connection) that are worth retrying."""
+
+
+class LessAnnoyingCRMError(Exception):
+ """Raised for terminal API errors. Carries the API's ErrorDescription so credential/permission
+ failures surface a friendly, matchable message (LACRM returns these as HTTP 400 with a JSON body,
+ not 401/403)."""
+
+
+class LessAnnoyingCRMResumeConfig:
+ # Next page number to request. Full refresh only, so page number is the entire cursor: on resume
+ # we re-request the last saved page (merge dedupes on the primary key).
+ page: int = 1
+
+
+def _get_headers(api_key: str) -> dict[str, str]:
+ # LACRM sends the raw API key as the Authorization header value — no Bearer prefix, no OAuth.
+ return {"Authorization": api_key, "Content-Type": "application/json"}
+
+
+def _extract_records(data: Any, result_path: list[str]) -> list[dict[str, Any]]:
+ """Walk ``result_path`` to the record collection and normalize it to a list of dicts.
+
+ LACRM returns list endpoints under ``Results`` (or a bare array for users/teams). GetTasks nests
+ its results as an object keyed by id, so a dict at the leaf is expanded to its values."""
+ node = data
+ for key in result_path:
+ if not isinstance(node, dict):
+ return []
+ node = node.get(key)
+ if isinstance(node, dict):
+ return [v for v in node.values() if isinstance(v, dict)]
+ if isinstance(node, list):
+ return [item for item in node if isinstance(item, dict)]
+ return []
+
+
+def _is_error_body(data: Any) -> bool:
+ return isinstance(data, dict) and ("ErrorCode" in data or "ErrorDescription" in data)
+
+
+@retry(
+ retry=retry_if_exception_type(
+ (
+ LessAnnoyingCRMRetryableError,
+ requests.ReadTimeout,
+ requests.ConnectionError,
+ requests.exceptions.ChunkedEncodingError,
+ )
+ ),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _call_function(
+ session: requests.Session,
+ api_key: str,
+ function: str,
+ parameters: dict[str, Any],
+ logger: FilteringBoundLogger,
+) -> Any:
+ response = session.post(
+ LESS_ANNOYING_CRM_BASE_URL,
+ headers=_get_headers(api_key),
+ json={"Function": function, "Parameters": parameters},
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise LessAnnoyingCRMRetryableError(
+ f"Less Annoying CRM API error (retryable): status={response.status_code}, function={function}"
+ )
+
+ # Errors (including invalid credentials) come back as HTTP 400 with a JSON body carrying
+ # ErrorCode / ErrorDescription. Surface the description so it can be matched as non-retryable.
+ try:
+ data = response.json()
+ except ValueError:
+ data = None
+
+ if not response.ok or _is_error_body(data):
+ description = data.get("ErrorDescription") if isinstance(data, dict) else None
+ message = description or f"HTTP {response.status_code}"
+ logger.error(f"Less Annoying CRM API error: function={function}, status={response.status_code}, body={message}")
+ raise LessAnnoyingCRMError(f"Less Annoying CRM API error for {function}: {message}")
+
+ return data
+
+
+def _build_parameters(config: LessAnnoyingCRMEndpointConfig, page: int) -> dict[str, Any]:
+ parameters: dict[str, Any] = {}
+ if config.paginated:
+ parameters["Page"] = page
+ parameters["MaxNumberOfResults"] = PAGE_SIZE
+ if config.date_window_params:
+ start_param, end_param = config.date_window_params
+ parameters[start_param] = WIDE_WINDOW_START
+ parameters[end_param] = WIDE_WINDOW_END
+ if config.sort_by:
+ parameters["SortBy"] = config.sort_by
+ if config.sort_direction:
+ parameters["SortDirection"] = config.sort_direction
+ return parameters
+
+
+def validate_credentials(api_key: str) -> bool:
+ """Confirm the API key is genuine with the cheapest possible probe.
+
+ ``GetUser`` takes no parameters and always returns the authenticated user, so it validates the
+ key without touching any specific resource's read permissions."""
+ try:
+ session = make_tracked_session(redact_values=(api_key,))
+ data = _call_function(session, api_key, "GetUser", {}, logger=logger)
+ return not _is_error_body(data)
+ except Exception:
+ return False
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[LessAnnoyingCRMResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ config = LESS_ANNOYING_CRM_ENDPOINTS[endpoint]
+ # Redact the key so it can never land in tracked HTTP request/response samples.
+ session = make_tracked_session(redact_values=(api_key,))
+
+ # Non-paginated reference tables (users, teams) are a single call.
+ if not config.paginated:
+ data = _call_function(session, api_key, config.function, _build_parameters(config, page=1), logger)
+ records = _extract_records(data, config.result_path)
+ if records:
+ yield records
+ return
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ page = resume.page if resume else 1
+
+ while True:
+ data = _call_function(session, api_key, config.function, _build_parameters(config, page), logger)
+ records = _extract_records(data, config.result_path)
+
+ if records:
+ yield records
+
+ # LACRM signals more pages via HasMoreResults. Fall back to a short-page heuristic if the flag
+ # is absent so we never loop forever on an endpoint that omits it.
+ has_more = data.get("HasMoreResults") if isinstance(data, dict) else None
+ if has_more is None:
+ has_more = len(records) >= PAGE_SIZE
+ if not has_more or not records:
+ break
+
+ page += 1
+ # Save AFTER yielding so a crash re-yields the last page rather than skipping it.
+ resumable_source_manager.save_state(LessAnnoyingCRMResumeConfig(page=page))
+
+
+def less_annoying_crm_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[LessAnnoyingCRMResumeConfig],
+) -> SourceResponse:
+ config = LESS_ANNOYING_CRM_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ 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,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/less_annoying_crm/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/less_annoying_crm/settings.py
new file mode 100644
index 000000000000..7679149f82e0
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/less_annoying_crm/settings.py
@@ -0,0 +1,102 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.types import IncrementalField
+
+# Less Annoying CRM's v2 API is RPC-shaped: every call is a POST to a single endpoint carrying a
+# `Function` name and a `Parameters` object. Each endpoint below maps a warehouse table to the LACRM
+# function that returns it, plus how to page through and where the records live in the response.
+
+
+@dataclass
+class LessAnnoyingCRMEndpointConfig:
+ name: str
+ # LACRM Function name sent in the request body (e.g. "GetContacts").
+ function: str
+ # Keys to walk in the JSON response to reach the record collection. An empty list means the
+ # response body is itself the array of records (GetUsers / GetTeams return a bare JSON array).
+ result_path: list[str]
+ primary_keys: list[str]
+ # Whether the function pages via Page / MaxNumberOfResults. Small reference tables (users, teams)
+ # return everything in one call and reject / ignore pagination params, so they're single-shot.
+ paginated: bool = True
+ # Stable creation-time field used for datetime partitioning. Never a mutable field like LastUpdate.
+ partition_key: Optional[str] = None
+ # (start_param, end_param) for functions that REQUIRE a date window (GetTasks). We send a very
+ # wide window so a full refresh still returns every row. These filter on the record's domain date
+ # (due/event date), NOT on a modification timestamp — see the incremental note below.
+ date_window_params: Optional[tuple[str, str]] = None
+ # Sort params to request a stable ascending order while paging. Which are accepted varies per
+ # function: only GetContacts takes a `SortBy` field (e.g. DateCreated); GetTasks and GetNotes
+ # expose `SortDirection` alone (their sort column is fixed by the API), so we set direction
+ # without a `SortBy` there. Sending an unsupported `SortBy` to those functions would be rejected.
+ sort_by: Optional[str] = None
+ sort_direction: Optional[str] = None
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ should_sync_default: bool = True
+
+
+# A date window wide enough to cover every plausible task/event date on a full refresh. GetTasks
+# requires StartDate/EndDate, so we always send this range rather than a modification-time cutoff.
+WIDE_WINDOW_START = "1970-01-01T00:00:00Z"
+WIDE_WINDOW_END = "2200-01-01T00:00:00Z"
+
+
+LESS_ANNOYING_CRM_ENDPOINTS: dict[str, LessAnnoyingCRMEndpointConfig] = {
+ "users": LessAnnoyingCRMEndpointConfig(
+ name="users",
+ function="GetUsers",
+ result_path=[],
+ primary_keys=["UserId"],
+ paginated=False,
+ ),
+ "teams": LessAnnoyingCRMEndpointConfig(
+ name="teams",
+ function="GetTeams",
+ result_path=[],
+ primary_keys=["TeamId"],
+ paginated=False,
+ ),
+ "contacts": LessAnnoyingCRMEndpointConfig(
+ name="contacts",
+ function="GetContacts",
+ result_path=["Results"],
+ primary_keys=["ContactId"],
+ partition_key="DateCreated",
+ sort_by="DateCreated",
+ sort_direction="Ascending",
+ ),
+ "tasks": LessAnnoyingCRMEndpointConfig(
+ name="tasks",
+ function="GetTasks",
+ result_path=["Results"],
+ primary_keys=["TaskId"],
+ partition_key="DateCreated",
+ date_window_params=("StartDate", "EndDate"),
+ sort_direction="Ascending",
+ ),
+ "notes": LessAnnoyingCRMEndpointConfig(
+ name="notes",
+ function="GetNotes",
+ result_path=["Results"],
+ primary_keys=["NoteId"],
+ partition_key="DateCreated",
+ sort_direction="Ascending",
+ ),
+ "events": LessAnnoyingCRMEndpointConfig(
+ name="events",
+ function="GetEvents",
+ result_path=["Results"],
+ primary_keys=["EventId"],
+ partition_key="DateCreated",
+ ),
+}
+
+ENDPOINTS = tuple(LESS_ANNOYING_CRM_ENDPOINTS.keys())
+
+# Every endpoint ships full refresh. LACRM exposes no server-side "modified since" filter: contacts
+# can only be sorted by LastUpdate (not filtered), and the date windows on GetTasks/GetEvents/GetNotes
+# filter on the record's domain date (due/event/entry date), not on a modification timestamp — so they
+# can't drive a correct incremental cursor. Enabling incremental would need live verification against a
+# real account, so we intentionally advertise no incremental fields for now.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: [] for name in LESS_ANNOYING_CRM_ENDPOINTS}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/less_annoying_crm/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/less_annoying_crm/source.py
index 2369c6356f62..eb4c6d799910 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/less_annoying_crm/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/less_annoying_crm/source.py
@@ -1,21 +1,47 @@
-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 (
LessAnnoyingCRMSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.less_annoying_crm.less_annoying_crm import (
+ LessAnnoyingCRMResumeConfig,
+ less_annoying_crm_source,
+ validate_credentials as validate_less_annoying_crm_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.less_annoying_crm.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ LESS_ANNOYING_CRM_ENDPOINTS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class LessAnnoyingCRMSource(SimpleSource[LessAnnoyingCRMSourceConfig]):
+class LessAnnoyingCRMSource(ResumableSource[LessAnnoyingCRMSourceConfig, LessAnnoyingCRMResumeConfig]):
+ # `get_schemas` iterates a static endpoint catalog with no I/O, so the table list is safe to
+ # render in public docs without credentials.
+ lists_tables_without_credentials = True
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.LESSANNOYINGCRM
@@ -26,7 +52,92 @@ class LessAnnoyingCRMSource(SimpleSource[LessAnnoyingCRMSourceConfig]):
name=SchemaExternalDataSourceType.LESS_ANNOYING_CRM,
category=DataWarehouseSourceCategory.CRM,
label="Less Annoying CRM",
+ caption="""Enter your Less Annoying CRM API key to pull your CRM data into the PostHog Data warehouse.
+
+Create an API key on the [Programmer API settings page](https://account.lessannoyingcrm.com/app/Settings/Api). Grant the key **read** access — the tables sync via the `GetUsers`, `GetTeams`, `GetContacts`, `GetTasks`, `GetNotes` and `GetEvents` functions.
+
+API keys can't be retrieved after creation, so store the key somewhere safe when you create it.""",
iconPath="/static/services/less_annoying_crm.png",
- fields=cast(list[FieldType], []),
+ docsUrl="https://posthog.com/docs/cdp/sources/less-annoying-crm",
+ keywords=["lacrm", "less annoying"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
)
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.less_annoying_crm.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # LACRM returns credential/permission failures as HTTP 400 with an ErrorDescription, which
+ # the transport re-raises verbatim. Retrying can never satisfy a bad key, so stop the sync.
+ "Invalid credentials": "Your Less Annoying CRM API key is invalid or has been disabled. Create a new API key in your account's Programmer API settings, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: LessAnnoyingCRMSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ # LACRM has no server-side modified-since filter, so every table is full refresh only.
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ detected_primary_keys=LESS_ANNOYING_CRM_ENDPOINTS[endpoint].primary_keys,
+ should_sync_default=LESS_ANNOYING_CRM_ENDPOINTS[endpoint].should_sync_default,
+ )
+ 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: LessAnnoyingCRMSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_less_annoying_crm_credentials(config.api_key):
+ return True, None
+
+ return False, "Invalid Less Annoying CRM API key"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[LessAnnoyingCRMResumeConfig]:
+ return ResumableSourceManager[LessAnnoyingCRMResumeConfig](inputs, LessAnnoyingCRMResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: LessAnnoyingCRMSourceConfig,
+ resumable_source_manager: ResumableSourceManager[LessAnnoyingCRMResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return less_annoying_crm_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/less_annoying_crm/tests/test_less_annoying_crm.py b/products/warehouse_sources/backend/temporal/data_imports/sources/less_annoying_crm/tests/test_less_annoying_crm.py
new file mode 100644
index 000000000000..53bad2c0cc3a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/less_annoying_crm/tests/test_less_annoying_crm.py
@@ -0,0 +1,221 @@
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.less_annoying_crm import less_annoying_crm
+from products.warehouse_sources.backend.temporal.data_imports.sources.less_annoying_crm.less_annoying_crm import (
+ PAGE_SIZE,
+ LessAnnoyingCRMError,
+ LessAnnoyingCRMResumeConfig,
+ LessAnnoyingCRMRetryableError,
+ _build_parameters,
+ _extract_records,
+ _is_error_body,
+ get_rows,
+ less_annoying_crm_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.less_annoying_crm.settings import (
+ ENDPOINTS,
+ LESS_ANNOYING_CRM_ENDPOINTS,
+)
+
+MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.less_annoying_crm.less_annoying_crm"
+
+LOGGER = MagicMock()
+
+
+def _response(status_code: int = 200, body: Any = None) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.ok = 200 <= status_code < 300
+ if body is None:
+ response.json.side_effect = ValueError("no json")
+ else:
+ response.json.return_value = body
+ return response
+
+
+def _session_returning(*responses: MagicMock) -> MagicMock:
+ session = MagicMock()
+ session.post.side_effect = list(responses)
+ return session
+
+
+def _manager(resume: LessAnnoyingCRMResumeConfig | None = None) -> MagicMock:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = resume is not None
+ manager.load_state.return_value = resume
+ return manager
+
+
+class TestExtractRecords:
+ @pytest.mark.parametrize(
+ ("data", "result_path", "expected"),
+ [
+ # Bare top-level array (users / teams).
+ ([{"UserId": "1"}, {"UserId": "2"}], [], [{"UserId": "1"}, {"UserId": "2"}]),
+ # Wrapped list (contacts / notes / events).
+ ({"Results": [{"ContactId": "1"}]}, ["Results"], [{"ContactId": "1"}]),
+ # Object keyed by id (GetTasks) — expand to values.
+ (
+ {"Results": {"a": {"TaskId": "a"}, "b": {"TaskId": "b"}}},
+ ["Results"],
+ [{"TaskId": "a"}, {"TaskId": "b"}],
+ ),
+ # Missing key yields nothing rather than raising.
+ ({"Other": []}, ["Results"], []),
+ # Empty results.
+ ({"Results": []}, ["Results"], []),
+ # Non-collection leaf.
+ ({"Results": "nope"}, ["Results"], []),
+ ],
+ )
+ def test_extract_records(self, data: Any, result_path: list[str], expected: list[dict[str, Any]]) -> None:
+ assert _extract_records(data, result_path) == expected
+
+
+class TestIsErrorBody:
+ @pytest.mark.parametrize(
+ ("data", "expected"),
+ [
+ ({"ErrorCode": "x", "ErrorDescription": "Invalid credentials."}, True),
+ ({"ErrorDescription": "boom"}, True),
+ ({"Results": []}, False),
+ ([{"UserId": "1"}], False),
+ (None, False),
+ ],
+ )
+ def test_is_error_body(self, data: Any, expected: bool) -> None:
+ assert _is_error_body(data) is expected
+
+
+class TestBuildParameters:
+ def test_paginated_endpoint_sends_page_and_size(self) -> None:
+ params = _build_parameters(LESS_ANNOYING_CRM_ENDPOINTS["contacts"], page=3)
+ assert params["Page"] == 3
+ assert params["MaxNumberOfResults"] == PAGE_SIZE
+ assert params["SortBy"] == "DateCreated"
+ assert params["SortDirection"] == "Ascending"
+
+ def test_non_paginated_endpoint_omits_pagination(self) -> None:
+ params = _build_parameters(LESS_ANNOYING_CRM_ENDPOINTS["users"], page=1)
+ assert "Page" not in params
+ assert "MaxNumberOfResults" not in params
+
+ def test_required_date_window_is_always_sent(self) -> None:
+ params = _build_parameters(LESS_ANNOYING_CRM_ENDPOINTS["tasks"], page=1)
+ assert "StartDate" in params
+ assert "EndDate" in params
+ # A wide window so a full refresh still returns every task.
+ assert params["StartDate"] < params["EndDate"]
+
+
+class TestCallFunction:
+ def test_success_returns_json(self) -> None:
+ session = _session_returning(_response(200, {"Results": [{"ContactId": "1"}]}))
+ data = less_annoying_crm._call_function(session, "key", "GetContacts", {"Page": 1}, LOGGER)
+ assert data == {"Results": [{"ContactId": "1"}]}
+
+ @pytest.mark.parametrize("status", [429, 500, 502, 503])
+ def test_retryable_statuses_raise_retryable(self, status: int) -> None:
+ session = _session_returning(*[_response(status) for _ in range(5)])
+ # Skip tenacity's real backoff sleeps so the test stays fast.
+ with patch("time.sleep"), pytest.raises(LessAnnoyingCRMRetryableError):
+ less_annoying_crm._call_function(session, "key", "GetContacts", {}, LOGGER)
+
+ def test_error_body_surfaces_description(self) -> None:
+ # LACRM returns credential failures as HTTP 400 with a JSON error body.
+ session = _session_returning(
+ _response(400, {"ErrorCode": "x", "ErrorDescription": "Invalid credentials. Please make sure."})
+ )
+ with pytest.raises(LessAnnoyingCRMError, match="Invalid credentials"):
+ less_annoying_crm._call_function(session, "key", "GetUser", {}, LOGGER)
+
+ def test_error_body_on_200_still_raises(self) -> None:
+ session = _session_returning(_response(200, {"ErrorCode": "x", "ErrorDescription": "nope"}))
+ with pytest.raises(LessAnnoyingCRMError):
+ less_annoying_crm._call_function(session, "key", "GetUser", {}, LOGGER)
+
+
+class TestValidateCredentials:
+ def test_valid_key_returns_true(self) -> None:
+ session = _session_returning(_response(200, {"UserId": "1", "Email": "[email protected]"}))
+ with patch(f"{MODULE}.make_tracked_session", return_value=session):
+ assert validate_credentials("good-key") is True
+
+ def test_invalid_key_returns_false(self) -> None:
+ session = _session_returning(_response(400, {"ErrorCode": "x", "ErrorDescription": "Invalid credentials."}))
+ with patch(f"{MODULE}.make_tracked_session", return_value=session):
+ assert validate_credentials("bad-key") is False
+
+ def test_probe_redacts_the_api_key(self) -> None:
+ session = _session_returning(_response(200, {"UserId": "1"}))
+ with patch(f"{MODULE}.make_tracked_session", return_value=session) as make_session:
+ validate_credentials("secret-key")
+ assert make_session.call_args.kwargs["redact_values"] == ("secret-key",)
+
+
+class TestGetRows:
+ def test_sync_redacts_the_api_key(self) -> None:
+ session = _session_returning(_response(200, [{"UserId": "1"}]))
+ with patch(f"{MODULE}.make_tracked_session", return_value=session) as make_session:
+ list(get_rows("secret-key", "users", LOGGER, _manager()))
+ assert make_session.call_args.kwargs["redact_values"] == ("secret-key",)
+
+ def test_non_paginated_single_call(self) -> None:
+ session = _session_returning(_response(200, [{"UserId": "1"}, {"UserId": "2"}]))
+ with patch(f"{MODULE}.make_tracked_session", return_value=session):
+ pages = list(get_rows("key", "users", LOGGER, _manager()))
+ assert pages == [[{"UserId": "1"}, {"UserId": "2"}]]
+ assert session.post.call_count == 1
+
+ def test_stops_when_no_more_results(self) -> None:
+ session = _session_returning(_response(200, {"Results": [{"ContactId": "1"}], "HasMoreResults": False}))
+ with patch(f"{MODULE}.make_tracked_session", return_value=session):
+ pages = list(get_rows("key", "contacts", LOGGER, _manager()))
+ assert pages == [[{"ContactId": "1"}]]
+ assert session.post.call_count == 1
+
+ def test_paginates_until_has_more_false(self) -> None:
+ page1 = _response(200, {"Results": [{"ContactId": "1"}], "HasMoreResults": True})
+ page2 = _response(200, {"Results": [{"ContactId": "2"}], "HasMoreResults": False})
+ session = _session_returning(page1, page2)
+ manager = _manager()
+ with patch(f"{MODULE}.make_tracked_session", return_value=session):
+ pages = list(get_rows("key", "contacts", LOGGER, manager))
+ assert pages == [[{"ContactId": "1"}], [{"ContactId": "2"}]]
+ # State saved after yielding the first page (more remained), pointing at page 2.
+ assert manager.save_state.call_args_list[0].args[0] == LessAnnoyingCRMResumeConfig(page=2)
+
+ def test_resumes_from_saved_page(self) -> None:
+ session = _session_returning(_response(200, {"Results": [{"ContactId": "9"}], "HasMoreResults": False}))
+ with patch(f"{MODULE}.make_tracked_session", return_value=session):
+ list(get_rows("key", "contacts", LOGGER, _manager(LessAnnoyingCRMResumeConfig(page=4))))
+ assert session.post.call_args.kwargs["json"]["Parameters"]["Page"] == 4
+
+ def test_empty_first_page_yields_nothing(self) -> None:
+ session = _session_returning(_response(200, {"Results": [], "HasMoreResults": False}))
+ with patch(f"{MODULE}.make_tracked_session", return_value=session):
+ pages = list(get_rows("key", "contacts", LOGGER, _manager()))
+ assert pages == []
+
+
+class TestSourceResponse:
+ @pytest.mark.parametrize("endpoint", sorted(ENDPOINTS))
+ def test_primary_keys_match_settings(self, endpoint: str) -> None:
+ response = less_annoying_crm_source("key", endpoint, LOGGER, _manager())
+ assert response.name == endpoint
+ assert response.primary_keys == LESS_ANNOYING_CRM_ENDPOINTS[endpoint].primary_keys
+
+ def test_partitioned_endpoint_uses_datetime_mode(self) -> None:
+ response = less_annoying_crm_source("key", "contacts", LOGGER, _manager())
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == ["DateCreated"]
+
+ def test_reference_table_is_not_partitioned(self) -> None:
+ response = less_annoying_crm_source("key", "users", LOGGER, _manager())
+ assert response.partition_mode is None
+ assert response.partition_keys is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/less_annoying_crm/tests/test_less_annoying_crm_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/less_annoying_crm/tests/test_less_annoying_crm_source.py
new file mode 100644
index 000000000000..5dc1d463eb99
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/less_annoying_crm/tests/test_less_annoying_crm_source.py
@@ -0,0 +1,111 @@
+from typing import Any
+
+import pytest
+from unittest import mock
+
+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 (
+ LessAnnoyingCRMSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.less_annoying_crm.less_annoying_crm import (
+ LessAnnoyingCRMResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.less_annoying_crm.settings import (
+ ENDPOINTS,
+ LESS_ANNOYING_CRM_ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.less_annoying_crm.source import (
+ LessAnnoyingCRMSource,
+)
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.less_annoying_crm.source"
+
+
+def _make_inputs(**overrides: Any) -> mock.MagicMock:
+ inputs = mock.MagicMock()
+ inputs.schema_name = overrides.get("schema_name", "contacts")
+ return inputs
+
+
+class TestLessAnnoyingCRMSource:
+ def setup_method(self) -> None:
+ self.source = LessAnnoyingCRMSource()
+ self.team_id = 123
+ self.config = LessAnnoyingCRMSourceConfig(api_key="test-key")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.LESSANNOYINGCRM
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+ assert config.name.value == "LessAnnoyingCRM"
+ assert config.label == "Less Annoying CRM"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is True
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/less-annoying-crm"
+
+ assert len(config.fields) == 1
+ api_key_field = config.fields[0]
+ assert isinstance(api_key_field, SourceFieldInputConfig)
+ assert api_key_field.name == "api_key"
+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key_field.required is True
+
+ def test_get_schemas_matches_endpoints(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+
+ @pytest.mark.parametrize("endpoint", sorted(ENDPOINTS))
+ def test_get_schemas_are_full_refresh_only(self, endpoint: str) -> None:
+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == endpoint)
+ # LACRM has no server-side modified-since filter, so nothing is incremental.
+ assert schema.supports_incremental is False
+ assert schema.supports_append is False
+ assert schema.detected_primary_keys == LESS_ANNOYING_CRM_ENDPOINTS[endpoint].primary_keys
+
+ def test_get_schemas_names_filter(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["contacts", "tasks"])
+ assert {s.name for s in schemas} == {"contacts", "tasks"}
+
+ def test_validate_credentials_success(self) -> None:
+ with mock.patch(f"{MODULE}.validate_less_annoying_crm_credentials", return_value=True):
+ assert self.source.validate_credentials(self.config, self.team_id) == (True, None)
+
+ def test_validate_credentials_failure(self) -> None:
+ with mock.patch(f"{MODULE}.validate_less_annoying_crm_credentials", return_value=False):
+ ok, error = self.source.validate_credentials(self.config, self.team_id)
+ assert ok is False
+ assert error is not None
+
+ def test_non_retryable_errors_cover_invalid_credentials(self) -> None:
+ assert "Invalid credentials" in self.source.get_non_retryable_errors()
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(_make_inputs())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is LessAnnoyingCRMResumeConfig
+
+ def test_source_for_pipeline_plumbs_arguments(self) -> None:
+ inputs = _make_inputs(schema_name="tasks")
+ manager = mock.MagicMock(spec=ResumableSourceManager)
+ with mock.patch(f"{MODULE}.less_annoying_crm_source") as mocked:
+ self.source.source_for_pipeline(self.config, manager, inputs)
+ mocked.assert_called_once_with(
+ api_key="test-key",
+ endpoint="tasks",
+ logger=inputs.logger,
+ resumable_source_manager=manager,
+ )
+
+ def test_canonical_descriptions_key_on_endpoint_names(self) -> None:
+ descriptions = self.source.get_canonical_descriptions()
+ assert set(descriptions).issubset(set(ENDPOINTS))
+ assert "contacts" in descriptions
+
+ def test_documented_tables_render_without_credentials(self) -> None:
+ tables = self.source.get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+ assert all("Full refresh" in t["sync_methods"] for t in tables)