Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(warehouse_sources): add AgileCRM tickets, notes and pipeline tables (#98105)

Tom Owers086088cef00e
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 6f2346e57b72..a4df51dcb5c0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -91,10 +91,10 @@ Today (5): `companies`, `contacts`, `deals`, `events`, `tasks`
Diffed against: <https://raw.githubusercontent.com/agilecrm/rest-api/master/README.md>
-- [ ] `milestone/pipelines (GET /dev/api/milestone/pipelines)` — tracks and their milestones - the lookup table decoding the milestone field on every synced deal (high)
-- [ ] `tickets (GET /dev/api/tickets/filter)` — help desk tickets, an entire product area with no coverage today (high)
-- [ ] `notes (GET /dev/api/notes, /dev/api/contacts/{id}/notes, /dev/api/opportunity/{id}/notes)` — free-text notes attached to synced contacts and deals (medium)
-- [ ] `ticket notes/messages (GET /dev/api/tickets/notes/{ticket-id})` — the conversation thread inside each ticket (medium)
+- [x] `milestone/pipelines (GET /dev/api/milestone/pipelines)` — tracks and their milestones - the lookup table decoding the milestone field on every synced deal (high) — added as `pipelines`
+- [x] `tickets (GET /dev/api/tickets/filter)` — help desk tickets, an entire product area with no coverage today (high)
+- [x] `notes (GET /dev/api/notes, /dev/api/contacts/{id}/notes, /dev/api/opportunity/{id}/notes)` — free-text notes attached to synced contacts and deals (medium) — added as `contact_notes` + `deal_notes` (there is no account-wide GET /dev/api/notes; notes are only exposed per parent)
+- [x] `ticket notes/messages (GET /dev/api/tickets/notes/{ticket-id})` — the conversation thread inside each ticket (medium) — added as `ticket_notes`
- [ ] `workflows / campaigns (GET /dev/api/workflows)` — marketing campaign definitions that contact automation activity references (medium)
- [ ] `documents (GET /dev/api/documents/contact/{contact_id}/docs)` — files attached to contacts (low)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/agilecrm.py b/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/agilecrm.py
index 1be9872895ac..2a7bb36fac9e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/agilecrm.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/agilecrm.py
@@ -1,13 +1,22 @@
import re
import dataclasses
+from collections.abc import Iterator
from typing import Any, Optional
-from requests import Request, Response
+from requests import Request, Response, Session
from requests.auth import HTTPBasicAuth
from products.warehouse_sources.backend.temporal.data_imports.sources.agilecrm.settings import (
AGILECRM_ENDPOINTS,
+ AGILECRM_FANOUT_ENDPOINTS,
BASE_URL_TEMPLATE,
+ DEFAULT_PAGE_SIZE,
+ TICKETS_ALL_FILTER_NAME,
+ TICKETS_FILTERS_PATH,
+ TICKETS_LIST_PATH,
+ TICKETS_PRIMARY_KEYS,
+ TICKETS_SORT_KEY,
+ AgileCRMFanoutConfig,
)
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 (
@@ -95,6 +104,102 @@ def _strip_cursor(item: dict[str, Any]) -> dict[str, Any]:
return {k: v for k, v in item.items() if k != "cursor"}
+def _basic_auth_session(email: str, api_key: str) -> Session:
+ session = make_tracked_session(headers={"Accept": "application/json"}, redact_values=(api_key,))
+ # Agile CRM authenticates with HTTP Basic: account email as username, API key as password.
+ session.auth = HTTPBasicAuth(email, api_key)
+ return session
+
+
+def _paginate(
+ session: Session, url: str, page_size: int, extra_params: Optional[dict[str, Any]] = None
+) -> Iterator[list[dict[str, Any]]]:
+ """Yield each page of a cursor-paginated list endpoint, following the `cursor` on its last item.
+
+ A missing cursor or a short page (fewer items than `page_size`) is terminal — the same rule the
+ `RESTAPIConfig`-driven endpoints use, reimplemented here because ticket and fan-out endpoints
+ need extra path/param handling the declarative resource config can't express.
+ """
+ cursor: Optional[str] = None
+ while True:
+ params: dict[str, Any] = {"page_size": page_size}
+ if extra_params:
+ params.update(extra_params)
+ if cursor is not None:
+ params["cursor"] = cursor
+
+ response = session.get(url, params=params)
+ response.raise_for_status()
+ body = response.json()
+ if not isinstance(body, list):
+ # Known list endpoints return a bare JSON array; an object body means the shape changed.
+ raise ValueError(f"Required a list response body from {url}, got {type(body).__name__}")
+ if not body:
+ return
+
+ yield [_strip_cursor(item) for item in body if isinstance(item, dict)]
+
+ last_item = body[-1]
+ cursor = last_item.get("cursor") if isinstance(last_item, dict) else None
+ if not cursor or len(body) < page_size:
+ return
+
+
+def _resolve_all_tickets_filter_id(session: Session, base: str) -> Optional[str]:
+ # `tickets/filter` needs a saved-filter id. Prefer the "All Tickets" system filter (returns every
+ # ticket); fall back to any default filter, then the first filter. None means no filters exist.
+ response = session.get(f"{base}/{TICKETS_FILTERS_PATH}")
+ response.raise_for_status()
+ filters = response.json()
+ if not isinstance(filters, list) or not filters:
+ return None
+
+ named = [f for f in filters if isinstance(f, dict) and f.get("name") == TICKETS_ALL_FILTER_NAME]
+ default = [f for f in filters if isinstance(f, dict) and f.get("is_default_filter")]
+ for candidate in (*named, *default, *filters):
+ if isinstance(candidate, dict) and candidate.get("id") is not None:
+ return str(candidate["id"])
+ return None
+
+
+def _ticket_pages(session: Session, base: str, page_size: int) -> Iterator[list[dict[str, Any]]]:
+ filter_id = _resolve_all_tickets_filter_id(session, base)
+ if filter_id is None:
+ return
+ yield from _paginate(
+ session,
+ f"{base}/{TICKETS_LIST_PATH}",
+ page_size,
+ {"filter_id": filter_id, "global_sort_key": TICKETS_SORT_KEY},
+ )
+
+
+def _iter_parent_ids(session: Session, base: str, config: AgileCRMFanoutConfig) -> Iterator[Any]:
+ if config.parent == "tickets":
+ pages = _ticket_pages(session, base, config.page_size)
+ else:
+ pages = _paginate(session, f"{base}/{config.parent_path}", config.page_size)
+ for page in pages:
+ for row in page:
+ parent_id = row.get("id")
+ if parent_id is not None:
+ yield parent_id
+
+
+def _fanout_pages(session: Session, base: str, config: AgileCRMFanoutConfig) -> Iterator[list[dict[str, Any]]]:
+ for parent_id in _iter_parent_ids(session, base, config):
+ child_url = f"{base}/{config.child_path_template.format(parent_id=parent_id)}"
+ response = session.get(child_url)
+ response.raise_for_status()
+ body = response.json()
+ # Child lists are bare arrays; a parent with no children can return an empty body.
+ if not isinstance(body, list):
+ continue
+ rows = [{**_strip_cursor(item), config.parent_id_field: parent_id} for item in body if isinstance(item, dict)]
+ if rows:
+ yield rows
+
+
def agilecrm_source(
domain: str,
email: str,
@@ -105,11 +210,30 @@ def agilecrm_source(
resumable_source_manager: ResumableSourceManager[AgileCRMResumeConfig],
db_incremental_field_last_value: Optional[Any] = None,
) -> SourceResponse:
+ base = base_url(domain)
+
+ # Tickets and fan-out tables need per-parent requests or filter resolution that the declarative
+ # resource config can't express, so they stream through a custom generator. All are full refresh.
+ if endpoint == "tickets":
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: _ticket_pages(_basic_auth_session(email, api_key), base, DEFAULT_PAGE_SIZE),
+ primary_keys=list(TICKETS_PRIMARY_KEYS),
+ )
+
+ if endpoint in AGILECRM_FANOUT_ENDPOINTS:
+ fanout_config = AGILECRM_FANOUT_ENDPOINTS[endpoint]
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: _fanout_pages(_basic_auth_session(email, api_key), base, fanout_config),
+ primary_keys=list(fanout_config.primary_keys),
+ )
+
config = AGILECRM_ENDPOINTS[endpoint]
rest_config: RESTAPIConfig = {
"client": {
- "base_url": base_url(domain),
+ "base_url": base,
"headers": {"Accept": "application/json"},
# Agile CRM authenticates with HTTP Basic: account email as username, API key as password.
"auth": {"type": "http_basic", "username": email, "password": api_key},
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/canonical_descriptions.py
index 962f1c686212..469f41d923eb 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/canonical_descriptions.py
@@ -76,4 +76,71 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"created_time": "Unix epoch timestamp of when the event was created.",
},
},
+ "pipelines": {
+ "description": "Deal tracks (pipelines) and their milestones — the lookup that decodes the milestone stage on each deal.",
+ "docs_url": "https://github.com/agilecrm/rest-api#7-track--milestones-api",
+ "columns": {
+ "id": "Unique identifier for the track (pipeline).",
+ "name": "Name of the track.",
+ "milestones": "Comma-separated, ordered list of the track's milestone (stage) names.",
+ },
+ },
+ "tickets": {
+ "description": "Help-desk tickets raised by requesters, with their status, priority and assignment.",
+ "docs_url": "https://github.com/agilecrm/rest-api#10-help-desks-api",
+ "columns": {
+ "id": "Unique identifier for the ticket.",
+ "subject": "Subject line of the ticket.",
+ "status": "Ticket status (e.g. NEW, OPEN, PENDING, CLOSED).",
+ "type": "Ticket type (e.g. PROBLEM, QUESTION, INCIDENT).",
+ "priority": "Ticket priority (e.g. LOW, MEDIUM, HIGH, URGENT).",
+ "source": "Channel the ticket came in through (e.g. EMAIL).",
+ "requester_name": "Name of the person who raised the ticket.",
+ "requester_email": "Email address of the person who raised the ticket.",
+ "groupID": "Identifier of the group the ticket is assigned to.",
+ "assigneeID": "Identifier of the Agile CRM user the ticket is assigned to.",
+ "contactID": "Identifier of the contact linked to the ticket.",
+ "created_time": "Unix epoch (milliseconds) when the ticket was created.",
+ "last_updated_time": "Unix epoch (milliseconds) when the ticket was last updated.",
+ },
+ },
+ "contact_notes": {
+ "description": "Free-text notes attached to contacts. One row per note per contact it is related to.",
+ "docs_url": "https://github.com/agilecrm/rest-api#43-gets-notes-related-to-specific-contact-",
+ "columns": {
+ "id": "Unique identifier for the note.",
+ "contact_id": "Identifier of the contact this note row was fetched for.",
+ "subject": "Subject of the note.",
+ "description": "Body text of the note.",
+ "contact_ids": "Identifiers of all contacts the note is related to.",
+ "created_time": "Unix epoch timestamp of when the note was created.",
+ },
+ },
+ "deal_notes": {
+ "description": "Free-text notes attached to deals (opportunities). One row per note per deal.",
+ "docs_url": "https://github.com/agilecrm/rest-api#47-gets-notes-related-to-specific-deal-",
+ "columns": {
+ "id": "Unique identifier for the note.",
+ "deal_id": "Identifier of the deal this note row was fetched for.",
+ "subject": "Subject of the note.",
+ "description": "Body text of the note.",
+ "entity_type": "Entity type the note is related to.",
+ "created_time": "Unix epoch timestamp of when the note was created.",
+ },
+ },
+ "ticket_notes": {
+ "description": "The message and note thread inside each help-desk ticket. One row per message.",
+ "docs_url": "https://github.com/agilecrm/rest-api#105-get-all-messages-within-a-ticket-",
+ "columns": {
+ "id": "Unique identifier for the ticket message.",
+ "ticket_id": "Identifier of the ticket this message belongs to.",
+ "plain_text": "Plain-text body of the message.",
+ "html_text": "HTML body of the message.",
+ "note_type": "Visibility of the message (e.g. PUBLIC, PRIVATE).",
+ "created_by": "Who created the message (e.g. REQUESTER, AGENT).",
+ "requester_name": "Name of the requester on the message.",
+ "requester_email": "Email address of the requester on the message.",
+ "created_time": "Unix epoch (milliseconds) when the message was created.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/settings.py
index 9fc55094fde0..32f7b9e7c3ed 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/settings.py
@@ -36,6 +36,69 @@ AGILECRM_ENDPOINTS: dict[str, AgileCRMEndpointConfig] = {
"tasks": AgileCRMEndpointConfig(name="tasks", path="tasks"),
# Calendar events.
"events": AgileCRMEndpointConfig(name="events", path="events"),
+ # Tracks and their milestones — the lookup that decodes the `milestone` field on every deal.
+ # A small, un-paginated list; the cursor paginator ends after the first (short) page.
+ "pipelines": AgileCRMEndpointConfig(name="pipelines", path="milestone/pipelines"),
}
-ENDPOINTS = tuple(AGILECRM_ENDPOINTS.keys())
+# Help-desk tickets. Listing goes through `tickets/filter`, which requires a saved-filter id; we
+# resolve the account's "All Tickets" system filter from `tickets/filters` at sync time. Not part of
+# AGILECRM_ENDPOINTS because it needs that extra resolution step rather than the plain list path.
+TICKETS_LIST_PATH = "tickets/filter"
+TICKETS_FILTERS_PATH = "tickets/filters"
+# The system filter that returns every ticket regardless of status.
+TICKETS_ALL_FILTER_NAME = "All Tickets"
+# Newest-first is the only stable sort the endpoint documents; order is irrelevant for full refresh.
+TICKETS_SORT_KEY = "-last_updated_time"
+TICKETS_PRIMARY_KEYS = ["id"]
+
+
+@dataclass(frozen=True)
+class AgileCRMFanoutConfig:
+ name: str
+ # Endpoint name whose rows supply the parent ids to fan out over.
+ parent: str
+ # List path for the parent resource (unused when `parent` is "tickets", which needs filter resolution).
+ parent_path: str
+ # Child path with a single `{parent_id}` placeholder, e.g. "contacts/{parent_id}/notes".
+ child_path_template: str
+ # Column the parent id is written to on each child row.
+ parent_id_field: str
+ # Composite key: a note/message id is only unique within its parent, so the parent id is part of it.
+ primary_keys: list[str]
+ page_size: int = DEFAULT_PAGE_SIZE
+
+
+# Fan-out tables: iterate a parent resource, then read each parent's child list. Agile CRM exposes
+# notes and ticket messages only per parent — there is no account-wide list endpoint for them.
+AGILECRM_FANOUT_ENDPOINTS: dict[str, AgileCRMFanoutConfig] = {
+ # Notes attached to contacts.
+ "contact_notes": AgileCRMFanoutConfig(
+ name="contact_notes",
+ parent="contacts",
+ parent_path="contacts",
+ child_path_template="contacts/{parent_id}/notes",
+ parent_id_field="contact_id",
+ primary_keys=["contact_id", "id"],
+ ),
+ # Notes attached to deals (opportunities).
+ "deal_notes": AgileCRMFanoutConfig(
+ name="deal_notes",
+ parent="deals",
+ parent_path="opportunity",
+ child_path_template="opportunity/{parent_id}/notes",
+ parent_id_field="deal_id",
+ primary_keys=["deal_id", "id"],
+ ),
+ # The message/note thread inside each ticket.
+ "ticket_notes": AgileCRMFanoutConfig(
+ name="ticket_notes",
+ parent="tickets",
+ parent_path=TICKETS_LIST_PATH,
+ child_path_template="tickets/notes/{parent_id}",
+ parent_id_field="ticket_id",
+ primary_keys=["ticket_id", "id"],
+ ),
+}
+
+ENDPOINTS = (*AGILECRM_ENDPOINTS.keys(), "tickets", *AGILECRM_FANOUT_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/tests/test_agilecrm.py b/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/tests/test_agilecrm.py
index bdc278ab52fe..ec65fb64731a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/tests/test_agilecrm.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/tests/test_agilecrm.py
@@ -185,6 +185,87 @@ class TestPagination:
_rows(_source(_make_manager()))
+def _mock_get_session(responses: list[Response]) -> tuple[mock.MagicMock, list[tuple[str, dict[str, Any]]]]:
+ """A mock session whose `.get(url, params=...)` returns the queued responses in order.
+
+ Returns the session and a list of (url, params) captured per call.
+ """
+ session = mock.MagicMock()
+ calls: list[tuple[str, dict[str, Any]]] = []
+
+ def _get(url: str, params: Any = None) -> Response:
+ calls.append((url, dict(params) if params else {}))
+ return responses[len(calls) - 1]
+
+ session.get.side_effect = _get
+ return session, calls
+
+
+class TestTickets:
+ @mock.patch(AGILECRM_SESSION_PATCH)
+ def test_lists_via_all_tickets_filter(self, mock_make_session) -> None:
+ # The default filter list has "All Tickets" second — listing must resolve it, not grab the first.
+ filters = [
+ {"id": 1, "name": "New Tickets", "is_default_filter": True},
+ {"id": 2, "name": "All Tickets", "is_default_filter": True},
+ ]
+ tickets_page = [{"id": 100, "subject": "x", "cursor": "C"}] # short page -> terminal
+ session, calls = _mock_get_session([_response(filters), _response(tickets_page)])
+ mock_make_session.return_value = session
+
+ rows = _rows(_source(_make_manager(), endpoint="tickets"))
+
+ assert [r["id"] for r in rows] == [100]
+ assert all("cursor" not in r for r in rows)
+ assert calls[1][0].endswith("/tickets/filter")
+ assert calls[1][1]["filter_id"] == "2"
+ assert calls[1][1]["global_sort_key"] == "-last_updated_time"
+
+ @mock.patch(AGILECRM_SESSION_PATCH)
+ def test_no_filters_yields_nothing(self, mock_make_session) -> None:
+ # Without a saved filter there is no way to list tickets, so the table stays empty.
+ session, calls = _mock_get_session([_response([])])
+ mock_make_session.return_value = session
+
+ assert _rows(_source(_make_manager(), endpoint="tickets")) == []
+ assert len(calls) == 1
+
+
+class TestFanout:
+ @mock.patch(AGILECRM_SESSION_PATCH)
+ def test_contact_notes_inject_parent_id(self, mock_make_session) -> None:
+ contacts_page = [{"id": 1}, {"id": 2}] # short page -> terminal
+ notes_1 = [{"id": 10, "subject": "a"}]
+ notes_2 = [{"id": 11, "subject": "b", "cursor": "X"}]
+ session, calls = _mock_get_session([_response(contacts_page), _response(notes_1), _response(notes_2)])
+ mock_make_session.return_value = session
+
+ rows = _rows(_source(_make_manager(), endpoint="contact_notes"))
+
+ # Each note carries the id of the contact it was fetched for (part of the composite key), and
+ # the navigation cursor never leaks into a row.
+ assert rows == [
+ {"id": 10, "subject": "a", "contact_id": 1},
+ {"id": 11, "subject": "b", "contact_id": 2},
+ ]
+ assert calls[1][0].endswith("/contacts/1/notes")
+ assert calls[2][0].endswith("/contacts/2/notes")
+
+ @mock.patch(AGILECRM_SESSION_PATCH)
+ def test_ticket_notes_fan_out_over_tickets(self, mock_make_session) -> None:
+ # Parent enumeration for ticket messages goes through the ticket filter, then per-ticket notes.
+ filters = [{"id": 2, "name": "All Tickets", "is_default_filter": True}]
+ tickets_page = [{"id": 5}] # short page -> terminal
+ messages = [{"id": 50, "ticket_id": 5, "plain_text": "hi"}]
+ session, calls = _mock_get_session([_response(filters), _response(tickets_page), _response(messages)])
+ mock_make_session.return_value = session
+
+ rows = _rows(_source(_make_manager(), endpoint="ticket_notes"))
+
+ assert rows == [{"id": 50, "ticket_id": 5, "plain_text": "hi"}]
+ assert calls[2][0].endswith("/tickets/notes/5")
+
+
class TestValidateCredentials:
@parameterized.expand([("ok", 200, True), ("unauthorized", 401, False), ("forbidden", 403, False)])
def test_status_maps_to_bool(self, _name: str, status_code: int, expected: bool) -> None:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/tests/test_agilecrm_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/tests/test_agilecrm_source.py
index 297b8d38224f..26f7137f97ff 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/tests/test_agilecrm_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/agilecrm/tests/test_agilecrm_source.py
@@ -48,9 +48,19 @@ class TestValidateCredentials:
class TestPipelinePlumbing:
- def test_source_for_pipeline_passes_endpoint_and_primary_keys(self) -> None:
+ @parameterized.expand(
+ [
+ # Top-level list endpoints keyed on their own id.
+ ("contacts", "contacts", ["id"]),
+ ("tickets", "tickets", ["id"]),
+ # Fan-out children carry the parent id in their composite key so rows stay unique table-wide.
+ ("contact_notes", "contact_notes", ["contact_id", "id"]),
+ ("ticket_notes", "ticket_notes", ["ticket_id", "id"]),
+ ]
+ )
+ def test_source_for_pipeline_routes_endpoint(self, _name: str, endpoint: str, expected_keys: list[str]) -> None:
inputs = MagicMock()
- inputs.schema_name = "contacts"
+ inputs.schema_name = endpoint
response = AgileCRMSource().source_for_pipeline(_config(), MagicMock(), inputs)
- assert response.name == "contacts"
- assert response.primary_keys == ["id"]
+ assert response.name == endpoint
+ assert response.primary_keys == expected_keys