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 Kommo source (#77089)

Tom Owers21b49c3c1702
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 abab917c7744..1b5605953c60 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -355,6 +355,7 @@ the row lists both.
| klaviyo | HTTP | requests | ✅ |
| knock | HTTP | requests + `rest_source.RESTClient` | ✅ |
| knowbe4 | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| kommo | HTTP | requests + `rest_source.RESTClient` | ✅ |
| koyeb | HTTP | requests | ✅ |
| kong_konnect | HTTP | requests | ✅ |
| kubecost | HTTP | requests | ✅ |
@@ -1076,7 +1077,6 @@ doesn't conflict with concurrent PRs.
- kisi
- kissmetrics
- klarna
-- kommo
- komodor
- koyeb
- kyve
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/kommo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/kommo.py
index c845adff67f3..1a294de440bb 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/kommo.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/kommo.py
@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class KommoSourceConfig(config.Config):
- pass
+ subdomain: str
+ api_key: str
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kommo/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kommo/canonical_descriptions.py
new file mode 100644
index 000000000000..45137746799d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kommo/canonical_descriptions.py
@@ -0,0 +1,220 @@
+"""Canonical, documentation-sourced descriptions for Kommo API v4 endpoints and columns.
+
+Sourced from the official Kommo developer reference (https://developers.kommo.com/reference).
+Keyed by the endpoint names in `settings.py` `ENDPOINTS`, which match the `ExternalDataSchema.name`
+of a synced Kommo table. Columns absent here fall back to LLM enrichment.
+"""
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Fields Kommo repeats across most entities, merged into each entry rather than restated.
+_COMMON_COLUMNS = {
+ "id": "Unique identifier of the entity within the Kommo account.",
+ "account_id": "Identifier of the Kommo account the entity belongs to.",
+ "created_at": "When the entity was created, as a Unix timestamp.",
+ "updated_at": "When the entity was last changed, as a Unix timestamp.",
+ "created_by": "Identifier of the user who created the entity. 0 when it was created by an integration.",
+ "updated_by": "Identifier of the user who last changed the entity. 0 when it was changed by an integration.",
+ "responsible_user_id": "Identifier of the user the entity is assigned to.",
+ "group_id": "Identifier of the team the responsible user belongs to.",
+ "custom_fields_values": "Custom field values as a list of {field_id, field_name, field_code, field_type, values}.",
+ "_embedded": "Related records returned because of the `with` request parameter, such as linked contacts or tags.",
+ "_links": "HAL links for the record, including its own API URL.",
+}
+
+_NOTE_COLUMNS = {
+ **_COMMON_COLUMNS,
+ "entity_id": "Identifier of the lead, contact, or company the note is attached to.",
+ "note_type": "Kind of note, for example common, call_in, call_out, or attachment.",
+ "params": "Note payload, whose keys depend on `note_type` (text, call duration, file metadata, and so on).",
+ "is_pinned": "Whether the note is pinned to the top of the entity's feed.",
+}
+
+_TAG_COLUMNS = {
+ "id": "Unique identifier of the tag.",
+ "name": "Tag name as shown in the interface.",
+ "color": "Tag color as a hex value, or null when the tag has no color set.",
+}
+
+_CUSTOM_FIELD_COLUMNS = {
+ "id": "Unique identifier of the custom field.",
+ "name": "Custom field name as shown in the interface.",
+ "code": "Field code, used to address predefined fields through the API.",
+ "sort": "Position of the field in the entity card.",
+ "type": "Field type, for example text, numeric, select, multiselect, date, or price.",
+ "entity_type": "Entity the field belongs to (leads, contacts, or companies).",
+ "is_predefined": "Whether the field is one of Kommo's built-in fields.",
+ "is_deletable": "Whether the field can be deleted.",
+ "is_api_only": "Whether the field can only be changed through the API.",
+ "group_id": "Identifier of the field group the field is shown in.",
+ "enums": "Available values for select-style fields, each with an id, value, and sort order.",
+ "required_statuses": "Pipeline stages that require this field to be filled in.",
+ "hidden_statuses": "Pipeline stages that hide this field.",
+ "currency": "Currency of the field, for monetary field types.",
+ "account_id": "Identifier of the Kommo account the field belongs to.",
+}
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "Leads": {
+ "description": "A sales opportunity moving through a Kommo pipeline, with its stage, price, and owner.",
+ "docs_url": "https://developers.kommo.com/reference/leads-list",
+ "columns": {
+ **_COMMON_COLUMNS,
+ "name": "Lead name.",
+ "price": "Lead value in the account's currency.",
+ "status_id": "Identifier of the pipeline stage the lead currently sits in.",
+ "pipeline_id": "Identifier of the pipeline the lead belongs to.",
+ "loss_reason_id": "Identifier of the loss reason, set when the lead was marked as lost.",
+ "closed_at": "When the lead was closed as won or lost, as a Unix timestamp.",
+ "closest_task_at": "Due date of the lead's nearest open task, as a Unix timestamp.",
+ "is_deleted": "Whether the lead is in the recycle bin.",
+ "score": "Lead score, when scoring is enabled for the account.",
+ "labor_cost": "Time logged against the lead, in seconds.",
+ "is_price_modified_by_robot": "Whether the lead price was last changed by a Salesbot.",
+ },
+ },
+ "Contacts": {
+ "description": "A person in the Kommo account, linked to the leads and companies they belong to.",
+ "docs_url": "https://developers.kommo.com/reference/contacts-list",
+ "columns": {
+ **_COMMON_COLUMNS,
+ "name": "Full contact name.",
+ "first_name": "Contact's first name.",
+ "last_name": "Contact's last name.",
+ "closest_task_at": "Due date of the contact's nearest open task, as a Unix timestamp.",
+ "is_deleted": "Whether the contact is in the recycle bin.",
+ },
+ },
+ "Companies": {
+ "description": "An organization in the Kommo account, linked to its contacts and leads.",
+ "docs_url": "https://developers.kommo.com/reference/companies-list",
+ "columns": {
+ **_COMMON_COLUMNS,
+ "name": "Company name.",
+ "closest_task_at": "Due date of the company's nearest open task, as a Unix timestamp.",
+ "is_deleted": "Whether the company is in the recycle bin.",
+ },
+ },
+ "LeadNotes": {
+ "description": "Notes and logged interactions attached to leads, including calls and system messages.",
+ "docs_url": "https://developers.kommo.com/reference/notes-list-entity",
+ "columns": _NOTE_COLUMNS,
+ },
+ "ContactNotes": {
+ "description": "Notes and logged interactions attached to contacts.",
+ "docs_url": "https://developers.kommo.com/reference/notes-list-entity",
+ "columns": _NOTE_COLUMNS,
+ },
+ "CompanyNotes": {
+ "description": "Notes and logged interactions attached to companies.",
+ "docs_url": "https://developers.kommo.com/reference/notes-list-entity",
+ "columns": _NOTE_COLUMNS,
+ },
+ "Tasks": {
+ "description": "A to-do assigned to a user against a lead, contact, or company.",
+ "docs_url": "https://developers.kommo.com/reference/tasks-list",
+ "columns": {
+ **_COMMON_COLUMNS,
+ "entity_id": "Identifier of the lead, contact, or company the task is attached to.",
+ "entity_type": "Type of entity the task is attached to (leads, contacts, or companies).",
+ "task_type_id": "Identifier of the task type, for example call or meeting.",
+ "text": "Task description.",
+ "duration": "Planned duration of the task, in seconds.",
+ "is_completed": "Whether the task has been completed.",
+ "result": "Result recorded when the task was completed.",
+ "complete_till": "Deadline for the task, as a Unix timestamp.",
+ },
+ },
+ "Events": {
+ "description": "The account's change feed: stage moves, field edits, and other recorded actions.",
+ "docs_url": "https://developers.kommo.com/reference/events-list",
+ "columns": {
+ "id": "Unique identifier of the event.",
+ "type": "Event type, for example lead_status_changed or sale_field_changed.",
+ "entity_id": "Identifier of the entity the event happened to.",
+ "entity_type": "Type of the entity the event happened to (lead, contact, company, task, or a catalog).",
+ "created_by": "Identifier of the user who triggered the event. 0 when it was an integration.",
+ "created_at": "When the event happened, as a Unix timestamp.",
+ "value_before": "The changed values as they were before the event.",
+ "value_after": "The changed values as they were after the event.",
+ "account_id": "Identifier of the Kommo account the event belongs to.",
+ },
+ },
+ "Pipelines": {
+ "description": "A lead pipeline, with its stages returned under `_embedded.statuses`.",
+ "docs_url": "https://developers.kommo.com/reference/pipelines-list",
+ "columns": {
+ "id": "Unique identifier of the pipeline.",
+ "name": "Pipeline name.",
+ "sort": "Position of the pipeline in the interface.",
+ "is_main": "Whether this is the account's main pipeline.",
+ "is_unsorted_on": "Whether the Incoming leads stage is enabled for this pipeline.",
+ "is_archive": "Whether the pipeline is archived.",
+ "account_id": "Identifier of the Kommo account the pipeline belongs to.",
+ "_embedded": "Pipeline stages, each with id, name, sort, color, and type.",
+ },
+ },
+ "Users": {
+ "description": "A user of the Kommo account, with their access rights. Requires an admin token.",
+ "docs_url": "https://developers.kommo.com/reference/users-list",
+ "columns": {
+ "id": "Unique identifier of the user.",
+ "name": "User's full name.",
+ "email": "User's email address, which is also their login.",
+ "lang": "Interface language of the user.",
+ "rights": "Per-entity access rights plus admin, active, and free-seat flags.",
+ "_embedded": "Role and team returned because of the `with` request parameter.",
+ },
+ },
+ "Catalogs": {
+ "description": "A Kommo list (catalog), such as a product or supplier list.",
+ "docs_url": "https://developers.kommo.com/reference/get-lists",
+ "columns": {
+ "id": "Unique identifier of the list.",
+ "name": "List name.",
+ "created_by": "Identifier of the user who created the list.",
+ "updated_by": "Identifier of the user who last changed the list.",
+ "created_at": "When the list was created, as a Unix timestamp.",
+ "updated_at": "When the list was last changed, as a Unix timestamp.",
+ "sort": "Position of the list in the interface.",
+ "type": "List type, for example regular, products, or invoices.",
+ "can_add_elements": "Whether elements can be added to the list.",
+ "can_show_in_cards": "Whether the list can be shown in entity cards.",
+ "can_link_multiple": "Whether several elements of the list can be linked to one entity.",
+ "can_be_deleted": "Whether the list can be deleted.",
+ "account_id": "Identifier of the Kommo account the list belongs to.",
+ },
+ },
+ "LeadCustomFields": {
+ "description": "Custom field definitions available on leads.",
+ "docs_url": "https://developers.kommo.com/reference/custom-field-by-entity",
+ "columns": _CUSTOM_FIELD_COLUMNS,
+ },
+ "ContactCustomFields": {
+ "description": "Custom field definitions available on contacts.",
+ "docs_url": "https://developers.kommo.com/reference/custom-field-by-entity",
+ "columns": _CUSTOM_FIELD_COLUMNS,
+ },
+ "CompanyCustomFields": {
+ "description": "Custom field definitions available on companies.",
+ "docs_url": "https://developers.kommo.com/reference/custom-field-by-entity",
+ "columns": _CUSTOM_FIELD_COLUMNS,
+ },
+ "LeadTags": {
+ "description": "Tags that can be applied to leads.",
+ "docs_url": "https://developers.kommo.com/reference/list-of-entity-tags",
+ "columns": _TAG_COLUMNS,
+ },
+ "ContactTags": {
+ "description": "Tags that can be applied to contacts.",
+ "docs_url": "https://developers.kommo.com/reference/list-of-entity-tags",
+ "columns": _TAG_COLUMNS,
+ },
+ "CompanyTags": {
+ "description": "Tags that can be applied to companies.",
+ "docs_url": "https://developers.kommo.com/reference/list-of-entity-tags",
+ "columns": _TAG_COLUMNS,
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kommo/kommo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kommo/kommo.py
new file mode 100644
index 000000000000..75227148813e
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kommo/kommo.py
@@ -0,0 +1,172 @@
+import re
+import dataclasses
+from typing import Any, Optional
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ BasePaginator,
+ PageNumberPaginator,
+ SinglePagePaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import EndpointResource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.kommo.settings import (
+ ENDPOINT_CONFIG,
+ PAGE_LIMIT,
+ KommoEndpoint,
+)
+
+# Kommo is a per-account host, so bound every request rather than letting a stalled account
+# hold an import worker open indefinitely.
+REQUEST_TIMEOUT = (10.0, 60.0)
+
+KOMMO_DOMAIN = "kommo.com"
+
+# A single DNS label: Kommo accounts live at https://<subdomain>.kommo.com.
+_SUBDOMAIN_RE = re.compile(r"^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$")
+
+
+class KommoResumeConfig:
+ page: int
+
+
+def normalize_subdomain(raw: str) -> str | None:
+ """Reduce whatever the user pasted to the bare account label, or None when it isn't one.
+
+ Accepts `mycompany`, `mycompany.kommo.com`, and `https://mycompany.kommo.com/`. Anything
+ else (an amocrm.ru host, a path, an IP) is rejected rather than guessed at, because the
+ value picks the host the access token is sent to.
+ """
+ value = (raw or "").strip().lower()
+ value = value.removeprefix("https://").removeprefix("http://")
+ value = value.split("/")[0].split("?")[0]
+ value = value.removesuffix(f".{KOMMO_DOMAIN}")
+ if not _SUBDOMAIN_RE.match(value):
+ return None
+ return value
+
+
+def account_host(subdomain: str) -> str:
+ return f"{subdomain}.{KOMMO_DOMAIN}"
+
+
+def _build_paginator(endpoint: KommoEndpoint) -> BasePaginator:
+ if not endpoint.paginated:
+ return SinglePagePaginator()
+ # Kommo pages are 1-indexed and answer 204 No Content once you page past the end; the REST
+ # client turns that empty body into an empty page, which stops the paginator. `_page_count`
+ # is present on most envelopes and saves that extra request when it is.
+ return PageNumberPaginator(base_page=1, page_param="page", total_path="_page_count")
+
+
+def get_resource(name: str, should_use_incremental_field: bool) -> EndpointResource:
+ endpoint = ENDPOINT_CONFIG[name]
+
+ params: dict[str, Any] = dict(endpoint.params)
+ if endpoint.paginated:
+ params["limit"] = PAGE_LIMIT
+
+ incremental_param = endpoint.incremental_param if should_use_incremental_field else None
+ if incremental_param is not None:
+ params[incremental_param] = {
+ "type": "incremental",
+ "cursor_path": "updated_at",
+ "initial_value": 0,
+ }
+
+ return {
+ "name": name,
+ "table_name": name.lower(),
+ "primary_key": endpoint.primary_key,
+ "write_disposition": {"disposition": "merge", "strategy": "upsert"}
+ if incremental_param is not None
+ else "replace",
+ "endpoint": {
+ "path": endpoint.path,
+ "data_selector": endpoint.data_selector,
+ "params": params,
+ "paginator": _build_paginator(endpoint),
+ },
+ "table_format": "delta",
+ }
+
+
+def kommo_source(
+ api_key: str,
+ subdomain: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[KommoResumeConfig],
+ db_incremental_field_last_value: Optional[Any],
+ should_use_incremental_field: bool = False,
+) -> Resource:
+ host = account_host(subdomain)
+ config: RESTAPIConfig = {
+ "client": {
+ "base_url": f"https://{host}",
+ "auth": {"type": "bearer", "token": api_key},
+ "allowed_hosts": [host],
+ "allow_redirects": False,
+ "request_timeout": REQUEST_TIMEOUT,
+ },
+ "resources": [get_resource(endpoint, should_use_incremental_field)],
+ }
+
+ # A page number is only a safe resume point on a full-refresh run. Incremental runs advance
+ # `filter[updated_at][from]` after every batch, so page N of the resumed query is not page N
+ # of the interrupted one and resuming by page would skip rows. There the watermark is the
+ # resume point: restarting at page 1 with the advanced filter picks up where we stopped,
+ # because rows arrive ordered by `updated_at` ascending.
+ resume_enabled = not should_use_incremental_field
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resume_enabled and resumable_source_manager.can_resume():
+ resume_config = resumable_source_manager.load_state()
+ if resume_config is not None:
+ initial_paginator_state = {"page": resume_config.page}
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # Only persist while there's a next page to come back to; the Redis TTL cleans up.
+ if state and state.get("page") is not None:
+ resumable_source_manager.save_state(KommoResumeConfig(page=int(state["page"])))
+
+ return rest_api_resource(
+ config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value,
+ resume_hook=save_checkpoint if resume_enabled else None,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+
+def validate_credentials(api_key: str, subdomain: str) -> tuple[bool, str | None]:
+ """Probe the token itself with the cheapest endpoint every Kommo user can reach."""
+ session = make_tracked_session(redact_values=(api_key,), allow_redirects=False)
+ response = session.get(
+ f"https://{account_host(subdomain)}/api/v4/account",
+ headers={"Authorization": f"Bearer {api_key}"},
+ timeout=REQUEST_TIMEOUT,
+ )
+
+ if response.status_code == 200:
+ return True, None
+ if response.status_code == 401:
+ return False, "Kommo rejected the access token. Check the token and the account subdomain."
+ if response.status_code == 403:
+ return False, (
+ "This Kommo token cannot access the account. Check the integration's scopes and the "
+ "token owner's user rights."
+ )
+ if response.status_code == 402:
+ return False, "This Kommo account is not paid up, so the API is unavailable."
+ if response.status_code == 404:
+ return False, f"No Kommo account found at {account_host(subdomain)}."
+ return False, f"Kommo returned an unexpected {response.status_code} response."
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kommo/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kommo/settings.py
new file mode 100644
index 000000000000..963fd4c29e6d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kommo/settings.py
@@ -0,0 +1,149 @@
+from dataclasses import dataclass, field
+from typing import Any
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# Kommo caps every list endpoint at 250 entities per response.
+PAGE_LIMIT = 250
+
+API_BASE_PATH = "/api/v4"
+
+
+@dataclass(frozen=True)
+class KommoEndpoint:
+ path: str
+ data_selector: str
+ primary_key: list[str]
+ # Server-side lower-bound filter for incremental syncs, e.g. `filter[updated_at][from]`.
+ # None means the endpoint is full refresh only.
+ incremental_param: str | None = None
+ params: dict[str, Any] = field(default_factory=dict)
+ # Endpoints that return their whole collection in one unpaginated response.
+ paginated: bool = True
+
+
+# `order[updated_at]=asc` is set on every endpoint that documents it, so rows arrive in the
+# same order the incremental watermark advances in. Tasks and Events are deliberately full
+# refresh: both expose a server-side timestamp filter, but neither documents an ordering
+# parameter for that timestamp, and an unordered incremental sync silently corrupts the
+# watermark. Tasks still asks for `order[created_at]=asc` so pagination is at least stable.
+ENDPOINT_CONFIG: dict[str, KommoEndpoint] = {
+ "Leads": KommoEndpoint(
+ path=f"{API_BASE_PATH}/leads",
+ data_selector="_embedded.leads",
+ primary_key=["id"],
+ incremental_param="filter[updated_at][from]",
+ params={"with": "contacts,loss_reason,source", "order[updated_at]": "asc"},
+ ),
+ "Contacts": KommoEndpoint(
+ path=f"{API_BASE_PATH}/contacts",
+ data_selector="_embedded.contacts",
+ primary_key=["id"],
+ incremental_param="filter[updated_at][from]",
+ params={"with": "leads", "order[updated_at]": "asc"},
+ ),
+ "Companies": KommoEndpoint(
+ path=f"{API_BASE_PATH}/companies",
+ data_selector="_embedded.companies",
+ primary_key=["id"],
+ incremental_param="filter[updated_at][from]",
+ params={"with": "contacts,leads", "order[updated_at]": "asc"},
+ ),
+ "LeadNotes": KommoEndpoint(
+ path=f"{API_BASE_PATH}/leads/notes",
+ data_selector="_embedded.notes",
+ primary_key=["id"],
+ incremental_param="filter[updated_at][from]",
+ params={"order[updated_at]": "asc"},
+ ),
+ "ContactNotes": KommoEndpoint(
+ path=f"{API_BASE_PATH}/contacts/notes",
+ data_selector="_embedded.notes",
+ primary_key=["id"],
+ incremental_param="filter[updated_at][from]",
+ params={"order[updated_at]": "asc"},
+ ),
+ "CompanyNotes": KommoEndpoint(
+ path=f"{API_BASE_PATH}/companies/notes",
+ data_selector="_embedded.notes",
+ primary_key=["id"],
+ incremental_param="filter[updated_at][from]",
+ params={"order[updated_at]": "asc"},
+ ),
+ "Tasks": KommoEndpoint(
+ path=f"{API_BASE_PATH}/tasks",
+ data_selector="_embedded.tasks",
+ primary_key=["id"],
+ params={"order[created_at]": "asc"},
+ ),
+ "Events": KommoEndpoint(
+ path=f"{API_BASE_PATH}/events",
+ data_selector="_embedded.events",
+ primary_key=["id"],
+ ),
+ "Pipelines": KommoEndpoint(
+ path=f"{API_BASE_PATH}/leads/pipelines",
+ data_selector="_embedded.pipelines",
+ primary_key=["id"],
+ paginated=False,
+ ),
+ "Users": KommoEndpoint(
+ path=f"{API_BASE_PATH}/users",
+ data_selector="_embedded.users",
+ primary_key=["id"],
+ params={"with": "role,group"},
+ ),
+ "Catalogs": KommoEndpoint(
+ path=f"{API_BASE_PATH}/catalogs",
+ data_selector="_embedded.catalogs",
+ primary_key=["id"],
+ ),
+ "LeadCustomFields": KommoEndpoint(
+ path=f"{API_BASE_PATH}/leads/custom_fields",
+ data_selector="_embedded.custom_fields",
+ primary_key=["id"],
+ ),
+ "ContactCustomFields": KommoEndpoint(
+ path=f"{API_BASE_PATH}/contacts/custom_fields",
+ data_selector="_embedded.custom_fields",
+ primary_key=["id"],
+ ),
+ "CompanyCustomFields": KommoEndpoint(
+ path=f"{API_BASE_PATH}/companies/custom_fields",
+ data_selector="_embedded.custom_fields",
+ primary_key=["id"],
+ ),
+ "LeadTags": KommoEndpoint(
+ path=f"{API_BASE_PATH}/leads/tags",
+ data_selector="_embedded.tags",
+ primary_key=["id"],
+ ),
+ "ContactTags": KommoEndpoint(
+ path=f"{API_BASE_PATH}/contacts/tags",
+ data_selector="_embedded.tags",
+ primary_key=["id"],
+ ),
+ "CompanyTags": KommoEndpoint(
+ path=f"{API_BASE_PATH}/companies/tags",
+ data_selector="_embedded.tags",
+ primary_key=["id"],
+ ),
+}
+
+ENDPOINTS = tuple(ENDPOINT_CONFIG.keys())
+
+
+def _updated_at_field() -> list[IncrementalField]:
+ return [
+ {
+ "label": "updated_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "updated_at",
+ "field_type": IncrementalFieldType.Integer,
+ }
+ ]
+
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: _updated_at_field() for name, endpoint in ENDPOINT_CONFIG.items() if endpoint.incremental_param is not None
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kommo/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kommo/source.py
index 0adcf0f39335..fa4a0de69145 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/kommo/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kommo/source.py
@@ -1,30 +1,173 @@
-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.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.kommo import KommoSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.kommo.kommo import (
+ KommoResumeConfig,
+ kommo_source,
+ normalize_subdomain,
+ validate_credentials as validate_kommo_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.kommo.settings import (
+ ENDPOINT_CONFIG,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
+SUBDOMAIN_ERROR = (
+ "Enter just the subdomain of your Kommo account, for example mycompany for https://mycompany.kommo.com"
+)
+
@SourceRegistry.register
-class KommoSource(SimpleSource[KommoSourceConfig]):
+class KommoSource(ResumableSource[KommoSourceConfig, KommoResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ supported_versions = ("v4",)
+ default_version = "v4"
+ api_docs_url = "https://developers.kommo.com/reference/kommo-api-reference"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.KOMMO
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # `subdomain` picks the host the access token is sent to, so retargeting it must
+ # re-require the token instead of reusing the stored one.
+ return ["subdomain"]
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url": "Kommo rejected the access token. Generate a new long-lived token and reconnect.",
+ "403 Client Error: Forbidden for url": "This Kommo token cannot access the requested data. Check the integration's scopes and the token owner's user rights.",
+ "402 Client Error: Payment Required for url": "This Kommo account is not paid up, so its API is unavailable.",
+ "404 Client Error: Not Found for url": "No Kommo account found at this subdomain. Check the account subdomain and reconnect.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.kommo.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: KommoSourceConfig,
+ 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: KommoSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ subdomain = normalize_subdomain(config.subdomain)
+ if subdomain is None:
+ return False, SUBDOMAIN_ERROR
+
+ return validate_kommo_credentials(config.api_key, subdomain)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[KommoResumeConfig]:
+ return ResumableSourceManager[KommoResumeConfig](inputs, KommoResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: KommoSourceConfig,
+ resumable_source_manager: ResumableSourceManager[KommoResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ subdomain = normalize_subdomain(config.subdomain)
+ if subdomain is None:
+ raise ValueError(SUBDOMAIN_ERROR)
+
+ endpoint = ENDPOINT_CONFIG[inputs.schema_name]
+ should_use_incremental_field = inputs.should_use_incremental_field and endpoint.incremental_param is not None
+
+ resource = kommo_source(
+ api_key=config.api_key,
+ subdomain=subdomain,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if should_use_incremental_field
+ else None,
+ )
+ return SourceResponse(
+ name=resource.name,
+ items=lambda: resource,
+ primary_keys=endpoint.primary_key,
+ column_hints=resource.column_hints,
+ # Incremental endpoints are requested with `order[updated_at]=asc`, the same order
+ # the watermark advances in.
+ sort_mode="asc",
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.KOMMO,
category=DataWarehouseSourceCategory.CRM,
label="Kommo",
+ caption=(
+ "In Kommo, go to Settings > Integrations and create a private integration, then open "
+ "**Keys and scopes** and generate a long-lived token. The token inherits the rights of "
+ "the user who created it, so create it as an admin if you want to sync users and "
+ "account-wide lists."
+ ),
+ docsUrl="https://posthog.com/docs/cdp/sources/kommo",
iconPath="/static/services/kommo.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ keywords=["amocrm", "crm"],
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="subdomain",
+ label="Account subdomain",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="mycompany",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="api_key",
+ label="Long-lived access token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kommo/tests/test_kommo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kommo/tests/test_kommo.py
new file mode 100644
index 000000000000..94fd2cb366b8
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kommo/tests/test_kommo.py
@@ -0,0 +1,317 @@
+import json
+from collections.abc import Iterable
+from typing import Any, cast
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from requests import Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ PageNumberPaginator,
+ SinglePagePaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.kommo.kommo import (
+ KommoResumeConfig,
+ get_resource,
+ kommo_source,
+ normalize_subdomain,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.kommo.settings import (
+ ENDPOINT_CONFIG,
+ ENDPOINTS,
+ PAGE_LIMIT,
+)
+
+SESSION_FACTORY = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
+
+
+def _http_response(body: dict[str, Any] | None, status_code: int = 200) -> Response:
+ response = Response()
+ response.status_code = status_code
+ response.url = "https://acme.kommo.com/api/v4/leads"
+ if body is None:
+ response._content = b""
+ else:
+ response._content = json.dumps(body).encode()
+ response.headers["Content-Type"] = "application/hal+json"
+ return response
+
+
+def _leads_page(ids: list[int], page: int, page_count: int) -> dict[str, Any]:
+ return {
+ "_page": page,
+ "_page_count": page_count,
+ "_embedded": {"leads": [{"id": lead_id, "updated_at": 1700000000 + lead_id} for lead_id in ids]},
+ }
+
+
+class TestNormalizeSubdomain:
+ @pytest.mark.parametrize(
+ ("raw", "expected"),
+ [
+ ("acme", "acme"),
+ (" ACME ", "acme"),
+ ("acme.kommo.com", "acme"),
+ ("https://acme.kommo.com", "acme"),
+ ("https://acme.kommo.com/leads", "acme"),
+ ("http://acme.kommo.com/", "acme"),
+ ("my-acme-2", "my-acme-2"),
+ ],
+ )
+ def test_accepts_and_reduces_valid_account_references(self, raw: str, expected: str) -> None:
+ assert normalize_subdomain(raw) == expected
+
+ @pytest.mark.parametrize(
+ "raw",
+ [
+ "",
+ " ",
+ "acme.amocrm.ru",
+ "evil.example.com",
+ "acme.kommo.com.evil.example.com",
+ "acme..kommo.com",
+ "-acme",
+ "acme-",
+ "acme_corp",
+ "acme:8080",
+ "10.0.0.1",
+ "acme kommo",
+ ],
+ )
+ def test_rejects_anything_that_is_not_a_single_kommo_label(self, raw: str) -> None:
+ # The subdomain picks the host the access token is sent to, so a value that
+ # smuggles another host through must be rejected rather than normalized.
+ assert normalize_subdomain(raw) is None
+
+
+class TestGetResource:
+ def test_every_declared_endpoint_builds_a_resource(self) -> None:
+ for name in ENDPOINTS:
+ resource = get_resource(name, should_use_incremental_field=False)
+ endpoint = cast(dict[str, Any], resource["endpoint"])
+
+ assert resource["name"] == name
+ assert resource["primary_key"] == ENDPOINT_CONFIG[name].primary_key
+ assert endpoint["path"].startswith("/api/v4/")
+ assert endpoint["data_selector"].startswith("_embedded.")
+
+ @pytest.mark.parametrize("name", ["Leads", "Contacts", "Companies", "LeadNotes", "ContactNotes", "CompanyNotes"])
+ def test_incremental_endpoints_bind_the_updated_at_filter_and_merge(self, name: str) -> None:
+ resource = get_resource(name, should_use_incremental_field=True)
+ params = cast(dict[str, Any], resource["endpoint"])["params"]
+
+ assert params["filter[updated_at][from]"] == {
+ "type": "incremental",
+ "cursor_path": "updated_at",
+ "initial_value": 0,
+ }
+ assert params["order[updated_at]"] == "asc"
+ assert resource["write_disposition"] == {"disposition": "merge", "strategy": "upsert"}
+
+ @pytest.mark.parametrize("name", ["Tasks", "Events", "Pipelines", "Users", "Catalogs", "LeadTags"])
+ def test_full_refresh_endpoints_never_bind_a_filter_even_when_asked(self, name: str) -> None:
+ # Tasks and Events do expose a server-side timestamp filter but no ordering parameter for
+ # it, so they must stay full refresh: an unordered incremental sync corrupts the watermark.
+ resource = get_resource(name, should_use_incremental_field=True)
+ params = cast(dict[str, Any], resource["endpoint"])["params"]
+
+ assert not any(key.startswith("filter[") for key in params)
+ assert resource["write_disposition"] == "replace"
+
+ @pytest.mark.parametrize("name", ["Leads", "Tasks", "Users"])
+ def test_paginated_endpoints_request_the_maximum_page_size(self, name: str) -> None:
+ # Kommo allows 7 requests/second per account, so under-filling pages costs real throughput.
+ resource = get_resource(name, should_use_incremental_field=False)
+ endpoint = cast(dict[str, Any], resource["endpoint"])
+
+ assert endpoint["params"]["limit"] == PAGE_LIMIT
+ assert isinstance(endpoint["paginator"], PageNumberPaginator)
+
+ def test_unpaginated_endpoint_uses_a_single_page_paginator(self) -> None:
+ resource = get_resource("Pipelines", should_use_incremental_field=False)
+ endpoint = cast(dict[str, Any], resource["endpoint"])
+
+ assert isinstance(endpoint["paginator"], SinglePagePaginator)
+ assert "limit" not in endpoint["params"]
+
+
+class TestKommoSourceTransport:
+ def _drive(
+ self,
+ endpoint: str,
+ manager: MagicMock,
+ responses: list[Response],
+ *,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ ) -> list[dict[str, Any]]:
+ sent_params: list[dict[str, Any]] = []
+ response_iter = iter(responses)
+
+ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:
+ sent_params.append(dict(request.params or {}))
+ return next(response_iter)
+
+ with patch(SESSION_FACTORY) as MockSession:
+ mock_session = MockSession.return_value
+ mock_session.headers = {}
+ mock_session.prepare_request.side_effect = lambda req: req
+ mock_session.send.side_effect = fake_send
+
+ resource = kommo_source(
+ api_key="test-token",
+ subdomain="acme",
+ endpoint=endpoint,
+ team_id=1,
+ job_id="job-1",
+ resumable_source_manager=manager,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ should_use_incremental_field=should_use_incremental_field,
+ )
+ list(cast(Iterable[Any], resource))
+
+ return sent_params
+
+ def test_pages_through_until_the_empty_no_content_page(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [
+ _http_response(_leads_page([1, 2], page=1, page_count=3)),
+ _http_response(_leads_page([3, 4], page=2, page_count=3)),
+ _http_response(_leads_page([5], page=3, page_count=3)),
+ ]
+ sent_params = self._drive("Leads", manager, responses)
+
+ assert [params["page"] for params in sent_params] == [1, 2, 3]
+
+ def test_stops_on_a_204_style_empty_body_when_page_count_is_absent(self) -> None:
+ # Kommo answers 204 with no body once you page past the end; a JSON decode of that
+ # body would blow up if the client did not treat it as an empty page.
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [
+ _http_response({"_page": 1, "_embedded": {"tags": [{"id": 1, "name": "vip"}]}}),
+ _http_response(None, status_code=204),
+ ]
+ sent_params = self._drive("LeadTags", manager, responses)
+
+ assert [params["page"] for params in sent_params] == [1, 2]
+
+ def test_full_refresh_run_checkpoints_the_next_page_after_each_batch(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [
+ _http_response(_leads_page([1], page=1, page_count=3)),
+ _http_response(_leads_page([2], page=2, page_count=3)),
+ _http_response(_leads_page([3], page=3, page_count=3)),
+ ]
+ self._drive("Leads", manager, responses)
+
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [KommoResumeConfig(page=2), KommoResumeConfig(page=3)]
+
+ def test_full_refresh_run_resumes_from_the_saved_page(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = KommoResumeConfig(page=7)
+
+ responses = [_http_response(_leads_page([9], page=7, page_count=7))]
+ sent_params = self._drive("Leads", manager, responses)
+
+ assert [params["page"] for params in sent_params] == [7]
+
+ def test_incremental_run_neither_saves_nor_loads_a_page(self) -> None:
+ # The watermark moves after every batch, so page N of a resumed incremental query is not
+ # page N of the interrupted one. Resuming by page there would skip rows.
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = KommoResumeConfig(page=7)
+
+ responses = [
+ _http_response(_leads_page([1], page=1, page_count=2)),
+ _http_response(_leads_page([2], page=2, page_count=2)),
+ ]
+ sent_params = self._drive(
+ "Leads",
+ manager,
+ responses,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=1699999999,
+ )
+
+ assert [params["page"] for params in sent_params] == [1, 2]
+ manager.load_state.assert_not_called()
+ manager.save_state.assert_not_called()
+
+ def test_incremental_run_sends_the_stored_watermark_as_the_filter_lower_bound(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [_http_response(_leads_page([1], page=1, page_count=1))]
+ sent_params = self._drive(
+ "Leads",
+ manager,
+ responses,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=1699999999,
+ )
+
+ assert sent_params[0]["filter[updated_at][from]"] == 1699999999
+ assert sent_params[0]["order[updated_at]"] == "asc"
+
+ def test_full_refresh_run_sends_no_filter(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [_http_response(_leads_page([1], page=1, page_count=1))]
+ sent_params = self._drive("Leads", manager, responses)
+
+ assert not any(key.startswith("filter[") for key in sent_params[0])
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ ("status_code", "expected_ok", "expected_message_fragment"),
+ [
+ (200, True, None),
+ (401, False, "rejected the access token"),
+ (403, False, "cannot access the account"),
+ (402, False, "not paid up"),
+ (404, False, "acme.kommo.com"),
+ (500, False, "unexpected 500"),
+ ],
+ )
+ def test_maps_status_codes_to_actionable_results(
+ self, status_code: int, expected_ok: bool, expected_message_fragment: str | None
+ ) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.kommo.kommo.make_tracked_session"
+ ) as MockSession:
+ MockSession.return_value.get.return_value = _http_response({}, status_code=status_code)
+
+ is_valid, message = validate_credentials("test-token", "acme")
+
+ assert is_valid is expected_ok
+ if expected_message_fragment is None:
+ assert message is None
+ else:
+ assert message is not None and expected_message_fragment in message
+
+ def test_probes_the_account_endpoint_on_the_accounts_own_host(self) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.kommo.kommo.make_tracked_session"
+ ) as MockSession:
+ session = MockSession.return_value
+ session.get.return_value = _http_response({}, status_code=200)
+
+ validate_credentials("test-token", "acme")
+
+ url = session.get.call_args.args[0]
+ assert url == "https://acme.kommo.com/api/v4/account"
+ assert session.get.call_args.kwargs["headers"]["Authorization"] == "Bearer test-token"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kommo/tests/test_kommo_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kommo/tests/test_kommo_source.py
new file mode 100644
index 000000000000..2b8e6d49903f
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kommo/tests/test_kommo_source.py
@@ -0,0 +1,193 @@
+from typing import Optional
+
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.kommo import KommoSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.kommo.kommo import KommoResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.kommo.settings import (
+ ENDPOINT_CONFIG,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.kommo.source import KommoSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.kommo.source"
+
+INCREMENTAL_ENDPOINTS = {"Leads", "Contacts", "Companies", "LeadNotes", "ContactNotes", "CompanyNotes"}
+
+
+class TestKommoSource:
+ def setup_method(self) -> None:
+ self.source = KommoSource()
+ self.team_id = 123
+ self.config = KommoSourceConfig(subdomain="acme", api_key="test-token")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.KOMMO
+
+ def test_get_source_config_is_released_with_an_alpha_label(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.name.value == "Kommo"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is None
+ assert config.iconPath == "/static/services/kommo.png"
+ assert [field.name for field in config.fields] == ["subdomain", "api_key"]
+
+ def test_access_token_field_is_a_secret_password(self) -> None:
+ field = next(
+ f
+ for f in self.source.get_source_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_subdomain_is_declared_as_a_connection_host_field(self) -> None:
+ # The token is sent to https://<subdomain>.kommo.com, so editing the subdomain must
+ # force the token to be re-entered instead of reusing the stored one.
+ assert self.source.connection_host_fields == ["subdomain"]
+
+ def test_api_version_is_pinned_to_the_path_the_source_calls(self) -> None:
+ assert self.source.supported_versions == ("v4",)
+ assert self.source.default_version == "v4"
+ assert self.source.resolve_api_version(None) == "v4"
+ assert all(endpoint.path.startswith("/api/v4/") for endpoint in ENDPOINT_CONFIG.values())
+
+ def test_get_schemas_needs_no_credentials(self) -> None:
+ assert self.source.lists_tables_without_credentials is True
+
+ def test_get_schemas_marks_only_ordered_endpoints_incremental(self) -> None:
+ # Tasks and Events expose a timestamp filter but no ordering parameter for it, so they
+ # must stay full refresh rather than advertising a watermark we cannot trust.
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+
+ assert set(schemas) == set(ENDPOINTS)
+ assert {name for name, schema in schemas.items() if schema.supports_incremental} == INCREMENTAL_ENDPOINTS
+ assert all(
+ [f["field"] for f in schemas[name].incremental_fields] == ["updated_at"] for name in INCREMENTAL_ENDPOINTS
+ )
+
+ @pytest.mark.parametrize(
+ ("names", "expected"),
+ [(["Leads"], ["Leads"]), (["Nope"], []), (None, list(ENDPOINTS))],
+ )
+ def test_get_schemas_filtered_by_names(self, names: Optional[list[str]], expected: list[str]) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=names)
+ assert [schema.name for schema in schemas] == expected
+
+ def test_incremental_fields_only_declared_where_a_server_side_filter_exists(self) -> None:
+ assert set(INCREMENTAL_FIELDS) == {
+ name for name, endpoint in ENDPOINT_CONFIG.items() if endpoint.incremental_param is not None
+ }
+
+ def test_canonical_descriptions_cover_every_endpoint(self) -> None:
+ assert set(self.source.get_canonical_descriptions()) == set(ENDPOINTS)
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://acme.kommo.com/api/v4/leads",
+ "403 Client Error: Forbidden for url: https://acme.kommo.com/api/v4/users",
+ "402 Client Error: Payment Required for url: https://acme.kommo.com/api/v4/events",
+ "404 Client Error: Not Found for url: https://acme.kommo.com/api/v4/leads",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_and_billing_failures(self, observed_error: str) -> None:
+ assert any(key in observed_error for key in self.source.get_non_retryable_errors())
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "429 Client Error: Too Many Requests for url: https://acme.kommo.com/api/v4/leads",
+ "500 Server Error for url: https://acme.kommo.com/api/v4/leads",
+ ],
+ )
+ def test_non_retryable_errors_leave_transient_failures_retryable(self, observed_error: str) -> None:
+ assert not any(key in observed_error for key in self.source.get_non_retryable_errors())
+
+ @pytest.mark.parametrize("subdomain", ["acme.amocrm.ru", "evil.example.com/acme", "", "acme_corp"])
+ @mock.patch(f"{_MODULE}.validate_kommo_credentials")
+ def test_validate_credentials_rejects_a_bad_subdomain_without_calling_kommo(
+ self, mock_validate: mock.MagicMock, subdomain: str
+ ) -> None:
+ config = KommoSourceConfig(subdomain=subdomain, api_key="test-token")
+
+ is_valid, message = self.source.validate_credentials(config, self.team_id)
+
+ assert is_valid is False
+ assert message is not None and "subdomain" in message
+ mock_validate.assert_not_called()
+
+ @pytest.mark.parametrize("raw_subdomain", ["acme", "https://acme.kommo.com/"])
+ @mock.patch(f"{_MODULE}.validate_kommo_credentials")
+ def test_validate_credentials_probes_the_normalized_account(
+ self, mock_validate: mock.MagicMock, raw_subdomain: str
+ ) -> None:
+ mock_validate.return_value = (True, None)
+ config = KommoSourceConfig(subdomain=raw_subdomain, api_key="test-token")
+
+ assert self.source.validate_credentials(config, self.team_id) == (True, None)
+ mock_validate.assert_called_once_with("test-token", "acme")
+
+ def test_get_resumable_source_manager_is_bound_to_the_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+ assert manager._data_class is KommoResumeConfig
+
+ @mock.patch(f"{_MODULE}.kommo_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "Leads"
+ inputs.team_id = self.team_id
+ inputs.job_id = "job-1"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = 1700000000
+ manager = mock.MagicMock()
+ config = KommoSourceConfig(subdomain="https://acme.kommo.com", api_key="test-token")
+
+ response = self.source.source_for_pipeline(config, manager, inputs)
+
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["api_key"] == "test-token"
+ assert kwargs["subdomain"] == "acme"
+ assert kwargs["endpoint"] == "Leads"
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == 1700000000
+ assert kwargs["resumable_source_manager"] is manager
+ assert response.primary_keys == ["id"]
+ assert response.sort_mode == "asc"
+
+ @pytest.mark.parametrize("schema_name", ["Tasks", "Events", "Pipelines"])
+ @mock.patch(f"{_MODULE}.kommo_source")
+ def test_source_for_pipeline_forces_full_refresh_on_unordered_endpoints(
+ self, mock_source: mock.MagicMock, schema_name: str
+ ) -> None:
+ # A schema row can carry should_use_incremental_field from an older config; the source
+ # must not honour it for an endpoint with no server-side filter.
+ inputs = mock.MagicMock()
+ inputs.schema_name = schema_name
+ inputs.should_use_incremental_field = True
+ 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
+
+ @mock.patch(f"{_MODULE}.kommo_source")
+ def test_source_for_pipeline_rejects_a_bad_subdomain(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "Leads"
+ config = KommoSourceConfig(subdomain="evil.example.com", api_key="test-token")
+
+ with pytest.raises(ValueError):
+ self.source.source_for_pipeline(config, mock.MagicMock(), inputs)
+
+ mock_source.assert_not_called()