: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement justcall import source (#67824)
Tom Owers51859b864114
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 0e18475a1f9e..5ee28c2640aa 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -187,6 +187,7 @@ the row lists both.| iterable | HTTP | requests | ✅ || jira | HTTP | requests | ✅ || jotform | HTTP | requests | ✅ |+| justcall | HTTP | requests | ✅ || klaviyo | HTTP | requests | ✅ || lago | HTTP | requests | ✅ || launchdarkly | HTTP | requests | ✅ |@@ -490,7 +491,6 @@ doesn't conflict with concurrent PRs.- jobber- jobnimbus- judgeme_reviews-- justcall- justsift- k6_cloud- kafkadiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex d4763ee614f2..fe25c89dd5f7 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@@ -1709,7 +1709,8 @@ class JudgeMeReviewsSourceConfig(config.Config):@config.configclass JustCallSourceConfig(config.Config):- pass+ api_key: str+ api_secret: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/justcall/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/justcall/canonical_descriptions.pynew file mode 100644index 000000000000..77c974ade2f4--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/justcall/canonical_descriptions.py@@ -0,0 +1,133 @@+"""Canonical, documentation-sourced descriptions for JustCall endpoints and columns.++Sourced from the official JustCall v2.1 API reference (https://developer.justcall.io/reference).+Keyed by the endpoint names in `settings.py` `JUSTCALL_ENDPOINTS`, which match the+`ExternalDataSchema.name` of a synced JustCall table. Columns absent here fall back to LLM enrichment.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "calls": {+ "description": "A phone call handled through JustCall, inbound or outbound, with its participants, timing, and outcome.",+ "docs_url": "https://developer.justcall.io/docs/justcall-call-object",+ "columns": {+ "id": "Unique identifier for the call, generated by JustCall.",+ "call_sid": "Telephony provider identifier for the call.",+ "contact_number": "Phone number of the external party.",+ "contact_name": "Name of the external party, if known.",+ "contact_email": "Email of the external party, if known.",+ "justcall_number": "The JustCall number the call came through.",+ "justcall_line_name": "Friendly name of the JustCall line.",+ "agent_id": "Identifier of the JustCall agent who handled the call.",+ "agent_name": "Name of the agent who handled the call.",+ "agent_email": "Email of the agent who handled the call.",+ "call_date": "Date of the call in UTC.",+ "call_time": "Time of the call in UTC.",+ "call_user_date": "Date of the call in the account's timezone.",+ "call_user_time": "Time of the call in the account's timezone.",+ "cost_incurred": "Cost of the call.",+ "call_info": "Nested object with direction, type, disposition, and status of the call.",+ "disposition": "Disposition code recorded for the call.",+ "notes": "Free-form notes attached to the call.",+ "rating": "Rating given to the call.",+ "recording": "URL of the call recording, if available.",+ "call_traits": "Traits describing how the call was routed (e.g. queue, transfer, IVR).",+ "call_duration": "Nested object describing the duration of the call.",+ "ivr_info": "Information about IVR navigation during the call.",+ "justcall_ai": "JustCall AI data associated with the call, when enabled.",+ "tags": "Tags applied to the call.",+ },+ },+ "texts": {+ "description": "An SMS or messaging conversation entry sent or received through JustCall.",+ "docs_url": "https://developer.justcall.io/docs/justcall-sms-object",+ "columns": {+ "id": "Unique identifier for the SMS, generated by JustCall.",+ "contact_number": "Phone number of the external party.",+ "contact_name": "Name of the external party, if known.",+ "contact_email": "Email of the external party, if known.",+ "justcall_number": "The JustCall number the message was sent from or to.",+ "justcall_line_name": "Friendly name of the JustCall line.",+ "agent_id": "Identifier of the JustCall agent associated with the message.",+ "agent_name": "Name of the agent associated with the message.",+ "agent_email": "Email of the agent associated with the message.",+ "sms_date": "Date of the SMS in UTC.",+ "sms_time": "Time of the SMS in UTC.",+ "sms_user_date": "Date of the SMS in the account's timezone.",+ "sms_user_time": "Time of the SMS in the account's timezone.",+ "direction": "Direction of the message: incoming or outgoing.",+ "cost_incurred": "Cost of the message.",+ "sms_info": "Nested object with the message body and related metadata.",+ "delivery_status": "Delivery status of the message.",+ "is_deleted": "Whether the message has been deleted.",+ "medium": "Messaging medium (e.g. SMS, MMS, WhatsApp).",+ },+ },+ "sales_dialer_calls": {+ "description": "A call placed through the JustCall Sales Dialer as part of an outbound campaign.",+ "docs_url": "https://developer.justcall.io/docs/sales-dialer-call-object",+ "columns": {+ "call_id": "Unique identifier for the Sales Dialer call.",+ "call_sid": "Telephony provider identifier for the call.",+ "contact_id": "Identifier of the campaign contact that was dialed.",+ "contact_number": "Phone number of the contact that was dialed.",+ "contact_name": "Name of the contact that was dialed.",+ "contact_email": "Email of the contact that was dialed.",+ "sales_dialer_number": "The JustCall number used to place the call.",+ "agent_id": "Identifier of the agent who placed the call.",+ "agent_name": "Name of the agent who placed the call.",+ "agent_email": "Email of the agent who placed the call.",+ "call_date": "Date of the call in UTC.",+ "call_time": "Time of the call in UTC.",+ "call_user_date": "Date of the call in the account's timezone.",+ "call_user_time": "Time of the call in the account's timezone.",+ "campaign": "Nested object describing the campaign the call belongs to.",+ "call_info": "Nested object with direction, type, disposition, and status of the call.",+ "justcall_ai": "JustCall AI data associated with the call, when enabled.",+ },+ },+ "contacts": {+ "description": "A contact in the JustCall address book, with phone numbers, agent ownership, and status.",+ "docs_url": "https://developer.justcall.io/reference/contacts_list_v21",+ "columns": {+ "id": "Unique identifier for the contact, generated by JustCall.",+ "first_name": "Contact's first name.",+ "last_name": "Contact's last name.",+ "phone": "Primary phone number of the contact.",+ "email": "Email address of the contact.",+ "company": "Company the contact is associated with.",+ "agent_id": "Identifier of the agent that owns the contact.",+ "notes": "Free-form notes attached to the contact.",+ },+ },+ "users": {+ "description": "A JustCall user (agent) who can make and receive calls and messages in the account.",+ "docs_url": "https://developer.justcall.io/reference/users_list_v21",+ "columns": {+ "id": "Unique identifier for the user, generated by JustCall.",+ "agent_id": "Agent identifier for the user.",+ "first_name": "User's first name.",+ "last_name": "User's last name.",+ "email": "Email address of the user.",+ "role": "Role of the user within the account.",+ },+ },+ "phone_numbers": {+ "description": "A JustCall phone number that places and receives calls and messages, with its configuration.",+ "docs_url": "https://developer.justcall.io/reference/phone_number_list_v21",+ "columns": {+ "id": "Unique identifier for the phone number, generated by JustCall.",+ "justcall_number": "The phone number in international format.",+ "friendly_number": "Human-readable formatting of the phone number.",+ "justcall_line_name": "Display name of the line.",+ "availability_setting": "Availability configuration for the number.",+ "current_status": "Current status of the number.",+ "number_type": "Type of the number (e.g. local, toll-free).",+ "capabilities": "Capabilities of the number (e.g. voice, SMS).",+ "number_owner": "Owner of the number.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/justcall/justcall.py b/products/warehouse_sources/backend/temporal/data_imports/sources/justcall/justcall.pynew file mode 100644index 000000000000..3167fb0fddb5--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/justcall/justcall.py@@ -0,0 +1,214 @@+import dataclasses+from collections.abc import Iterator+from datetime import 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.justcall.settings import (+ JUSTCALL_ENDPOINTS,+ JustCallEndpointConfig,+)++JUSTCALL_BASE_URL = "https://api.justcall.io/v2.1"+# JustCall caps list pages at 100 items across the v2.1 list endpoints.+PAGE_SIZE = 100+# v2.1 list endpoints are 0-indexed ("page 0 indicates first page").+FIRST_PAGE = 0+REQUEST_TIMEOUT_SECONDS = 60+MAX_RETRIES = 5+++class JustCallRetryableError(Exception):+ pass+++class JustCallResumeConfig:+ # Next 0-indexed page to fetch. The cursor filter (`from_datetime`) is recomputed from the+ # unchanged job inputs on resume, so only the page position needs persisting.+ page: int+++def _get_headers(api_key: str, api_secret: str) -> dict[str, str]:+ # JustCall v2.1 authenticates with the raw `api_key:api_secret` pair in the Authorization+ # header — no `Basic` prefix and no base64 encoding.+ return {+ "Authorization": f"{api_key}:{api_secret}",+ "Accept": "application/json",+ }+++def _make_session(api_key: str, api_secret: str) -> requests.Session:+ # Register the raw credential values (and the combined Authorization header value) for+ # value-based redaction, since the auth scheme puts the secret in a nonstandard raw header+ # value that name-based scrubbers can't recognise. This keeps the credentials masked in+ # request logs and captured HTTP samples on a failed sync.+ return make_tracked_session(+ headers=_get_headers(api_key, api_secret),+ redact_values=(api_key, api_secret, f"{api_key}:{api_secret}"),+ )+++def _format_cursor(value: Any) -> Optional[str]:+ """Coerce an incremental cursor value to the `yyyy-mm-dd` form JustCall's `from_datetime` takes.++ The cursor is a `_user_date` field (account-timezone date), persisted as a Date. Datetimes and+ ISO strings are handled defensively; only the date component is kept because `from_datetime`+ accepts a bare date and the watermark is day-granular.+ """+ if value is None:+ return None+ if isinstance(value, datetime):+ return value.strftime("%Y-%m-%d")+ if isinstance(value, date):+ return value.strftime("%Y-%m-%d")+ text = str(value).strip()+ if not text:+ return None+ # Handles "2021-08-25", "2021-08-25 10:30:00", and "2021-08-25T10:30:00" alike.+ return text[:10]+++def _build_params(config: JustCallEndpointConfig, page: int, from_value: Optional[str]) -> dict[str, Any]:+ params: dict[str, Any] = {"page": page, "per_page": PAGE_SIZE, "order": config.order}+ if config.incremental_cursor:+ # `sort=datetime` orders by call/SMS time; combined with `order=asc` the watermark advances+ # monotonically. `from_datetime` is only meaningful on the endpoints that support it.+ params["sort"] = "datetime"+ if from_value is not None:+ params["from_datetime"] = from_value+ return params+++def _build_url(path: str, params: dict[str, Any]) -> str:+ clean_params = {key: value for key, value in params.items() if value is not None}+ if not clean_params:+ return f"{JUSTCALL_BASE_URL}{path}"+ return f"{JUSTCALL_BASE_URL}{path}?{urlencode(clean_params)}"+++def validate_credentials(api_key: str, api_secret: str) -> bool:+ """Confirm the API key/secret pair is valid with one cheap authenticated probe.++ `/phone-numbers` is a tiny account-level list available to any valid JustCall key, so it makes a+ good token check without pulling call/message history.+ """+ try:+ response = _make_session(api_key, api_secret).get(+ _build_url("/phone-numbers", {"page": FIRST_PAGE, "per_page": 1}),+ timeout=10,+ )+ return response.status_code == 200+ except Exception:+ return False+++def get_rows(+ api_key: str,+ api_secret: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[JustCallResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = JUSTCALL_ENDPOINTS[endpoint]+ session = _make_session(api_key, api_secret)++ # Only endpoints with a server-side `from_datetime` filter honor the incremental cursor; the+ # rest are full refresh regardless of what the pipeline passes.+ from_value = (+ _format_cursor(db_incremental_field_last_value)+ if should_use_incremental_field and config.incremental_cursor+ else None+ )++ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ page = resume_config.page if resume_config is not None else FIRST_PAGE+ if resume_config is not None:+ logger.debug(f"JustCall: resuming {endpoint} from page {page}")++ @retry(+ retry=retry_if_exception_type((JustCallRetryableError, 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) -> dict[str, Any]:+ response = session.get(page_url, timeout=REQUEST_TIMEOUT_SECONDS)++ # JustCall rate-limits per API key on both a minutely burst window and an hourly window,+ # returning 429 on breach. Exponential backoff with jitter is sufficient here.+ if response.status_code == 429 or response.status_code >= 500:+ raise JustCallRetryableError(+ f"JustCall API error (retryable): status={response.status_code}, url={page_url}"+ )++ if not response.ok:+ # Deliberately not logging the response body: these endpoints return calls, texts, and+ # contacts, so a raw error payload could copy customer PII (or echoed credentials) into+ # logs. Status and endpoint are enough to debug an auth/permission failure.+ logger.error(f"JustCall API error: status={response.status_code}, url={page_url}")+ response.raise_for_status()++ return response.json()++ # Page forward, rebuilding the query each time so `from_datetime`/`sort`/`order` stay attached to+ # every request. This deliberately does not follow the response's `next_page_link`: we can't+ # verify that link preserves the time filter on later pages, and dropping it would re-walk each+ # endpoint's full history every incremental sync. A short page (< PAGE_SIZE) marks the end.+ while True:+ url = _build_url(config.path, _build_params(config, page, from_value))+ data = fetch_page(url)+ items = data.get("data", []) or []++ if items:+ yield items+ # Save the page we just yielded (not the next one) AFTER yielding it, so a crash+ # re-fetches and re-yields this page rather than skipping it — the primary-key merge+ # dedupes the overlap.+ resumable_source_manager.save_state(JustCallResumeConfig(page=page))++ if len(items) < PAGE_SIZE:+ break++ page += 1+++def justcall_source(+ api_key: str,+ api_secret: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[JustCallResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = JUSTCALL_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ api_secret=api_secret,+ 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],+ sort_mode="asc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.incremental_cursor else None,+ partition_format="week" if config.incremental_cursor else None,+ partition_keys=[config.incremental_cursor] if config.incremental_cursor else None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/justcall/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/justcall/settings.pynew file mode 100644index 000000000000..ca5b7977204f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/justcall/settings.py@@ -0,0 +1,84 @@+from dataclasses import dataclass+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+++@dataclass+class JustCallEndpointConfig:+ name: str+ path: str+ primary_key: str = "id"+ # User-timezone date field the JustCall `from_datetime` filter aligns with. When set, the+ # endpoint supports server-side incremental sync (rows are requested ascending with+ # `sort=datetime` and bounded by `from_datetime`), and this field doubles as the stable+ # datetime partition key. When None the endpoint is full refresh only.+ #+ # JustCall exposes both UTC (`call_date`) and account-timezone (`call_user_date`) date fields;+ # `from_datetime` is documented as being interpreted in the account timezone, so the cursor+ # must be the `_user_` variant for the watermark and the filter to agree.+ incremental_cursor: Optional[str] = None+ # `order` casing differs per endpoint in JustCall's API (calls/texts accept lowercase+ # `asc`/`desc`; phone-numbers documents uppercase `ASC`/`DESC`). Ascending keeps already-paged+ # results stable under concurrent inserts and lets the incremental watermark advance monotonically.+ order: str = "asc"+++def _incremental_fields(cursor: str) -> list[IncrementalField]:+ # JustCall's `_user_date` fields are `yyyy-mm-dd` strings, so the DB field type is Date even+ # though the UI presents a datetime cursor. Day-granularity is intentional: `from_datetime`+ # re-fetches the boundary day each sync and the primary-key merge dedupes the overlap.+ return [+ {+ "label": cursor,+ "type": IncrementalFieldType.DateTime,+ "field": cursor,+ "field_type": IncrementalFieldType.Date,+ }+ ]+++# Endpoints are the JustCall v2.1 list resources a warehouse user is most likely to want:+# telephony (calls), messaging (texts), the sales-dialer contact-center calls, plus the+# supporting dimensions (contacts, users, phone numbers). Analytics/aggregate endpoints are+# intentionally excluded — they return computed rollups, not raw records.+JUSTCALL_ENDPOINTS: dict[str, JustCallEndpointConfig] = {+ "calls": JustCallEndpointConfig(+ name="calls",+ path="/calls",+ incremental_cursor="call_user_date",+ ),+ "texts": JustCallEndpointConfig(+ name="texts",+ path="/texts",+ incremental_cursor="sms_user_date",+ ),+ "sales_dialer_calls": JustCallEndpointConfig(+ name="sales_dialer_calls",+ path="/sales_dialer/calls",+ # Sales Dialer calls key their id under `call_id`, not `id`.+ primary_key="call_id",+ incremental_cursor="call_user_date",+ ),+ "contacts": JustCallEndpointConfig(+ name="contacts",+ path="/contacts",+ ),+ "users": JustCallEndpointConfig(+ name="users",+ path="/users",+ ),+ "phone_numbers": JustCallEndpointConfig(+ name="phone_numbers",+ path="/phone-numbers",+ order="ASC",+ ),+}++ENDPOINTS = tuple(JUSTCALL_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: _incremental_fields(config.incremental_cursor)+ for name, config in JUSTCALL_ENDPOINTS.items()+ if config.incremental_cursor+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/justcall/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/justcall/source.pyindex 9002678bf724..3094b9ddbe70 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/justcall/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/justcall/source.py@@ -1,30 +1,146 @@-from typing import cast+from typing import Optional, castfrom 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 SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import JustCallSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.justcall.justcall import (+ JustCallResumeConfig,+ justcall_source,+ validate_credentials as validate_justcall_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.justcall.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class JustCallSource(SimpleSource[JustCallSourceConfig]):+class JustCallSource(ResumableSource[JustCallSourceConfig, JustCallResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.JUSTCALL+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://api.justcall.io": "JustCall authentication failed. Please check your API key and secret.",+ "403 Client Error: Forbidden for url: https://api.justcall.io": "JustCall denied access. Please check that your API key has permission for the resources you are syncing.",+ }+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.JUST_CALL,category=DataWarehouseSourceCategory.COMMUNICATION,label="JustCall",+ caption="""Enter your JustCall API credentials to pull your JustCall data into the PostHog Data warehouse.++Generate an API key and secret under **Account Settings → Developers (APIs and Webhooks)** in your [JustCall dashboard](https://app.justcall.io/). The credentials have read access to your account's calls, texts, contacts, and phone numbers.""",iconPath="/static/services/justcall.png",- fields=cast(list[FieldType], []),+ docsUrl="https://posthog.com/docs/cdp/sources/justcall",+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="api_secret",+ label="API secret",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.justcall.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: JustCallSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = []+ for endpoint in ENDPOINTS:+ incremental_fields = INCREMENTAL_FIELDS.get(endpoint, [])+ schemas.append(+ SourceSchema(+ name=endpoint,+ supports_incremental=bool(incremental_fields),+ supports_append=bool(incremental_fields),+ incremental_fields=incremental_fields,+ )+ )++ 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: JustCallSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_justcall_credentials(config.api_key, config.api_secret):+ return True, None++ return False, "Invalid JustCall API credentials"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[JustCallResumeConfig]:+ return ResumableSourceManager[JustCallResumeConfig](inputs, JustCallResumeConfig)++ def source_for_pipeline(+ self,+ config: JustCallSourceConfig,+ resumable_source_manager: ResumableSourceManager[JustCallResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return justcall_source(+ api_key=config.api_key,+ api_secret=config.api_secret,+ 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/justcall/tests/test_justcall.py b/products/warehouse_sources/backend/temporal/data_imports/sources/justcall/tests/test_justcall.pynew file mode 100644index 000000000000..62ccc32aefdb--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/justcall/tests/test_justcall.py@@ -0,0 +1,212 @@+from datetime import date, datetime+from typing import Any++import pytest+from unittest import mock++from products.warehouse_sources.backend.temporal.data_imports.sources.justcall.justcall import (+ JustCallResumeConfig,+ _build_params,+ _build_url,+ _format_cursor,+ get_rows,+ justcall_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.justcall.settings import (+ ENDPOINTS,+ JUSTCALL_ENDPOINTS,+)++MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.justcall.justcall"+++def _make_manager(resume_state: JustCallResumeConfig | 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+++def _page(items: list[dict[str, Any]]) -> dict[str, Any]:+ return {"data": items, "next_page_link": None}+++def _responses(pages: list[dict[str, Any]]) -> list[mock.MagicMock]:+ out = []+ for page in pages:+ resp = mock.MagicMock(status_code=200, ok=True)+ resp.json.return_value = page+ out.append(resp)+ return out+++class TestFormatCursor:+ @pytest.mark.parametrize(+ "value, expected",+ [+ (None, None),+ ("", None),+ (" ", None),+ ("2021-08-25", "2021-08-25"),+ ("2021-08-25 10:30:00", "2021-08-25"),+ ("2021-08-25T10:30:00", "2021-08-25"),+ (date(2021, 8, 25), "2021-08-25"),+ (datetime(2021, 8, 25, 10, 30, 0), "2021-08-25"),+ ],+ )+ def test_format_cursor(self, value, expected):+ assert _format_cursor(value) == expected+++class TestBuildParams:+ def test_incremental_endpoint_sorts_by_datetime_ascending(self):+ params = _build_params(JUSTCALL_ENDPOINTS["calls"], page=0, from_value=None)+ assert params["sort"] == "datetime"+ assert params["order"] == "asc"+ assert params["per_page"] == 100+ assert params["page"] == 0+ assert "from_datetime" not in params++ def test_incremental_endpoint_includes_from_datetime_when_set(self):+ params = _build_params(JUSTCALL_ENDPOINTS["calls"], page=2, from_value="2021-08-25")+ assert params["from_datetime"] == "2021-08-25"+ assert params["page"] == 2++ def test_full_refresh_endpoint_has_no_sort_or_filter(self):+ params = _build_params(JUSTCALL_ENDPOINTS["users"], page=0, from_value="2021-08-25")+ assert "sort" not in params+ # A full-refresh endpoint never carries a time filter, even if a value is passed in.+ assert "from_datetime" not in params++ def test_phone_numbers_uses_uppercase_order(self):+ params = _build_params(JUSTCALL_ENDPOINTS["phone_numbers"], page=0, from_value=None)+ assert params["order"] == "ASC"+++class TestBuildUrl:+ def test_no_params(self):+ assert _build_url("/calls", {}) == "https://api.justcall.io/v2.1/calls"++ def test_drops_none_and_encodes(self):+ url = _build_url("/calls", {"page": 0, "per_page": 100, "from_datetime": None})+ assert url == "https://api.justcall.io/v2.1/calls?page=0&per_page=100"+++class TestValidateCredentials:+ @pytest.mark.parametrize("status_code, expected", [(200, True), (401, False), (403, False), (500, False)])+ @mock.patch(f"{MODULE}.make_tracked_session")+ def test_status_mapping(self, mock_session, status_code, expected):+ response = mock.MagicMock(status_code=status_code)+ mock_session.return_value.get.return_value = response+ assert validate_credentials("key", "secret") is expected++ @mock.patch(f"{MODULE}.make_tracked_session")+ def test_swallows_exceptions(self, mock_session):+ mock_session.return_value.get.side_effect = Exception("boom")+ assert validate_credentials("key", "secret") is False+++class TestGetRows:+ @mock.patch(f"{MODULE}.PAGE_SIZE", 2)+ @mock.patch(f"{MODULE}.make_tracked_session")+ def test_paginates_until_short_page(self, mock_session):+ # Full page (== PAGE_SIZE) continues; a short page ends pagination.+ mock_session.return_value.get.side_effect = _responses([_page([{"id": 1}, {"id": 2}]), _page([{"id": 3}])])++ manager = _make_manager()+ batches = list(get_rows("key", "secret", "users", mock.MagicMock(), manager))++ assert [item["id"] for batch in batches for item in batch] == [1, 2, 3]+ assert mock_session.return_value.get.call_count == 2+ # Each yielded page is checkpointed after it is yielded, by its own page number.+ assert manager.save_state.call_args_list == [+ mock.call(JustCallResumeConfig(page=0)),+ mock.call(JustCallResumeConfig(page=1)),+ ]++ @mock.patch(f"{MODULE}.PAGE_SIZE", 2)+ @mock.patch(f"{MODULE}.make_tracked_session")+ def test_empty_first_page_stops_without_saving(self, mock_session):+ mock_session.return_value.get.side_effect = _responses([_page([])])++ manager = _make_manager()+ batches = list(get_rows("key", "secret", "calls", mock.MagicMock(), manager))++ assert batches == []+ manager.save_state.assert_not_called()++ @mock.patch(f"{MODULE}.PAGE_SIZE", 2)+ @mock.patch(f"{MODULE}.make_tracked_session")+ def test_resumes_from_saved_page(self, mock_session):+ mock_session.return_value.get.side_effect = _responses([_page([{"id": 9}])])++ manager = _make_manager(JustCallResumeConfig(page=5))+ list(get_rows("key", "secret", "calls", mock.MagicMock(), manager))++ requested_url = mock_session.return_value.get.call_args_list[0].args[0]+ assert "page=5" in requested_url++ @mock.patch(f"{MODULE}.make_tracked_session")+ def test_incremental_request_carries_from_datetime(self, mock_session):+ mock_session.return_value.get.side_effect = _responses([_page([{"id": 1, "call_user_date": "2021-08-25"}])])++ manager = _make_manager()+ list(+ get_rows(+ "key",+ "secret",+ "calls",+ mock.MagicMock(),+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value="2021-08-25",+ )+ )++ url = mock_session.return_value.get.call_args_list[0].args[0]+ assert "from_datetime=2021-08-25" in url+ assert "sort=datetime" in url++ @mock.patch(f"{MODULE}.make_tracked_session")+ def test_full_refresh_endpoint_ignores_incremental_value(self, mock_session):+ # `users` has no server-side time filter, so an incremental value must not leak into the request.+ mock_session.return_value.get.side_effect = _responses([_page([{"id": 1}])])++ manager = _make_manager()+ list(+ get_rows(+ "key",+ "secret",+ "users",+ mock.MagicMock(),+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value="2021-08-25",+ )+ )++ url = mock_session.return_value.get.call_args_list[0].args[0]+ assert "from_datetime" not in url+++class TestJustCallSourceResponse:+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_response_metadata_per_endpoint(self, endpoint):+ config = JUSTCALL_ENDPOINTS[endpoint]+ response = justcall_source("key", "secret", endpoint, mock.MagicMock(), _make_manager())++ assert response.name == endpoint+ assert response.primary_keys == [config.primary_key]+ assert response.sort_mode == "asc"+ if config.incremental_cursor:+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [config.incremental_cursor]+ else:+ assert response.partition_mode is None+ assert response.partition_keys is None++ @pytest.mark.parametrize("config", list(JUSTCALL_ENDPOINTS.values()))+ def test_partition_keys_are_stable_user_date_fields(self, config):+ if config.incremental_cursor:+ assert config.incremental_cursor in {"call_user_date", "sms_user_date"}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/justcall/tests/test_justcall_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/justcall/tests/test_justcall_source.pynew file mode 100644index 000000000000..7d66c6616b02--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/justcall/tests/test_justcall_source.py@@ -0,0 +1,159 @@+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 JustCallSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.justcall.justcall import JustCallResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.justcall.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.justcall.source import JustCallSource+from products.warehouse_sources.backend.types import ExternalDataSourceType++SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.justcall.source"+++class TestJustCallSource:+ def setup_method(self):+ self.source = JustCallSource()+ self.team_id = 123+ self.config = JustCallSourceConfig(api_key="key", api_secret="secret")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.JUSTCALL++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "JustCall"+ assert config.label == "JustCall"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is True+ assert config.iconPath == "/static/services/justcall.png"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["api_key", "api_secret"]++ @pytest.mark.parametrize("field_name", ["api_key", "api_secret"])+ def test_credential_fields_are_secret_passwords(self, field_name):+ config = self.source.get_source_config+ secret_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == field_name)+ assert secret_field.type == SourceFieldInputConfigType.PASSWORD+ assert secret_field.secret is True+ assert secret_field.required is True++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://api.justcall.io/v2.1/calls?page=0",+ "403 Client Error: Forbidden for url: https://api.justcall.io/v2.1/texts",+ ],+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error):+ 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",+ [+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",+ "500 Server Error for url: https://api.justcall.io/v2.1/calls",+ ],+ )+ def test_non_retryable_errors_ignore_unrelated(self, other_error):+ 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):+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {schema.name for schema in schemas} == set(ENDPOINTS)++ def test_only_time_filterable_endpoints_support_incremental(self):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ incremental = {name for name, schema in schemas.items() if schema.supports_incremental}+ # Only calls, texts, and sales dialer calls expose JustCall's from_datetime filter.+ assert incremental == {"calls", "texts", "sales_dialer_calls"}++ assert schemas["calls"].incremental_fields == INCREMENTAL_FIELDS["calls"]+ assert schemas["contacts"].incremental_fields == []+ assert schemas["contacts"].supports_append is False++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["calls"])+ assert [s.name for s in schemas] == ["calls"]++ def test_get_schemas_filtered_unknown_name_returns_empty(self):+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_lists_tables_without_credentials(self):+ # The endpoint catalog is static (no I/O), so it's safe to render in public docs.+ assert JustCallSource.lists_tables_without_credentials is True++ def test_documented_tables_render_from_static_catalog(self):+ tables = self.source.get_documented_tables()+ names = {t["name"] for t in tables}+ assert set(ENDPOINTS).issubset(names)+ # Canonical descriptions flow through to the rendered docs.+ calls = next(t for t in tables if t["name"] == "calls")+ assert calls["description"]++ def test_canonical_descriptions_cover_every_endpoint(self):+ descriptions = self.source.get_canonical_descriptions()+ for endpoint in ENDPOINTS:+ assert endpoint in descriptions, f"missing canonical description for {endpoint}"+ assert descriptions[endpoint]["columns"]++ @pytest.mark.parametrize(+ "probe_result, expected_valid, expected_message",+ [+ (True, True, None),+ (False, False, "Invalid JustCall API credentials"),+ ],+ )+ @mock.patch(f"{SOURCE_MODULE}.validate_justcall_credentials")+ def test_validate_credentials(self, mock_validate, probe_result, expected_valid, expected_message):+ mock_validate.return_value = probe_result++ is_valid, message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is expected_valid+ assert message == expected_message+ mock_validate.assert_called_once_with(self.config.api_key, self.config.api_secret)++ def test_get_resumable_source_manager_binds_resume_config(self):+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is JustCallResumeConfig++ @mock.patch(f"{SOURCE_MODULE}.justcall_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_justcall_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "calls"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2021-08-25"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = mock_justcall_source.call_args.kwargs+ assert kwargs["api_key"] == "key"+ assert kwargs["api_secret"] == "secret"+ assert kwargs["endpoint"] == "calls"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2021-08-25"++ @mock.patch(f"{SOURCE_MODULE}.justcall_source")+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_justcall_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "users"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2021-08-25"++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_justcall_source.call_args.kwargs["db_incremental_field_last_value"] is None