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): add four insightly tables from the coverage audit (#111526)

Tom Owers13de3137c126
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
index 9807709dc9a4..50900d38c8e2 100644
--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
@@ -690,7 +690,6 @@
1 products/warehouse_sources/backend/temporal/data_imports/sources/inngest/inngest.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/inngest/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/insightly/insightly.py
-1 products/warehouse_sources/backend/temporal/data_imports/sources/insightly/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/instagram/instagram.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/instagram/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/instana/instana.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 b6fdd29899ef..8a0899f077e1 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
@@ -4313,10 +4313,10 @@ Today (11): `Contacts`, `Emails`, `Events`, `Leads`, `Notes`, `Opportunities`, `
Diffed against: <https://api.insightly.com/v3.1/swagger/docs/v3.1>
-- [ ] `/PipelineStages` — lookup resolving PIPELINE_STAGE_ID on Opportunities and Projects - Pipelines is synced but its stages are not, so no funnel breakdown is possible (high)
-- [ ] `/OpportunityLineItem` — line-item revenue detail behind each opportunity; the deal header alone cannot break revenue down by product (high)
-- [ ] `/Opportunities/{id}/StateHistory` — won/lost/abandoned state transition history - the only source for sales-cycle and stage-velocity analysis (pair with /OpportunityStateReasons) (high)
-- [ ] `/LeadSources` — lookup resolving LEAD_SOURCE_ID on Leads - the core attribution dimension (high)
+- [x] `/PipelineStages` — lookup resolving PIPELINE_STAGE_ID on Opportunities and Projects - Pipelines is synced but its stages are not, so no funnel breakdown is possible (high)
+- [x] `/OpportunityLineItem` — line-item revenue detail behind each opportunity; the deal header alone cannot break revenue down by product (high)
+- [x] `/Opportunities/{id}/StateHistory` — won/lost/abandoned state transition history - the only source for sales-cycle and stage-velocity analysis (pair with /OpportunityStateReasons) (high)
+- [x] `/LeadSources` — lookup resolving LEAD_SOURCE_ID on Leads - the core attribution dimension (high)
- [ ] `/LeadStatuses` — lookup resolving LEAD_STATUS_ID on Leads, needed for any lead funnel (high)
- [ ] `/Ticket` — Insightly Service tickets, an entire product area with no table today (high)
- [ ] `/Quotation and /QuotationLineItem` — quotes and their line items, the pre-close revenue pipeline (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/insightly/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/insightly/canonical_descriptions.py
index 3d3d0525ddde..5c2799d27e53 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/insightly/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/insightly/canonical_descriptions.py
@@ -156,4 +156,58 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"FOR_PROJECTS": "Whether the pipeline applies to projects.",
},
},
+ "PipelineStages": {
+ "description": "Stages within each pipeline, marking how far an opportunity or project has progressed.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "STAGE_ID": "Unique identifier for the pipeline stage.",
+ "PIPELINE_ID": "ID of the pipeline the stage belongs to.",
+ "STAGE_NAME": "Name of the stage.",
+ "STAGE_ORDER": "Position of the stage within its pipeline.",
+ "ACTIVITYSET_ID": "ID of the activity set triggered when a record enters the stage, if any.",
+ "OWNER_USER_ID": "User ID of the stage owner.",
+ },
+ },
+ "LeadSources": {
+ "description": "Lead source values defined for your Insightly account, referenced by LEAD_SOURCE_ID on leads.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "LEAD_SOURCE_ID": "Unique identifier for the lead source.",
+ "LEAD_SOURCE": "Name of the lead source.",
+ "DEFAULT_VALUE": "Whether this is the default lead source for new leads.",
+ "FIELD_ORDER": "Display order of the lead source in pick lists.",
+ },
+ },
+ "OpportunityLineItem": {
+ "description": "Products on an opportunity, with quantity, pricing, and discount.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "OPPORTUNITY_ITEM_ID": "Unique identifier for the opportunity line item.",
+ "OPPORTUNITY_ID": "ID of the opportunity the line item belongs to.",
+ "PRICEBOOK_ENTRY_ID": "ID of the price book entry for the product.",
+ "CURRENCY_CODE": "Currency of the line item prices.",
+ "DESCRIPTION": "Line item description.",
+ "QUANTITY": "Quantity of the product.",
+ "LIST_PRICE": "List price of the product.",
+ "UNIT_PRICE": "Unit price charged for the product.",
+ "SUBTOTAL": "Line total before discount.",
+ "DISCOUNT": "Discount applied to the line item.",
+ "TOTAL_PRICE": "Line total after discount.",
+ "SERVICE_DATE": "Service date of the line item.",
+ "DATE_CREATED_UTC": "UTC timestamp when the line item was created.",
+ "DATE_UPDATED_UTC": "UTC timestamp when the line item was last modified (the incremental cursor).",
+ "CUSTOMFIELDS": "List of custom field values defined for your Insightly account.",
+ },
+ },
+ "OpportunityStateHistory": {
+ "description": "History of state changes (for example open, won, lost, abandoned) for each opportunity, with the reason given.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "OPPORTUNITY_ID": "ID of the opportunity whose state changed.",
+ "DATE_CHANGED_UTC": "UTC timestamp when the state changed.",
+ "FOR_OPPORTUNITY_STATE": "State the opportunity changed to.",
+ "STATE_REASON_ID": "ID of the reason recorded for the state change, if any.",
+ "STATE_REASON": "Reason recorded for the state change, if any.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/insightly/insightly.py b/products/warehouse_sources/backend/temporal/data_imports/sources/insightly/insightly.py
index 4e5d50cfdf55..fffa0ccedb6f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/insightly/insightly.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/insightly/insightly.py
@@ -8,16 +8,24 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.htt
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
RESTAPIConfig,
rest_api_resource,
+ rest_api_resources,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import HttpBasicAuth
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
OffsetPaginator,
+ SinglePagePaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ ClientConfig,
+ Endpoint,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import Endpoint
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
-from products.warehouse_sources.backend.temporal.data_imports.sources.insightly.settings import INSIGHTLY_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.insightly.settings import (
+ INSIGHTLY_ENDPOINTS,
+ InsightlyEndpointConfig,
+)
API_VERSION = "v3.1"
# Insightly caps list pages at 500 items (default is 100).
@@ -71,6 +79,84 @@ def _format_updated_after(value: Any) -> str:
return dt.strftime("%Y-%m-%dT%H:%M:%SZ")
+def _client_config(pod: str, api_key: str) -> ClientConfig:
+ return {
+ "base_url": base_url(pod),
+ "headers": {"Accept": "application/json"},
+ # HTTP Basic auth with the API key as the username and a blank password. Using the
+ # framework auth keeps the key out of raised error messages / logged URLs.
+ "auth": {"type": "http_basic", "username": api_key, "password": ""},
+ # Pin every request (including resume URLs) to api.<pod>.insightly.com — reinforces the
+ # pod normalization guard so credentials can never be sent off-host.
+ "allowed_hosts": [],
+ }
+
+
+def _offset_paginator() -> OffsetPaginator:
+ # Offset pagination with Insightly's `top`/`skip`; a short (< top) page is the last one.
+ return OffsetPaginator(limit=PAGE_SIZE, offset_param="skip", limit_param="top", total_path=None)
+
+
+def _source_response(endpoint: str, config: InsightlyEndpointConfig, items: Any) -> SourceResponse:
+ return SourceResponse(
+ name=endpoint,
+ items=items,
+ primary_keys=config.primary_keys,
+ # Insightly paginates in record-id (creation) order, so rows for a given sync arrive roughly
+ # oldest-first; DATE_UPDATED_UTC is not strictly monotonic across pages. We keep the same
+ # `updated_after_utc` filter on every page (offset pagination reuses the query), so an
+ # incremental sync never walks unbounded history — and if Insightly ever ignored the filter,
+ # the sync degrades to full-refresh cost, never incorrect data (merge dedupes on the id).
+ sort_mode="asc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="week" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
+
+
+def _fanout_source(pod: str, api_key: str, endpoint: str, team_id: int, job_id: str) -> SourceResponse:
+ config = INSIGHTLY_ENDPOINTS[endpoint]
+ assert config.fanout_parent is not None and config.parent_id_field is not None
+ parent_config = INSIGHTLY_ENDPOINTS[config.fanout_parent]
+
+ rest_config: RESTAPIConfig = {
+ "client": _client_config(pod, api_key),
+ "resources": [
+ {
+ "name": config.fanout_parent,
+ "endpoint": {
+ "path": parent_config.path,
+ # Only the id is needed from each parent row.
+ "params": {"brief": "true"},
+ "paginator": _offset_paginator(),
+ "data_selector_required": True,
+ },
+ },
+ {
+ "name": endpoint,
+ "endpoint": {
+ "path": config.path,
+ "params": {
+ "id": {"type": "resolve", "resource": config.fanout_parent, "field": config.parent_id_field}
+ },
+ "paginator": SinglePagePaginator(),
+ "data_selector_required": True,
+ # A parent deleted between the parent listing and its child fetch has no history left.
+ "response_actions": [{"status_code": 404, "action": "ignore"}],
+ },
+ },
+ ],
+ }
+
+ # The parent listing is re-read every run and the fan-out resume state does not fit
+ # InsightlyResumeConfig, so this endpoint restarts from the first opportunity.
+ resources = rest_api_resources(rest_config, team_id, job_id, None)
+ child = next(r for r in resources if r.name == endpoint)
+ return _source_response(endpoint, config, lambda: child)
+
+
def insightly_source(
pod: str,
api_key: str,
@@ -82,25 +168,21 @@ def insightly_source(
db_incremental_field_last_value: Optional[Any] = None,
) -> SourceResponse:
config = INSIGHTLY_ENDPOINTS[endpoint]
+ if config.fanout_parent is not None:
+ return _fanout_source(pod, api_key, endpoint, team_id, job_id)
+
+ # Only incremental endpoints expose `updated_after_utc`, and only when the job supplies a cursor.
+ use_incremental = bool(
+ config.supports_incremental and should_use_incremental_field and db_incremental_field_last_value
+ )
endpoint_config: Endpoint = {
- "path": config.path,
- # Offset pagination with Insightly's `top`/`skip`; a short (< top) page is the last one.
- "paginator": OffsetPaginator(
- limit=PAGE_SIZE,
- offset_param="skip",
- limit_param="top",
- total_path=None,
- ),
+ "path": config.incremental_path if use_incremental and config.incremental_path else config.path,
+ "paginator": _offset_paginator(),
# Insightly list endpoints return a bare JSON array. A non-list 200 body (a 2xx error
# envelope, an HTML gateway page) must fail loud instead of silently syncing 0 rows.
"data_selector_required": True,
}
-
- # Only incremental endpoints expose `updated_after_utc`, and only when the job supplies a cursor.
- use_incremental = bool(
- config.supports_incremental and should_use_incremental_field and db_incremental_field_last_value
- )
if use_incremental:
endpoint_config["incremental"] = {
"start_param": UPDATED_AFTER_PARAM,
@@ -108,16 +190,7 @@ def insightly_source(
}
rest_config: RESTAPIConfig = {
- "client": {
- "base_url": base_url(pod),
- "headers": {"Accept": "application/json"},
- # HTTP Basic auth with the API key as the username and a blank password. Using the
- # framework auth keeps the key out of raised error messages / logged URLs.
- "auth": {"type": "http_basic", "username": api_key, "password": ""},
- # Pin every request (including resume URLs) to api.<pod>.insightly.com — reinforces the
- # pod normalization guard so credentials can never be sent off-host.
- "allowed_hosts": [],
- },
+ "client": _client_config(pod, api_key),
"resources": [
{
"name": endpoint,
@@ -147,22 +220,7 @@ def insightly_source(
initial_paginator_state=initial_paginator_state,
)
- return SourceResponse(
- name=endpoint,
- items=lambda: resource,
- primary_keys=[config.primary_key],
- # Insightly paginates in record-id (creation) order, so rows for a given sync arrive roughly
- # oldest-first; DATE_UPDATED_UTC is not strictly monotonic across pages. We keep the same
- # `updated_after_utc` filter on every page (offset pagination reuses the query), so an
- # incremental sync never walks unbounded history — and if Insightly ever ignored the filter,
- # the sync degrades to full-refresh cost, never incorrect data (merge dedupes on the id).
- sort_mode="asc",
- partition_count=1,
- partition_size=1,
- partition_mode="datetime" if config.partition_key else None,
- partition_format="week" if config.partition_key else None,
- partition_keys=[config.partition_key] if config.partition_key else None,
- )
+ return _source_response(endpoint, config, lambda: resource)
def validate_credentials(pod: str, api_key: str, path: str = "/Contacts") -> Optional[int]:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/insightly/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/insightly/settings.py
index d3fde470d474..0746c7933846 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/insightly/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/insightly/settings.py
@@ -1,6 +1,8 @@
-from dataclasses import dataclass, field
+from dataclasses import field
from typing import Optional
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
# Insightly objects share a common audit-field schema: DATE_CREATED_UTC is stamped once at
@@ -21,11 +23,11 @@ def _updated_at_incremental_fields() -> list[IncrementalField]:
]
-@dataclass
+@frozen
class InsightlyEndpointConfig:
name: str
path: str
- primary_key: str
+ primary_key: str | tuple[str, ...]
# Only set for endpoints where Insightly exposes the server-side `updated_after_utc` list
# filter; those endpoints advertise DATE_UPDATED_UTC as the incremental cursor.
supports_incremental: bool = False
@@ -33,9 +35,29 @@ class InsightlyEndpointConfig:
# Pipelines) whose rows carry no creation timestamp.
partition_key: Optional[str] = DATE_CREATED
incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Set when the plain list endpoint takes no `updated_after_utc` and only its `/Search` variant
+ # filters server-side; incremental syncs page through this path instead.
+ incremental_path: Optional[str] = None
+ # Set for per-record sub-resources: `path` carries an `{id}` placeholder that is filled from
+ # `parent_id_field` on each row of the `fanout_parent` endpoint.
+ fanout_parent: Optional[str] = None
+ parent_id_field: Optional[str] = None
+
+ @property
+ def primary_keys(self) -> list[str]:
+ return [self.primary_key] if isinstance(self.primary_key, str) else list(self.primary_key)
+ @property
+ def probe_path(self) -> str:
+ """A path that can be requested as-is to check the key's access to this endpoint."""
+ if self.fanout_parent is not None:
+ return INSIGHTLY_ENDPOINTS[self.fanout_parent].path
+ return self.path
-def _incremental_endpoint(name: str, path: str, primary_key: str) -> InsightlyEndpointConfig:
+
+def _incremental_endpoint(
+ name: str, path: str, primary_key: str, incremental_path: Optional[str] = None
+) -> InsightlyEndpointConfig:
return InsightlyEndpointConfig(
name=name,
path=path,
@@ -43,6 +65,7 @@ def _incremental_endpoint(name: str, path: str, primary_key: str) -> InsightlyEn
supports_incremental=True,
partition_key=DATE_CREATED,
incremental_fields=_updated_at_incremental_fields(),
+ incremental_path=incremental_path,
)
@@ -64,6 +87,28 @@ INSIGHTLY_ENDPOINTS: dict[str, InsightlyEndpointConfig] = {
"Pipelines": InsightlyEndpointConfig(
name="Pipelines", path="/Pipelines", primary_key="PIPELINE_ID", partition_key=None
),
+ "PipelineStages": InsightlyEndpointConfig(
+ name="PipelineStages", path="/PipelineStages", primary_key="STAGE_ID", partition_key=None
+ ),
+ "LeadSources": InsightlyEndpointConfig(
+ name="LeadSources", path="/LeadSources", primary_key="LEAD_SOURCE_ID", partition_key=None
+ ),
+ "OpportunityLineItem": _incremental_endpoint(
+ "OpportunityLineItem",
+ "/OpportunityLineItem",
+ "OPPORTUNITY_ITEM_ID",
+ incremental_path="/OpportunityLineItem/Search",
+ ),
+ # One request per opportunity and no server-side filter, so full refresh only. History rows
+ # carry no id of their own; a transition is identified by its opportunity, time, and state.
+ "OpportunityStateHistory": InsightlyEndpointConfig(
+ name="OpportunityStateHistory",
+ path="/Opportunities/{id}/StateHistory",
+ primary_key=("OPPORTUNITY_ID", "DATE_CHANGED_UTC", "FOR_OPPORTUNITY_STATE"),
+ partition_key="DATE_CHANGED_UTC",
+ fanout_parent="Opportunities",
+ parent_id_field="OPPORTUNITY_ID",
+ ),
}
ENDPOINTS = tuple(INSIGHTLY_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/insightly/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/insightly/source.py
index 0d4c0bf82ed4..948ec5373194 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/insightly/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/insightly/source.py
@@ -93,6 +93,16 @@ The API key inherits your Insightly user's permissions, so make sure your user c
return CANONICAL_DESCRIPTIONS
+ def resume_covers_run(
+ self,
+ *,
+ incremental_or_append: bool,
+ schema_name: str | None = None,
+ ) -> bool:
+ # A fan-out endpoint saves no checkpoint, so each retry re-requests every parent's children.
+ endpoint = INSIGHTLY_ENDPOINTS.get(schema_name or "")
+ return endpoint is None or endpoint.fanout_parent is None
+
def get_non_retryable_errors(self) -> dict[str, str | None]:
return {
# An invalid or revoked key surfaces as an HTTPError when `fetch_page` calls
@@ -117,7 +127,7 @@ The API key inherits your Insightly user's permissions, so make sure your user c
supports_incremental=endpoint_config.supports_incremental,
supports_append=endpoint_config.supports_incremental,
incremental_fields=endpoint_config.incremental_fields,
- detected_primary_keys=[endpoint_config.primary_key],
+ detected_primary_keys=endpoint_config.primary_keys,
)
schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]
@@ -133,7 +143,7 @@ The API key inherits your Insightly user's permissions, so make sure your user c
schema_name: Optional[str] = None,
api_version: str | None = None,
) -> tuple[bool, str | None]:
- path = INSIGHTLY_ENDPOINTS[schema_name].path if schema_name in INSIGHTLY_ENDPOINTS else "/Contacts"
+ path = INSIGHTLY_ENDPOINTS[schema_name].probe_path if schema_name in INSIGHTLY_ENDPOINTS else "/Contacts"
try:
status = validate_insightly_credentials(config.pod, config.api_key, path)
except ValueError as e:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/insightly/tests/test_insightly.py b/products/warehouse_sources/backend/temporal/data_imports/sources/insightly/tests/test_insightly.py
index d60d0d007c19..d972703918e8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/insightly/tests/test_insightly.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/insightly/tests/test_insightly.py
@@ -219,6 +219,34 @@ class TestPagination:
)
assert "updated_after_utc" not in params[0]
+ @pytest.mark.parametrize(
+ "incremental, expected_path, expected_filter",
+ [
+ (True, "/OpportunityLineItem/Search", "2020-01-01T00:00:00Z"),
+ (False, "/OpportunityLineItem", None),
+ ],
+ )
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_search_path_carries_the_incremental_filter(
+ self, MockSession, incremental: bool, expected_path: str, expected_filter: str | None
+ ) -> None:
+ from datetime import UTC, datetime
+
+ session = MockSession.return_value
+ params = _wire(session, [_response([{"OPPORTUNITY_ITEM_ID": 1}])])
+
+ _rows(
+ _source(
+ _make_manager(),
+ endpoint="OpportunityLineItem",
+ should_use_incremental_field=incremental,
+ db_incremental_field_last_value=datetime(2020, 1, 1, tzinfo=UTC) if incremental else None,
+ )
+ )
+ # The plain list endpoint takes no `updated_after_utc`; only its /Search variant filters.
+ assert session.prepare_request.call_args.args[0].url.endswith(expected_path)
+ assert params[0].get("updated_after_utc") == expected_filter
+
@mock.patch(CLIENT_SESSION_PATCH)
def test_raises_on_non_retryable_error(self, MockSession) -> None:
session = MockSession.return_value
@@ -237,6 +265,34 @@ class TestPagination:
_rows(_source(_make_manager()))
+class TestOpportunityStateHistoryFanout:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_fetches_history_per_opportunity_and_skips_deleted_ones(self, MockSession) -> None:
+ session = MockSession.return_value
+ history = [{"OPPORTUNITY_ID": 1, "DATE_CHANGED_UTC": "2024-01-02 03:04:05", "FOR_OPPORTUNITY_STATE": "WON"}]
+ params = _wire(
+ session,
+ [
+ _response([{"OPPORTUNITY_ID": 1}, {"OPPORTUNITY_ID": 2}]),
+ _response(history),
+ _response([], status=404),
+ ],
+ )
+
+ manager = _make_manager()
+ rows = _rows(_source(manager, endpoint="OpportunityStateHistory"))
+
+ assert rows == history
+ urls = [c.args[0].url for c in session.prepare_request.call_args_list]
+ assert urls[0].endswith("/Opportunities")
+ assert params[0]["brief"] == "true"
+ assert urls[1].endswith("/Opportunities/1/StateHistory")
+ assert urls[2].endswith("/Opportunities/2/StateHistory")
+ # Child requests are single, unpaginated calls.
+ assert "top" not in params[1]
+ manager.save_state.assert_not_called()
+
+
class TestValidateCredentials:
@pytest.mark.parametrize("status_code", [200, 401, 403, 500])
@mock.patch(INSIGHTLY_SESSION_PATCH)
@@ -260,12 +316,18 @@ class TestValidateCredentials:
class TestInsightlySourceResponse:
@pytest.mark.parametrize(
- "endpoint, expected_pk, expected_partition_keys, expected_mode",
+ "endpoint, expected_pks, expected_partition_keys, expected_mode",
[
- ("Contacts", "CONTACT_ID", ["DATE_CREATED_UTC"], "datetime"),
- ("Opportunities", "OPPORTUNITY_ID", ["DATE_CREATED_UTC"], "datetime"),
- ("Users", "USER_ID", ["DATE_CREATED_UTC"], "datetime"),
- ("Pipelines", "PIPELINE_ID", None, None),
+ ("Contacts", ["CONTACT_ID"], ["DATE_CREATED_UTC"], "datetime"),
+ ("Opportunities", ["OPPORTUNITY_ID"], ["DATE_CREATED_UTC"], "datetime"),
+ ("Users", ["USER_ID"], ["DATE_CREATED_UTC"], "datetime"),
+ ("Pipelines", ["PIPELINE_ID"], None, None),
+ (
+ "OpportunityStateHistory",
+ ["OPPORTUNITY_ID", "DATE_CHANGED_UTC", "FOR_OPPORTUNITY_STATE"],
+ ["DATE_CHANGED_UTC"],
+ "datetime",
+ ),
],
)
@mock.patch(CLIENT_SESSION_PATCH)
@@ -273,13 +335,13 @@ class TestInsightlySourceResponse:
self,
MockSession,
endpoint: str,
- expected_pk: str,
+ expected_pks: list[str],
expected_partition_keys: list[str] | None,
expected_mode: str | None,
) -> None:
response = _source(_make_manager(), endpoint=endpoint)
assert response.name == endpoint
- assert response.primary_keys == [expected_pk]
+ assert response.primary_keys == expected_pks
assert response.partition_keys == expected_partition_keys
assert response.partition_mode == expected_mode
assert response.sort_mode == "asc"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/insightly/tests/test_insightly_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/insightly/tests/test_insightly_source.py
index 7fed2e7b3ddd..5664ca52a2ee 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/insightly/tests/test_insightly_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/insightly/tests/test_insightly_source.py
@@ -46,6 +46,17 @@ class TestInsightlySource:
non_retryable_errors = self.source.get_non_retryable_errors()
assert not any(key in other_error for key in non_retryable_errors)
+ @pytest.mark.parametrize(
+ "schema_name, expected",
+ [
+ ("Contacts", True),
+ ("OpportunityStateHistory", False),
+ (None, True),
+ ],
+ )
+ def test_resume_covers_only_checkpointed_endpoints(self, schema_name: str | None, expected: bool) -> None:
+ assert self.source.resume_covers_run(incremental_or_append=False, schema_name=schema_name) is expected
+
def test_get_schemas_lists_every_endpoint(self) -> None:
schemas = self.source.get_schemas(self.config, self.team_id)
assert {s.name for s in schemas} == set(ENDPOINTS)
@@ -98,6 +109,24 @@ class TestInsightlySource:
ok, _ = self.source.validate_credentials(self.config, self.team_id, schema_name)
assert ok is expected_ok
+ @pytest.mark.parametrize(
+ "schema_name, expected_path",
+ [
+ ("Leads", "/Leads"),
+ # The per-opportunity path has an `{id}` placeholder, so access is probed on its parent.
+ ("OpportunityStateHistory", "/Opportunities"),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.insightly.source.validate_insightly_credentials"
+ )
+ def test_validate_credentials_probes_a_requestable_path(
+ self, mock_validate: mock.MagicMock, schema_name: str, expected_path: str
+ ) -> None:
+ mock_validate.return_value = 200
+ self.source.validate_credentials(self.config, self.team_id, schema_name)
+ assert mock_validate.call_args.args[2] == expected_path
+
@mock.patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.insightly.source.validate_insightly_credentials"
)