Skip to content

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

feat(data-warehouse): implement insightly import source (#67803)

Tom Owersaf89ff952c0e
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 08c2e730e170..a7b82982ebcc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -175,6 +175,7 @@ the row lists both.
| hubspot | HTTP | requests | ✅ |
| hugging_face | HTTP | requests | ✅ |
| incident_io | HTTP | requests | ✅ |
+| insightly | HTTP | requests | ✅ |
| intercom | HTTP | requests + `rest_source.RESTClient` | ✅ |
| iterable | HTTP | requests | ✅ |
| jira | HTTP | requests | ✅ |
@@ -463,7 +464,6 @@ doesn't conflict with concurrent PRs.
- inflowinventory
- infor_nexus
- insightful
-- insightly
- instagram
- instantly
- instatus
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index cf473c2c1533..56dfb79aaada 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
@@ -1614,7 +1614,8 @@ class InsightfulSourceConfig(config.Config):
@config.config
class InsightlySourceConfig(config.Config):
- pass
+ pod: str
+ api_key: str
@config.config
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
new file mode 100644
index 000000000000..3d3d0525ddde
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/insightly/canonical_descriptions.py
@@ -0,0 +1,159 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+_DOCS_URL = "https://api.insightly.com/v3.1/Help"
+
+# Fields shared by every Insightly object. Merged into each endpoint's columns below.
+_COMMON_COLUMNS = {
+ "DATE_CREATED_UTC": "UTC timestamp when the record was created.",
+ "DATE_UPDATED_UTC": "UTC timestamp when the record was last modified (the incremental cursor).",
+ "OWNER_USER_ID": "User ID of the record owner.",
+ "CREATED_USER_ID": "User ID of the user who created the record.",
+ "VISIBLE_TO": "Sharing scope of the record (e.g. EVERYONE, OWNER, TEAM, INDIVIDUAL).",
+ "CUSTOMFIELDS": "List of custom field values defined for your Insightly account.",
+ "TAGS": "List of tags applied to the record.",
+}
+
+
+def _columns(**extra: str) -> dict[str, str]:
+ return {**_COMMON_COLUMNS, **extra}
+
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "Contacts": {
+ "description": "People tracked in Insightly, with their contact details and relationships.",
+ "docs_url": _DOCS_URL,
+ "columns": _columns(
+ CONTACT_ID="Unique identifier for the contact.",
+ FIRST_NAME="Contact's first name.",
+ LAST_NAME="Contact's last name.",
+ EMAIL_ADDRESS="Primary email address of the contact.",
+ ORGANISATION_ID="ID of the organisation the contact belongs to, if any.",
+ TITLE="Contact's job title.",
+ PHONE="Primary phone number of the contact.",
+ ),
+ },
+ "Organisations": {
+ "description": "Companies and organisations tracked in Insightly.",
+ "docs_url": _DOCS_URL,
+ "columns": _columns(
+ ORGANISATION_ID="Unique identifier for the organisation.",
+ ORGANISATION_NAME="Name of the organisation.",
+ PHONE="Primary phone number of the organisation.",
+ WEBSITE="Organisation's website URL.",
+ ),
+ },
+ "Opportunities": {
+ "description": "Sales opportunities (deals) tracked through your pipelines.",
+ "docs_url": _DOCS_URL,
+ "columns": _columns(
+ OPPORTUNITY_ID="Unique identifier for the opportunity.",
+ OPPORTUNITY_NAME="Name of the opportunity.",
+ OPPORTUNITY_STATE="Current state of the opportunity (e.g. OPEN, WON, LOST, ABANDONED).",
+ OPPORTUNITY_VALUE="Monetary value of the opportunity.",
+ PROBABILITY="Estimated probability (%) of winning the opportunity.",
+ BID_CURRENCY="Currency code for the opportunity value.",
+ PIPELINE_ID="ID of the pipeline the opportunity is in.",
+ STAGE_ID="ID of the current pipeline stage.",
+ FORECAST_CLOSE_DATE="Expected close date of the opportunity.",
+ ACTUAL_CLOSE_DATE="Date the opportunity was actually closed.",
+ ),
+ },
+ "Leads": {
+ "description": "Unqualified prospects that can be converted into contacts, organisations, and opportunities.",
+ "docs_url": _DOCS_URL,
+ "columns": _columns(
+ LEAD_ID="Unique identifier for the lead.",
+ FIRST_NAME="Lead's first name.",
+ LAST_NAME="Lead's last name.",
+ EMAIL="Lead's email address.",
+ ORGANISATION_NAME="Organisation the lead is associated with.",
+ LEAD_STATUS_ID="ID of the lead's status.",
+ LEAD_SOURCE_ID="ID of the lead's source.",
+ CONVERTED="Whether the lead has been converted.",
+ CONVERTED_DATE_UTC="UTC timestamp when the lead was converted.",
+ ),
+ },
+ "Projects": {
+ "description": "Projects used to manage post-sale work and deliverables.",
+ "docs_url": _DOCS_URL,
+ "columns": _columns(
+ PROJECT_ID="Unique identifier for the project.",
+ PROJECT_NAME="Name of the project.",
+ STATUS="Current status of the project (e.g. NOT STARTED, IN PROGRESS, COMPLETED).",
+ PIPELINE_ID="ID of the pipeline the project is in.",
+ STAGE_ID="ID of the current pipeline stage.",
+ COMPLETED_DATE_UTC="UTC timestamp when the project was completed.",
+ ),
+ },
+ "Tasks": {
+ "description": "To-do items assigned to users and linked to CRM records.",
+ "docs_url": _DOCS_URL,
+ "columns": _columns(
+ TASK_ID="Unique identifier for the task.",
+ TITLE="Title of the task.",
+ STATUS="Current status of the task (e.g. NOT STARTED, IN PROGRESS, COMPLETED).",
+ DUE_DATE="Due date of the task.",
+ COMPLETED="Whether the task is complete.",
+ COMPLETED_DATE_UTC="UTC timestamp when the task was completed.",
+ PRIORITY="Priority of the task.",
+ RESPONSIBLE_USER_ID="User ID of the person responsible for the task.",
+ ),
+ },
+ "Events": {
+ "description": "Calendar events and appointments.",
+ "docs_url": _DOCS_URL,
+ "columns": _columns(
+ EVENT_ID="Unique identifier for the event.",
+ TITLE="Title of the event.",
+ LOCATION="Location of the event.",
+ START_DATE_UTC="UTC start time of the event.",
+ END_DATE_UTC="UTC end time of the event.",
+ ALL_DAY="Whether the event lasts all day.",
+ ),
+ },
+ "Notes": {
+ "description": "Free-text notes attached to CRM records.",
+ "docs_url": _DOCS_URL,
+ "columns": _columns(
+ NOTE_ID="Unique identifier for the note.",
+ TITLE="Title of the note.",
+ BODY="Body text of the note.",
+ ),
+ },
+ "Emails": {
+ "description": "Emails logged against CRM records.",
+ "docs_url": _DOCS_URL,
+ "columns": _columns(
+ EMAIL_ID="Unique identifier for the email.",
+ SUBJECT="Subject line of the email.",
+ EMAIL_FROM="Sender of the email.",
+ EMAIL_DATE_UTC="UTC timestamp when the email was sent.",
+ ),
+ },
+ "Users": {
+ "description": "Insightly users in your account.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "USER_ID": "Unique identifier for the user.",
+ "FIRST_NAME": "User's first name.",
+ "LAST_NAME": "User's last name.",
+ "EMAIL_ADDRESS": "User's email address.",
+ "ADMINISTRATOR": "Whether the user is an account administrator.",
+ "ACTIVE": "Whether the user account is active.",
+ "DATE_CREATED_UTC": "UTC timestamp when the user was created.",
+ "DATE_UPDATED_UTC": "UTC timestamp when the user was last modified.",
+ },
+ },
+ "Pipelines": {
+ "description": "Sales/project pipelines used to organise opportunities and projects into stages.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "PIPELINE_ID": "Unique identifier for the pipeline.",
+ "PIPELINE_NAME": "Name of the pipeline.",
+ "FOR_OPPORTUNITIES": "Whether the pipeline applies to opportunities.",
+ "FOR_PROJECTS": "Whether the pipeline applies to projects.",
+ },
+ },
+}
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
new file mode 100644
index 000000000000..04abddcfb87b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/insightly/insightly.py
@@ -0,0 +1,216 @@
+import re
+import base64
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import urlencode
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.insightly.settings import (
+ INSIGHTLY_ENDPOINTS,
+ InsightlyEndpointConfig,
+)
+
+API_VERSION = "v3.1"
+# Insightly caps list pages at 500 items (default is 100).
+PAGE_SIZE = 500
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRIES = 5
+
+# A pod/instance is a short region token such as `na1`, `eu1`, `aps1`.
+_POD_RE = re.compile(r"^[a-z0-9]+$")
+_POD_FROM_URL_RE = re.compile(r"api\.([a-z0-9]+)\.insightly\.com")
+
+
+class InsightlyRetryableError(Exception):
+ pass
+
+
+class InsightlyResumeConfig:
+ # Offset (`skip`) of the next page to fetch. The `updated_after_utc` filter is rebuilt from the
+ # job's incremental value at resume time, so it never needs to be persisted here.
+ skip: int
+
+
+def normalize_pod(raw: str) -> str:
+ """Reduce whatever the user pasted to the bare Insightly pod token.
+
+ Accepts ``na1`` or a full API URL (``https://api.na1.insightly.com/v3.1``). Raising on anything
+ that isn't a plain pod token also pins outbound traffic to ``api.<pod>.insightly.com`` (no SSRF
+ to arbitrary hosts).
+ """
+ pod = raw.strip().lower()
+ match = _POD_FROM_URL_RE.search(pod)
+ if match:
+ pod = match.group(1)
+ if not _POD_RE.match(pod):
+ raise ValueError(f"Invalid Insightly pod/instance: {raw!r}")
+ return pod
+
+
+def base_url(pod: str) -> str:
+ return f"https://api.{normalize_pod(pod)}.insightly.com/{API_VERSION}"
+
+
+def _auth_headers(api_key: str) -> dict[str, str]:
+ # Insightly uses HTTP Basic auth with the API key as the username and a blank password.
+ token = base64.b64encode(f"{api_key}:".encode()).decode()
+ return {"Authorization": f"Basic {token}", "Accept": "application/json"}
+
+
+def _format_updated_after(value: Any) -> str:
+ """Format the incremental cursor as ISO 8601 with a trailing Z, which `updated_after_utc` expects
+ (e.g. ``2018-04-09T16:58:14Z``)."""
+ if isinstance(value, datetime):
+ dt = value.astimezone(UTC) if value.tzinfo is not None else value.replace(tzinfo=UTC)
+ elif isinstance(value, date):
+ dt = datetime.combine(value, datetime.min.time(), tzinfo=UTC)
+ else:
+ # Already a string cursor (e.g. the raw DATE_UPDATED_UTC value round-tripped from the DB).
+ return str(value)
+ return dt.strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def _build_params(
+ config: InsightlyEndpointConfig,
+ skip: int,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> dict[str, Any]:
+ params: dict[str, Any] = {"top": PAGE_SIZE, "skip": skip}
+ if config.supports_incremental and should_use_incremental_field and db_incremental_field_last_value:
+ params["updated_after_utc"] = _format_updated_after(db_incremental_field_last_value)
+ return params
+
+
+def _build_url(pod: str, path: str, params: dict[str, Any]) -> str:
+ return f"{base_url(pod)}{path}?{urlencode(params)}"
+
+
+def validate_credentials(pod: str, api_key: str, path: str = "/Contacts") -> Optional[int]:
+ """Return the status code of a cheap authenticated probe, or ``None`` on transport error.
+
+ Requests a single row from ``path`` so a genuine key returns 200, a bad key 401, and a key
+ without scope for that resource 403. Built outside the ``try`` so an invalid-pod ``ValueError``
+ propagates rather than being flattened to ``None`` by the transport-error handler.
+ """
+ url = _build_url(pod, path, {"top": 1})
+ try:
+ session = make_tracked_session(headers=_auth_headers(api_key), redact_values=(api_key,))
+ response = session.get(url, timeout=10)
+ return response.status_code
+ except Exception:
+ return None
+
+
+def get_rows(
+ pod: str,
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[InsightlyResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = INSIGHTLY_ENDPOINTS[endpoint]
+ # `redact_values` masks the key inside the base64 Authorization header in logged URLs / captured
+ # samples, on top of the name-based denylist that already scrubs the header itself.
+ session = make_tracked_session(headers=_auth_headers(api_key), redact_values=(api_key,))
+
+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume_config is not None:
+ skip = resume_config.skip
+ logger.debug(f"Insightly: resuming {endpoint} from skip={skip}")
+ else:
+ skip = 0
+
+ @retry(
+ retry=retry_if_exception_type((InsightlyRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRIES),
+ wait=wait_exponential_jitter(initial=1, max=60),
+ reraise=True,
+ )
+ def fetch_page(page_url: str) -> Any:
+ response = session.get(page_url, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ # Insightly rate-limits at 10 req/s plus daily caps, returning 429; retry those and
+ # transient 5xx with exponential backoff.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise InsightlyRetryableError(
+ f"Insightly API error (retryable): status={response.status_code}, url={page_url}"
+ )
+
+ if not response.ok:
+ logger.error(f"Insightly API error: status={response.status_code}, body={response.text}, url={page_url}")
+ response.raise_for_status()
+
+ return response.json()
+
+ while True:
+ url = _build_url(
+ pod, config.path, _build_params(config, skip, should_use_incremental_field, db_incremental_field_last_value)
+ )
+ data = fetch_page(url)
+ # Insightly list endpoints return a bare JSON array. Anything else (a 2xx error envelope,
+ # an HTML gateway page) would otherwise make `items` empty and silently end the sync with
+ # no rows and no error — so fail loudly instead of masking it as an empty table.
+ if not isinstance(data, list):
+ raise ValueError(f"Insightly API returned an unexpected {type(data).__name__} response for {url}")
+ items = data
+
+ if items:
+ yield items
+
+ # A short page (fewer than a full `top`) is the last page — offset pagination is done.
+ if len(items) < PAGE_SIZE:
+ break
+
+ skip += PAGE_SIZE
+ # Save the next offset only after the current page has been yielded, so a crash resumes at
+ # this page rather than past it. Merge dedupes any rows re-yielded on resume by primary key.
+ resumable_source_manager.save_state(InsightlyResumeConfig(skip=skip))
+
+
+def insightly_source(
+ pod: str,
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[InsightlyResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = INSIGHTLY_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ pod=pod,
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ 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,
+ )
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
new file mode 100644
index 000000000000..d3fde470d474
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/insightly/settings.py
@@ -0,0 +1,73 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# Insightly objects share a common audit-field schema: DATE_CREATED_UTC is stamped once at
+# creation (stable — safe to partition on) and DATE_UPDATED_UTC advances on every edit (the
+# incremental cursor, mapped to the `updated_after_utc` list filter).
+DATE_CREATED = "DATE_CREATED_UTC"
+DATE_UPDATED = "DATE_UPDATED_UTC"
+
+
+def _updated_at_incremental_fields() -> list[IncrementalField]:
+ return [
+ {
+ "label": DATE_UPDATED,
+ "type": IncrementalFieldType.DateTime,
+ "field": DATE_UPDATED,
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ]
+
+
+@dataclass
+class InsightlyEndpointConfig:
+ name: str
+ path: str
+ primary_key: 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
+ # Stable creation timestamp used for datetime partitioning. `None` for endpoints (e.g.
+ # Pipelines) whose rows carry no creation timestamp.
+ partition_key: Optional[str] = DATE_CREATED
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+
+
+def _incremental_endpoint(name: str, path: str, primary_key: str) -> InsightlyEndpointConfig:
+ return InsightlyEndpointConfig(
+ name=name,
+ path=path,
+ primary_key=primary_key,
+ supports_incremental=True,
+ partition_key=DATE_CREATED,
+ incremental_fields=_updated_at_incremental_fields(),
+ )
+
+
+INSIGHTLY_ENDPOINTS: dict[str, InsightlyEndpointConfig] = {
+ "Contacts": _incremental_endpoint("Contacts", "/Contacts", "CONTACT_ID"),
+ "Organisations": _incremental_endpoint("Organisations", "/Organisations", "ORGANISATION_ID"),
+ "Opportunities": _incremental_endpoint("Opportunities", "/Opportunities", "OPPORTUNITY_ID"),
+ "Leads": _incremental_endpoint("Leads", "/Leads", "LEAD_ID"),
+ "Projects": _incremental_endpoint("Projects", "/Projects", "PROJECT_ID"),
+ "Tasks": _incremental_endpoint("Tasks", "/Tasks", "TASK_ID"),
+ "Events": _incremental_endpoint("Events", "/Events", "EVENT_ID"),
+ "Notes": _incremental_endpoint("Notes", "/Notes", "NOTE_ID"),
+ "Emails": _incremental_endpoint("Emails", "/Emails", "EMAIL_ID"),
+ # Users list is a small, admin-scoped metadata table with no `updated_after_utc` filter, so
+ # it's full refresh only. It still carries DATE_CREATED_UTC for partitioning.
+ "Users": InsightlyEndpointConfig(name="Users", path="/Users", primary_key="USER_ID"),
+ # Pipelines / stages are configuration objects without audit timestamps: full refresh, no
+ # partitioning.
+ "Pipelines": InsightlyEndpointConfig(
+ name="Pipelines", path="/Pipelines", primary_key="PIPELINE_ID", partition_key=None
+ ),
+}
+
+ENDPOINTS = tuple(INSIGHTLY_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in INSIGHTLY_ENDPOINTS.items()
+}
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 b8c5ee7ef878..2c14f71021b9 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
@@ -1,30 +1,165 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import InsightlySourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.insightly.insightly import (
+ InsightlyResumeConfig,
+ insightly_source,
+ normalize_pod,
+ validate_credentials as validate_insightly_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.insightly.settings import (
+ ENDPOINTS,
+ INSIGHTLY_ENDPOINTS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class InsightlySource(SimpleSource[InsightlySourceConfig]):
+class InsightlySource(ResumableSource[InsightlySourceConfig, InsightlyResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.INSIGHTLY
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # The stored API key is sent to `api.{pod}.insightly.com`; retargeting the pod must
+ # re-require the key so it can't be exfiltrated to another instance.
+ return ["pod"]
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.INSIGHTLY,
category=DataWarehouseSourceCategory.CRM,
label="Insightly",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Insightly API key to sync your Insightly CRM data into the PostHog Data warehouse.
+
+Find your **API key** and your **API URL** in Insightly under **User Settings** (top-right profile menu). The API URL looks like `https://api.na1.insightly.com/v3.1` — the **pod** is the region token in the middle (`na1`, `eu1`, ...). Enter just that token, or paste the full API URL.
+
+The API key inherits your Insightly user's permissions, so make sure your user can access the data you want to sync.""",
iconPath="/static/services/insightly.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/insightly",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="pod",
+ label="Pod (instance)",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="na1",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.insightly.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # An invalid or revoked key surfaces as an HTTPError when `fetch_page` calls
+ # `raise_for_status()`. Retrying can't fix a credential problem, so stop the sync.
+ "401 Client Error": "Your Insightly API key is invalid or has been revoked. Generate a new key in Insightly User Settings, then reconnect.",
+ "403 Client Error": "Your Insightly user lacks permission for this data. Check your user's access in Insightly, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: InsightlySourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ def _build_schema(endpoint: str) -> SourceSchema:
+ endpoint_config = INSIGHTLY_ENDPOINTS[endpoint]
+ return SourceSchema(
+ name=endpoint,
+ 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],
+ )
+
+ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: InsightlySourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ path = INSIGHTLY_ENDPOINTS[schema_name].path if schema_name in INSIGHTLY_ENDPOINTS else "/Contacts"
+ try:
+ status = validate_insightly_credentials(config.pod, config.api_key, path)
+ except ValueError as e:
+ return False, str(e)
+
+ if status is not None and 200 <= status < 300:
+ return True, None
+ # A valid key may lack scope for some endpoints; accept that at source-create
+ # (schema_name is None) and only reject when validating a specific schema.
+ if status == 403 and schema_name is None:
+ return True, None
+ if status in (401, 403):
+ return False, "Invalid Insightly API key or insufficient permissions"
+ return False, "Could not validate Insightly credentials"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[InsightlyResumeConfig]:
+ return ResumableSourceManager[InsightlyResumeConfig](inputs, InsightlyResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: InsightlySourceConfig,
+ resumable_source_manager: ResumableSourceManager[InsightlyResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return insightly_source(
+ pod=normalize_pod(config.pod),
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
)
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
new file mode 100644
index 000000000000..dc23f051cb24
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/insightly/tests/test_insightly.py
@@ -0,0 +1,275 @@
+from typing import Any
+
+import pytest
+from unittest import mock
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.insightly.insightly import (
+ PAGE_SIZE,
+ InsightlyResumeConfig,
+ _build_params,
+ _build_url,
+ _format_updated_after,
+ base_url,
+ get_rows,
+ insightly_source,
+ normalize_pod,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.insightly.settings import INSIGHTLY_ENDPOINTS
+
+
+class TestNormalizePod:
+ @pytest.mark.parametrize(
+ "raw, expected",
+ [
+ ("na1", "na1"),
+ ("NA1", "na1"),
+ (" eu1 ", "eu1"),
+ ("https://api.na1.insightly.com/v3.1", "na1"),
+ ("https://api.aps1.insightly.com/v3.1/", "aps1"),
+ ("api.eu2.insightly.com", "eu2"),
+ ],
+ )
+ def test_normalizes_valid_pods(self, raw: str, expected: str) -> None:
+ assert normalize_pod(raw) == expected
+
+ @pytest.mark.parametrize(
+ "raw",
+ [
+ "",
+ "na 1",
+ "evil.com",
+ "na1.evil.com",
+ "http://169.254.169.254",
+ "na_1",
+ ],
+ )
+ def test_rejects_invalid_pods(self, raw: str) -> None:
+ with pytest.raises(ValueError):
+ normalize_pod(raw)
+
+ def test_base_url_is_pinned_to_insightly(self) -> None:
+ assert base_url("na1") == "https://api.na1.insightly.com/v3.1"
+ assert base_url("https://api.EU1.insightly.com/v3.1") == "https://api.eu1.insightly.com/v3.1"
+
+
+class TestFormatUpdatedAfter:
+ def test_formats_datetime_with_trailing_z(self) -> None:
+ from datetime import UTC, datetime
+
+ assert _format_updated_after(datetime(2018, 4, 9, 16, 58, 14, tzinfo=UTC)) == "2018-04-09T16:58:14Z"
+
+ def test_naive_datetime_treated_as_utc(self) -> None:
+ from datetime import datetime
+
+ assert _format_updated_after(datetime(2020, 1, 2, 3, 4, 5)) == "2020-01-02T03:04:05Z"
+
+ def test_date_formats_at_midnight(self) -> None:
+ from datetime import date
+
+ assert _format_updated_after(date(2021, 6, 7)) == "2021-06-07T00:00:00Z"
+
+ def test_string_passes_through(self) -> None:
+ assert _format_updated_after("2022-03-04T05:06:07Z") == "2022-03-04T05:06:07Z"
+
+
+class TestBuildParams:
+ def test_adds_updated_after_only_for_incremental_endpoint_with_value(self) -> None:
+ from datetime import UTC, datetime
+
+ params = _build_params(
+ INSIGHTLY_ENDPOINTS["Contacts"],
+ skip=0,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2020, 1, 1, tzinfo=UTC),
+ )
+ assert params == {"top": PAGE_SIZE, "skip": 0, "updated_after_utc": "2020-01-01T00:00:00Z"}
+
+ def test_no_updated_after_without_value(self) -> None:
+ params = _build_params(
+ INSIGHTLY_ENDPOINTS["Contacts"],
+ skip=500,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=None,
+ )
+ assert params == {"top": PAGE_SIZE, "skip": 500}
+
+ def test_full_refresh_endpoint_never_filters(self) -> None:
+ from datetime import UTC, datetime
+
+ # Users is full-refresh only; even with an incremental value it must not send updated_after_utc.
+ params = _build_params(
+ INSIGHTLY_ENDPOINTS["Users"],
+ skip=0,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2020, 1, 1, tzinfo=UTC),
+ )
+ assert params == {"top": PAGE_SIZE, "skip": 0}
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize("status_code", [200, 401, 403, 500])
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.insightly.insightly.make_tracked_session"
+ )
+ def test_returns_status_code(self, mock_session: mock.MagicMock, status_code: int) -> None:
+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=status_code)
+ assert validate_credentials("na1", "key", "/Contacts") == status_code
+ called_url = mock_session.return_value.get.call_args.args[0]
+ assert called_url == "https://api.na1.insightly.com/v3.1/Contacts?top=1"
+ # The key is masked in logged URLs and captured samples.
+ assert mock_session.call_args.kwargs["redact_values"] == ("key",)
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.insightly.insightly.make_tracked_session"
+ )
+ def test_returns_none_on_transport_error(self, mock_session: mock.MagicMock) -> None:
+ mock_session.return_value.get.side_effect = Exception("boom")
+ assert validate_credentials("na1", "key") is None
+
+ def test_propagates_invalid_pod(self) -> None:
+ with pytest.raises(ValueError):
+ validate_credentials("evil.com", "key")
+
+
+class TestGetRows:
+ def _manager(self, resume_state: InsightlyResumeConfig | None = None) -> mock.MagicMock:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = resume_state is not None
+ manager.load_state.return_value = resume_state
+ return manager
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.insightly.insightly.make_tracked_session"
+ )
+ def test_paginates_offset_and_saves_state_after_yield(self, mock_session: mock.MagicMock) -> None:
+ # A full page forces a second request; the short second page ends pagination.
+ full_page = mock.MagicMock(status_code=200, ok=True)
+ full_page.json.return_value = [{"CONTACT_ID": i} for i in range(PAGE_SIZE)]
+ last_page = mock.MagicMock(status_code=200, ok=True)
+ last_page.json.return_value = [{"CONTACT_ID": 9999}]
+ mock_session.return_value.get.side_effect = [full_page, last_page]
+
+ manager = self._manager()
+ batches = list(get_rows("na1", "key", "Contacts", mock.MagicMock(), manager))
+
+ assert len(batches) == 2
+ assert batches[1] == [{"CONTACT_ID": 9999}]
+ # Two page fetches at skip=0 then skip=PAGE_SIZE.
+ urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]
+ assert urls[0].endswith(f"top={PAGE_SIZE}&skip=0")
+ assert urls[1].endswith(f"top={PAGE_SIZE}&skip={PAGE_SIZE}")
+ # State saved once, after the first (full) page, pointing at the next offset.
+ manager.save_state.assert_called_once_with(InsightlyResumeConfig(skip=PAGE_SIZE))
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.insightly.insightly.make_tracked_session"
+ )
+ def test_single_short_page_does_not_save_state(self, mock_session: mock.MagicMock) -> None:
+ page = mock.MagicMock(status_code=200, ok=True)
+ page.json.return_value = [{"CONTACT_ID": 1}, {"CONTACT_ID": 2}]
+ mock_session.return_value.get.return_value = page
+
+ manager = self._manager()
+ batches = list(get_rows("na1", "key", "Contacts", mock.MagicMock(), manager))
+
+ assert batches == [[{"CONTACT_ID": 1}, {"CONTACT_ID": 2}]]
+ manager.save_state.assert_not_called()
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.insightly.insightly.make_tracked_session"
+ )
+ def test_resumes_from_saved_offset(self, mock_session: mock.MagicMock) -> None:
+ page = mock.MagicMock(status_code=200, ok=True)
+ page.json.return_value = [{"CONTACT_ID": 7}]
+ mock_session.return_value.get.return_value = page
+
+ manager = self._manager(InsightlyResumeConfig(skip=1000))
+ batches = list(get_rows("na1", "key", "Contacts", mock.MagicMock(), manager))
+
+ assert batches == [[{"CONTACT_ID": 7}]]
+ assert mock_session.return_value.get.call_args.args[0].endswith(f"top={PAGE_SIZE}&skip=1000")
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.insightly.insightly.make_tracked_session"
+ )
+ def test_incremental_filter_applied_on_every_page(self, mock_session: mock.MagicMock) -> None:
+ from datetime import UTC, datetime
+
+ full_page = mock.MagicMock(status_code=200, ok=True)
+ full_page.json.return_value = [{"CONTACT_ID": i} for i in range(PAGE_SIZE)]
+ last_page = mock.MagicMock(status_code=200, ok=True)
+ last_page.json.return_value = []
+ mock_session.return_value.get.side_effect = [full_page, last_page]
+
+ list(
+ get_rows(
+ "na1",
+ "key",
+ "Contacts",
+ mock.MagicMock(),
+ self._manager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2020, 1, 1, tzinfo=UTC),
+ )
+ )
+ urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]
+ # The `updated_after_utc` filter is present on both the first and the second page.
+ assert all("updated_after_utc=2020-01-01T00%3A00%3A00Z" in url for url in urls)
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.insightly.insightly.make_tracked_session"
+ )
+ def test_raises_on_non_retryable_error(self, mock_session: mock.MagicMock) -> None:
+ page = mock.MagicMock(status_code=401, ok=False, text="unauthorized")
+ page.raise_for_status.side_effect = Exception("401 Client Error")
+ mock_session.return_value.get.return_value = page
+
+ with pytest.raises(Exception, match="401 Client Error"):
+ list(get_rows("na1", "key", "Contacts", mock.MagicMock(), self._manager()))
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.insightly.insightly.make_tracked_session"
+ )
+ def test_raises_on_non_list_response(self, mock_session: mock.MagicMock) -> None:
+ # A 2xx with an unexpected (non-array) body must fail loudly, not sync zero rows silently.
+ page = mock.MagicMock(status_code=200, ok=True)
+ page.json.return_value = {"error": "something went wrong"}
+ mock_session.return_value.get.return_value = page
+
+ with pytest.raises(ValueError, match="unexpected"):
+ list(get_rows("na1", "key", "Contacts", mock.MagicMock(), self._manager()))
+
+
+class TestInsightlySourceResponse:
+ @pytest.mark.parametrize(
+ "endpoint, expected_pk, 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),
+ ],
+ )
+ def test_source_response_shape(
+ self,
+ endpoint: str,
+ expected_pk: str,
+ expected_partition_keys: list[str] | None,
+ expected_mode: str | None,
+ ) -> None:
+ response = insightly_source("na1", "key", endpoint, mock.MagicMock(), mock.MagicMock())
+ assert response.name == endpoint
+ assert response.primary_keys == [expected_pk]
+ assert response.partition_keys == expected_partition_keys
+ assert response.partition_mode == expected_mode
+ assert response.sort_mode == "asc"
+
+
+class TestBuildUrl:
+ def test_build_url_encodes_params(self) -> None:
+ params: dict[str, Any] = {"top": 500, "skip": 0, "updated_after_utc": "2020-01-01T00:00:00Z"}
+ url = _build_url("na1", "/Contacts", params)
+ assert url == (
+ "https://api.na1.insightly.com/v3.1/Contacts?top=500&skip=0&updated_after_utc=2020-01-01T00%3A00%3A00Z"
+ )
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
new file mode 100644
index 000000000000..c88446b718b2
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/insightly/tests/test_insightly_source.py
@@ -0,0 +1,169 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import InsightlySourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.insightly.insightly import InsightlyResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.insightly.settings import (
+ ENDPOINTS,
+ INSIGHTLY_ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.insightly.source import InsightlySource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+# Derived from settings so a new endpoint is automatically covered by the parametrized tests below.
+INCREMENTAL_ENDPOINTS = {name for name, cfg in INSIGHTLY_ENDPOINTS.items() if cfg.supports_incremental}
+FULL_REFRESH_ENDPOINTS = {name for name, cfg in INSIGHTLY_ENDPOINTS.items() if not cfg.supports_incremental}
+
+
+class TestInsightlySource:
+ def setup_method(self) -> None:
+ self.source = InsightlySource()
+ self.team_id = 123
+ self.config = InsightlySourceConfig(pod="na1", api_key="key")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.INSIGHTLY
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+ assert config.name.value == "Insightly"
+ assert config.label == "Insightly"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is None
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/insightly"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["pod", "api_key"]
+
+ def test_api_key_field_is_secret_password(self) -> None:
+ config = self.source.get_source_config
+ key_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")
+ assert key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert key_field.secret is True
+ assert key_field.required is True
+
+ def test_pod_is_connection_host_field(self) -> None:
+ assert self.source.connection_host_fields == ["pod"]
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.na1.insightly.com/v3.1/Contacts?top=500&skip=0",
+ "403 Client Error: Forbidden for url: https://api.na1.insightly.com/v3.1/Leads?top=500&skip=0",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ @pytest.mark.parametrize(
+ "other_error",
+ [
+ "429 Client Error: Too Many Requests for url: https://api.na1.insightly.com/v3.1/Contacts",
+ "500 Server Error for url: https://api.na1.insightly.com/v3.1/Notes",
+ ],
+ )
+ def test_transient_errors_are_not_marked_non_retryable(self, other_error: str) -> None:
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(key in other_error for key in non_retryable_errors)
+
+ 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)
+
+ @pytest.mark.parametrize("endpoint", sorted(INCREMENTAL_ENDPOINTS))
+ def test_incremental_endpoints_advertise_updated_at_cursor(self, endpoint: str) -> None:
+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id, names=[endpoint]))
+ assert schema.supports_incremental is True
+ assert [f["field"] for f in schema.incremental_fields] == ["DATE_UPDATED_UTC"]
+
+ @pytest.mark.parametrize("endpoint", sorted(FULL_REFRESH_ENDPOINTS))
+ def test_full_refresh_endpoints_have_no_incremental(self, endpoint: str) -> None:
+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id, names=[endpoint]))
+ assert schema.supports_incremental is False
+ assert schema.incremental_fields == []
+
+ def test_get_schemas_names_filter(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["Contacts"])
+ assert [s.name for s in schemas] == ["Contacts"]
+
+ def test_lists_tables_without_credentials(self) -> None:
+ # Static endpoint catalog with no I/O — safe for public docs.
+ assert self.source.lists_tables_without_credentials is True
+ tables = self.source.get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+
+ @pytest.mark.parametrize(
+ "status, schema_name, expected_ok",
+ [
+ (200, None, True),
+ (200, "Contacts", True),
+ (403, None, True), # missing scope tolerated at source-create
+ (403, "Leads", False), # but rejected for a specific schema
+ (401, None, False),
+ (500, None, False),
+ (None, None, False),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.insightly.source.validate_insightly_credentials"
+ )
+ def test_validate_credentials(
+ self,
+ mock_validate: mock.MagicMock,
+ status: int | None,
+ schema_name: str | None,
+ expected_ok: bool,
+ ) -> None:
+ mock_validate.return_value = status
+ ok, _ = self.source.validate_credentials(self.config, self.team_id, schema_name)
+ assert ok is expected_ok
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.insightly.source.validate_insightly_credentials"
+ )
+ def test_validate_credentials_rejects_invalid_pod(self, mock_validate: mock.MagicMock) -> None:
+ mock_validate.side_effect = ValueError("Invalid Insightly pod/instance: 'evil.com'")
+ ok, message = self.source.validate_credentials(
+ InsightlySourceConfig(pod="evil.com", api_key="key"), self.team_id
+ )
+ assert ok is False
+ assert "Invalid Insightly pod" in (message or "")
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ inputs = mock.MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is InsightlyResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.insightly.source.insightly_source")
+ def test_source_for_pipeline_passes_normalized_pod_and_cursor(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "Contacts"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2020-01-01T00:00:00Z"
+ manager = mock.MagicMock()
+
+ # A full API URL in the pod field is normalized to the bare pod token.
+ self.source.source_for_pipeline(
+ InsightlySourceConfig(pod="https://api.eu1.insightly.com/v3.1", api_key="key"), manager, inputs
+ )
+
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["pod"] == "eu1"
+ assert kwargs["endpoint"] == "Contacts"
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2020-01-01T00:00:00Z"
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.insightly.source.insightly_source")
+ def test_source_for_pipeline_omits_cursor_when_not_incremental(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "Contacts"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2020-01-01T00:00:00Z"
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None