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 less annoying crm pipeline and group tables (#114511)

Tom Owers6b902a21a898
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
index fb8773599f99..04a6874b199e 100644
--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
@@ -754,8 +754,6 @@
1 products/warehouse_sources/backend/temporal/data_imports/sources/lemlist/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/lemon_squeezy/lemon_squeezy.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/lemon_squeezy/settings.py
-1 products/warehouse_sources/backend/temporal/data_imports/sources/less_annoying_crm/less_annoying_crm.py
-1 products/warehouse_sources/backend/temporal/data_imports/sources/less_annoying_crm/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/lever/lever.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/lever/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/lightdash/settings.py
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 1ed24cb2431f..c8de11e9e4df 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
@@ -5096,14 +5096,14 @@ Note: Coverage is essentially complete: every list endpoint in the API nav (stor
## LessAnnoyingCRM — gaps
-Today (6): `contacts`, `events`, `notes`, `tasks`, `teams`, `users`
+Today (11): `contacts`, `events`, `group_memberships`, `groups`, `notes`, `pipeline_items`, `pipeline_statuses`, `pipelines`, `tasks`, `teams`, `users`
Diffed against: <https://account.lessannoyingcrm.com/api_docs/v2/Core_Functions/Pipeline_Items>
-- [ ] `GetPipelineItems (also GetPipelineItemsAttachedToContact)` — pipeline items are the deal/opportunity records - the core revenue object and the biggest hole in coverage (high)
-- [ ] `GetPipelines` — lookup resolving the pipeline ids that pipeline items and contacts carry (high)
-- [ ] `GetPipelineStatuses` — lookup resolving stage/status ids on pipeline items; required for any funnel or stage-duration analysis (high)
-- [ ] `GetGroups + GetContactsInGroup (GetGroupsAttachedToContact)` — group definitions plus the contact-to-group membership table used for segmentation (medium)
+- [x] `GetPipelineItems (also GetPipelineItemsAttachedToContact)` — pipeline items are the deal/opportunity records - the core revenue object and the biggest hole in coverage (high)
+- [x] `GetPipelines` — lookup resolving the pipeline ids that pipeline items and contacts carry (high)
+- [x] `GetPipelineStatuses` — lookup resolving stage/status ids on pipeline items; required for any funnel or stage-duration analysis (high)
+- [x] `GetGroups + GetContactsInGroup (GetGroupsAttachedToContact)` — group definitions plus the contact-to-group membership table used for segmentation (medium)
- [ ] `GetEmails (GetEmailsAttachedToContact)` — logged email activity per contact, the main engagement signal alongside notes and events (medium)
- [ ] `GetCustomFields` — lookup decoding the custom field ids that appear on contacts and pipeline items (medium)
- [ ] `GetRelationshipsAttachedToContacts` — contact-to-contact relationship graph (company/person links) used for account rollups (medium)
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
index a1d5beeed240..d55057d0a0ff 100644
--- 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
@@ -77,4 +77,68 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"DateUpdated": "When the event was last modified.",
},
},
+ "pipelines": {
+ "description": "Pipelines configured on the account, including archived ones. A pipeline tracks deals, leads or other processes through a set of statuses.",
+ "docs_url": "https://account.lessannoyingcrm.com/api_docs/v2/Settings_Functions/Pipelines",
+ "columns": {
+ "PipelineId": "Unique identifier for the pipeline.",
+ "Name": "Display name of the pipeline.",
+ "Color": "Display color of the pipeline.",
+ "DateCreated": "When the pipeline was created.",
+ "DateArchived": "When the pipeline was archived, if it has been archived.",
+ "Statuses": "The statuses (stages) defined on the pipeline.",
+ "Fields": "The custom fields defined on the pipeline's items.",
+ },
+ },
+ "pipeline_statuses": {
+ "description": "Statuses (stages) that pipeline items move through, across every pipeline.",
+ "docs_url": "https://account.lessannoyingcrm.com/api_docs/v2/Settings_Functions/Pipeline_Statuses",
+ "columns": {
+ "StatusId": "Unique identifier for the status.",
+ "PipelineId": "Identifier of the pipeline the status belongs to.",
+ "Name": "Display name of the status.",
+ "IsActive": "Whether items in this status are active (false for closed statuses).",
+ "Color": "Display color of the status.",
+ "DateCreated": "When the status was created.",
+ },
+ },
+ "pipeline_items": {
+ "description": "Pipeline items (deals, leads and other tracked processes) attached to contacts, in active and closed statuses of every non-archived pipeline.",
+ "docs_url": "https://account.lessannoyingcrm.com/api_docs/v2/Core_Functions/Pipeline_Items",
+ "columns": {
+ "PipelineItemId": "Unique identifier for the pipeline item.",
+ "PipelineId": "Identifier of the pipeline the item belongs to.",
+ "StatusId": "Identifier of the item's current status in the pipeline.",
+ "ContactId": "Identifier of the contact or company the item is attached to.",
+ "DateCreated": "When the pipeline item was created.",
+ "CreatedBy": "Identifier of the user who created the item.",
+ "LastUpdate": "When the pipeline item was last modified.",
+ "LastUpdatedBy": "Identifier of the user who last modified the item.",
+ "NumberOfUpdates": "How many times the item has been updated.",
+ "LastNote": "The most recent note recorded on the item.",
+ "PipelineMetaData": "Summary of the item's pipeline, such as its name.",
+ "StatusMetaData": "Summary of the item's status, such as its name.",
+ "ContactMetaData": "Summary of the attached contact, such as its name and assigned user.",
+ },
+ },
+ "groups": {
+ "description": "Groups used to segment contacts and companies.",
+ "docs_url": "https://account.lessannoyingcrm.com/api_docs/v2/Settings_Functions/Groups",
+ "columns": {
+ "GroupId": "Unique identifier for the group.",
+ "Name": "Display name of the group.",
+ "Sharing": "Who the group is shared with.",
+ "TeamIds": "Identifiers of the teams the group is shared with.",
+ "Color": "Display color of the group.",
+ },
+ },
+ "group_memberships": {
+ "description": "Which contacts and companies belong to which groups. One row per contact per group.",
+ "docs_url": "https://account.lessannoyingcrm.com/api_docs/v2/Core_Functions/Group_Memberships",
+ "columns": {
+ "GroupId": "Identifier of the group.",
+ "ContactId": "Identifier of the contact or company in the group.",
+ "ContactMetaData": "Summary of the contact, such as its name and assigned user.",
+ },
+ },
}
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
index ef14f60f4e11..0bc36a0e91a3 100644
--- 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
@@ -1,4 +1,5 @@
import dataclasses
+from collections.abc import Iterator
from typing import Any, Optional
from requests import Request, Response
@@ -22,6 +23,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.less_annoy
WIDE_WINDOW_END,
WIDE_WINDOW_START,
LessAnnoyingCRMEndpointConfig,
+ LessAnnoyingCRMFanoutConfig,
)
# Single flat RPC endpoint — every call is a POST here with a {"Function", "Parameters"} body.
@@ -52,11 +54,13 @@ LESS_ANNOYING_CRM_RESPONSE_ACTIONS: list[ResponseAction] = [
]
[email protected](frozen=True)
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
+ # Fan-out tables only: the parent (pipeline / group) whose child pages `page` points into.
+ parent_id: Optional[str] = None
class LessAnnoyingCRMPaginator(BasePaginator):
@@ -130,9 +134,105 @@ def _build_parameters(config: LessAnnoyingCRMEndpointConfig) -> dict[str, Any]:
parameters["SortBy"] = config.sort_by
if config.sort_direction:
parameters["SortDirection"] = config.sort_direction
+ parameters.update(config.parameters)
return parameters
+def _rest_config(
+ api_key: str,
+ name: str,
+ function: str,
+ parameters: dict[str, Any],
+ data_selector: Optional[str],
+ paginator: BasePaginator,
+) -> RESTAPIConfig:
+ endpoint_def: Endpoint = {
+ "path": "",
+ "method": "POST",
+ "json": {"Function": function, "Parameters": parameters},
+ "data_selector": data_selector,
+ "paginator": paginator,
+ "response_actions": LESS_ANNOYING_CRM_RESPONSE_ACTIONS,
+ }
+ resource_def: EndpointResource = {
+ "name": name,
+ "endpoint": endpoint_def,
+ }
+ return {
+ "client": {
+ "base_url": LESS_ANNOYING_CRM_BASE_URL,
+ # LACRM sends the raw API key as the Authorization header value (no Bearer prefix). Framework
+ # auth redacts it from logs and error messages; only the non-secret content-type is set here.
+ "headers": {"Content-Type": "application/json"},
+ "auth": {"type": "api_key", "api_key": api_key, "name": "Authorization", "location": "header"},
+ },
+ "resources": [resource_def],
+ }
+
+
+def _parent_rows(api_key: str, fanout: LessAnnoyingCRMFanoutConfig, team_id: int, job_id: str) -> list[dict[str, Any]]:
+ paginator: BasePaginator = (
+ LessAnnoyingCRMPaginator(page_size=PAGE_SIZE) if fanout.parent_paginated else SinglePagePaginator()
+ )
+ parameters: dict[str, Any] = {"MaxNumberOfResults": PAGE_SIZE} if fanout.parent_paginated else {}
+ rest_config = _rest_config(
+ api_key, "parents", fanout.parent_function, parameters, fanout.parent_data_selector, paginator
+ )
+ resource = rest_api_resource(rest_config, team_id, job_id, None)
+ return [row for page in resource for row in page if row.get(fanout.parent_id_field)]
+
+
+def _fanout_items(
+ api_key: str,
+ endpoint: str,
+ config: LessAnnoyingCRMEndpointConfig,
+ fanout: LessAnnoyingCRMFanoutConfig,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[LessAnnoyingCRMResumeConfig],
+) -> Iterator[Any]:
+ parents = _parent_rows(api_key, fanout, team_id, job_id)
+ parent_ids = [str(parent[fanout.parent_id_field]) for parent in parents]
+
+ start_index, start_page = 0, 1
+ if resumable_source_manager.can_resume():
+ resume = resumable_source_manager.load_state()
+ # A parent deleted since the checkpoint restarts the fan-out; merge dedupes the re-read rows.
+ if resume is not None and resume.parent_id in parent_ids:
+ start_index, start_page = parent_ids.index(resume.parent_id), resume.page
+
+ for index in range(start_index, len(parents)):
+ parent_id = parent_ids[index]
+
+ def save_checkpoint(state: Optional[dict[str, Any]], parent_id: str = parent_id) -> None:
+ if state and state.get("page") is not None:
+ resumable_source_manager.save_state(
+ LessAnnoyingCRMResumeConfig(page=int(state["page"]), parent_id=parent_id)
+ )
+
+ page = start_page if index == start_index else 1
+ # Every row of the previous parent is yielded, so a hand-off here resumes at this parent.
+ resumable_source_manager.save_state(LessAnnoyingCRMResumeConfig(page=page, parent_id=parent_id))
+ resumable_source_manager.safe_point()
+ parameters = {**_build_parameters(config), **fanout.child_parameters(parents[index])}
+ resource = rest_api_resource(
+ _rest_config(
+ api_key,
+ endpoint,
+ config.function,
+ parameters,
+ config.data_selector,
+ LessAnnoyingCRMPaginator(page_size=PAGE_SIZE),
+ ),
+ team_id,
+ job_id,
+ None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state={"page": page} if page > 1 else None,
+ )
+ yield from resource
+
+
def validate_credentials(api_key: str) -> bool:
"""Confirm the API key is genuine with the cheapest possible probe.
@@ -164,34 +264,29 @@ def less_annoying_crm_source(
db_incremental_field_last_value: Optional[Any] = None,
) -> SourceResponse:
config = LESS_ANNOYING_CRM_ENDPOINTS[endpoint]
+ partition_kwargs: dict[str, Any] = {
+ "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,
+ }
+
+ fanout = config.fanout
+ if fanout is not None:
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: _fanout_items(api_key, endpoint, config, fanout, team_id, job_id, resumable_source_manager),
+ primary_keys=config.primary_keys,
+ **partition_kwargs,
+ )
paginator: BasePaginator = (
LessAnnoyingCRMPaginator(page_size=PAGE_SIZE) if config.paginated else SinglePagePaginator()
)
-
- endpoint_def: Endpoint = {
- "path": "",
- "method": "POST",
- "json": {"Function": config.function, "Parameters": _build_parameters(config)},
- "data_selector": config.data_selector,
- "paginator": paginator,
- "response_actions": LESS_ANNOYING_CRM_RESPONSE_ACTIONS,
- }
- resource_def: EndpointResource = {
- "name": endpoint,
- "endpoint": endpoint_def,
- }
-
- rest_config: RESTAPIConfig = {
- "client": {
- "base_url": LESS_ANNOYING_CRM_BASE_URL,
- # LACRM sends the raw API key as the Authorization header value (no Bearer prefix). Framework
- # auth redacts it from logs and error messages; only the non-secret content-type is set here.
- "headers": {"Content-Type": "application/json"},
- "auth": {"type": "api_key", "api_key": api_key, "name": "Authorization", "location": "header"},
- },
- "resources": [resource_def],
- }
+ rest_config = _rest_config(
+ api_key, endpoint, config.function, _build_parameters(config), config.data_selector, paginator
+ )
initial_paginator_state: Optional[dict[str, Any]] = None
if config.paginated and resumable_source_manager.can_resume():
@@ -218,10 +313,6 @@ def less_annoying_crm_source(
name=endpoint,
items=lambda: resource,
primary_keys=config.primary_keys,
- partition_count=1,
- partition_size=1,
- partition_mode="datetime" if config.partition_key else None,
- partition_format="month" if config.partition_key else None,
- partition_keys=[config.partition_key] if config.partition_key else None,
column_hints=resource.column_hints,
+ **partition_kwargs,
)
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
index 32f937ba63d3..eb41a11fb746 100644
--- 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
@@ -1,5 +1,6 @@
+from collections.abc import Callable
from dataclasses import dataclass, field
-from typing import Optional
+from typing import Any, Optional
from products.warehouse_sources.backend.types import IncrementalField
@@ -8,7 +9,30 @@ from products.warehouse_sources.backend.types import IncrementalField
# function that returns it, plus how to page through and where the records live in the response.
-@dataclass
+@dataclass(frozen=True)
+class LessAnnoyingCRMFanoutConfig:
+ # Function listing the parents (GetPipelines / GetGroups). Each parent's child call is paged on
+ # its own, and the parent list is small enough to read in full before the first child call.
+ parent_function: str
+ parent_data_selector: Optional[str]
+ parent_paginated: bool
+ parent_id_field: str
+ # Builds the child's per-parent Parameters from a parent row.
+ child_parameters: Callable[[dict[str, Any]], dict[str, Any]]
+
+
+def _pipeline_item_parameters(pipeline: dict[str, Any]) -> dict[str, Any]:
+ # An empty StatusFilter returns only items in active statuses, so pass every status the pipeline
+ # has to include closed (won/lost) items too.
+ status_ids = [status["StatusId"] for status in pipeline.get("Statuses") or [] if status.get("StatusId")]
+ return {"PipelineId": pipeline["PipelineId"], "StatusFilter": status_ids}
+
+
+def _group_membership_parameters(group: dict[str, Any]) -> dict[str, Any]:
+ return {"GroupId": group["GroupId"]}
+
+
+@dataclass(frozen=True)
class LessAnnoyingCRMEndpointConfig:
name: str
# LACRM Function name sent in the request body (e.g. "GetContacts").
@@ -34,6 +58,10 @@ class LessAnnoyingCRMEndpointConfig:
# without a `SortBy` there. Sending an unsupported `SortBy` to those functions would be rejected.
sort_by: Optional[str] = None
sort_direction: Optional[str] = None
+ # Constant extra Parameters for the function (e.g. IncludeArchivedPipelines).
+ parameters: dict[str, Any] = field(default_factory=dict)
+ # Set for functions that need a parent id (GetPipelineItems, GetContactsInGroup).
+ fanout: Optional[LessAnnoyingCRMFanoutConfig] = None
incremental_fields: list[IncrementalField] = field(default_factory=list)
should_sync_default: bool = True
@@ -92,6 +120,60 @@ LESS_ANNOYING_CRM_ENDPOINTS: dict[str, LessAnnoyingCRMEndpointConfig] = {
primary_keys=["EventId"],
partition_key="DateCreated",
),
+ "pipelines": LessAnnoyingCRMEndpointConfig(
+ name="pipelines",
+ function="GetPipelines",
+ data_selector=None,
+ primary_keys=["PipelineId"],
+ paginated=False,
+ partition_key="DateCreated",
+ # Archived pipelines are kept so pipeline ids on older records still resolve.
+ parameters={"IncludeArchivedPipelines": True},
+ ),
+ "pipeline_statuses": LessAnnoyingCRMEndpointConfig(
+ name="pipeline_statuses",
+ function="GetPipelineStatuses",
+ data_selector=None,
+ primary_keys=["StatusId"],
+ paginated=False,
+ partition_key="DateCreated",
+ ),
+ "pipeline_items": LessAnnoyingCRMEndpointConfig(
+ name="pipeline_items",
+ function="GetPipelineItems",
+ data_selector="Results",
+ primary_keys=["PipelineItemId"],
+ partition_key="DateCreated",
+ sort_by="DateCreated",
+ sort_direction="Ascending",
+ fanout=LessAnnoyingCRMFanoutConfig(
+ parent_function="GetPipelines",
+ parent_data_selector=None,
+ parent_paginated=False,
+ parent_id_field="PipelineId",
+ child_parameters=_pipeline_item_parameters,
+ ),
+ ),
+ "groups": LessAnnoyingCRMEndpointConfig(
+ name="groups",
+ function="GetGroups",
+ data_selector="Results",
+ primary_keys=["GroupId"],
+ ),
+ "group_memberships": LessAnnoyingCRMEndpointConfig(
+ name="group_memberships",
+ function="GetContactsInGroup",
+ data_selector="Results",
+ # A contact can be in many groups, so ContactId alone is not unique across the table.
+ primary_keys=["GroupId", "ContactId"],
+ fanout=LessAnnoyingCRMFanoutConfig(
+ parent_function="GetGroups",
+ parent_data_selector="Results",
+ parent_paginated=True,
+ parent_id_field="GroupId",
+ child_parameters=_group_membership_parameters,
+ ),
+ ),
}
ENDPOINTS = tuple(LESS_ANNOYING_CRM_ENDPOINTS.keys())
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 12ffa7988f02..3874ea010698 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
@@ -52,7 +52,7 @@ class LessAnnoyingCRMSource(ResumableSource[LessAnnoyingCRMSourceConfig, LessAnn
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.
+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`, `GetEvents`, `GetPipelines`, `GetPipelineStatuses`, `GetPipelineItems`, `GetGroups` and `GetContactsInGroup` 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",
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
index 6cd6a8710b27..90b9e056e701 100644
--- 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
@@ -106,6 +106,73 @@ class TestPagination:
assert bodies[0]["Parameters"]["Page"] == 4
+class TestFanout:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_pipeline_items_walk_every_pipeline_with_all_statuses(self, MockSession) -> None:
+ session = MockSession.return_value
+ bodies = _wire(
+ session,
+ [
+ _response(
+ [
+ {
+ "PipelineId": "p1",
+ "Statuses": [{"StatusId": "open"}, {"StatusId": "won", "IsActive": False}],
+ },
+ {"PipelineId": "p2", "Statuses": []},
+ ]
+ ),
+ _response({"Results": [{"PipelineItemId": "i1"}], "HasMoreResults": True}),
+ _response({"Results": [{"PipelineItemId": "i2"}], "HasMoreResults": False}),
+ _response({"Results": [{"PipelineItemId": "i3"}], "HasMoreResults": False}),
+ ],
+ )
+
+ manager = _make_manager()
+ rows = _rows(_source("pipeline_items", manager))
+
+ assert rows == [{"PipelineItemId": "i1"}, {"PipelineItemId": "i2"}, {"PipelineItemId": "i3"}]
+ assert bodies[0]["Function"] == "GetPipelines"
+ child_params = [(b["Parameters"]["PipelineId"], b["Parameters"]["Page"]) for b in bodies[1:]]
+ assert child_params == [("p1", 1), ("p1", 2), ("p2", 1)]
+ # Closed statuses are only returned when named explicitly in StatusFilter.
+ assert bodies[1]["Parameters"]["StatusFilter"] == ["open", "won"]
+ assert manager.save_state.call_args_list == [
+ mock.call(LessAnnoyingCRMResumeConfig(page=1, parent_id="p1")),
+ mock.call(LessAnnoyingCRMResumeConfig(page=2, parent_id="p1")),
+ mock.call(LessAnnoyingCRMResumeConfig(page=1, parent_id="p2")),
+ ]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ @pytest.mark.parametrize(
+ "resume,expected",
+ [
+ # Resumes inside the saved group at the saved page, skipping groups already synced.
+ (LessAnnoyingCRMResumeConfig(page=3, parent_id="g2"), [("g2", 3)]),
+ # A group deleted since the checkpoint restarts the fan-out from the first group.
+ (LessAnnoyingCRMResumeConfig(page=3, parent_id="gone"), [("g1", 1), ("g2", 1)]),
+ ],
+ )
+ def test_group_memberships_resume(
+ self, MockSession, resume: LessAnnoyingCRMResumeConfig, expected: list[tuple[str, int]]
+ ) -> None:
+ session = MockSession.return_value
+ members = {"Results": [{"GroupId": "g", "ContactId": "c"}], "HasMoreResults": False}
+ bodies = _wire(
+ session,
+ [
+ _response({"Results": [{"GroupId": "g1"}, {"GroupId": "g2"}], "HasMoreResults": False}),
+ _response(members),
+ _response(members),
+ ],
+ )
+
+ _rows(_source("group_memberships", _make_manager(resume)))
+
+ assert bodies[0]["Function"] == "GetGroups"
+ assert [(b["Parameters"]["GroupId"], b["Parameters"]["Page"]) for b in bodies[1:]] == expected
+
+
class TestRequestBody:
@mock.patch(CLIENT_SESSION_PATCH)
def test_tasks_send_required_date_window_and_expand_dict_results(self, MockSession) -> None: