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 the yotpo import source (#115762)

Tom Owersfeee4fe97d2d
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 e8b680f68a98..6957910b2266 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -909,6 +909,7 @@ the row lists both.
| xsolla | HTTP | requests + `rest_source.RESTClient` | ✅ |
| ynab | HTTP | requests + `rest_source.RESTClient` | ✅ |
| yoco | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| yotpo | HTTP | requests + `rest_source.RESTClient` | ✅ |
| yousign | HTTP + Webhook | requests + `rest_source.RESTClient` + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |
| youtube_analytics | HTTP | requests | ✅ |
| youtube_data | HTTP | requests + `rest_source.RESTClient` | ✅ |
@@ -1535,7 +1536,6 @@ doesn't conflict with concurrent PRs.
- xero
- yahoo_finance
- yandex_metrica
-- yotpo
- younium
- zalando_zdirect
- zapsign
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/yotpo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/yotpo.py
index 23c1a3d4477e..4b29c33bb39b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/yotpo.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/yotpo.py
@@ -6,4 +6,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class YotpoSourceConfig(config.Config):
- pass
+ app_key: str
+ api_secret: str
+ start_date: str
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/yotpo/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/yotpo/canonical_descriptions.py
new file mode 100644
index 000000000000..332ad7a0eb52
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/yotpo/canonical_descriptions.py
@@ -0,0 +1,47 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "reviews": {
+ "description": "Product and site reviews submitted to the store.",
+ "docs_url": "https://apidocs.yotpo.com/reference/retrieve-all-reviews",
+ "columns": {
+ "id": "The Yotpo review ID.",
+ "created_at": "The time the review was created.",
+ "updated_at": "The time the review was last updated.",
+ "score": "The review's star rating.",
+ "sku": "The product SKU associated with the review.",
+ "deleted": "Whether the review is unpublished.",
+ },
+ },
+ "email_analytics": {
+ "description": "Daily counts of emails sent, grouped by email type.",
+ "docs_url": "https://apidocs.yotpo.com/reference/email-analytics",
+ "columns": {
+ "since": "The first date included in this reporting period.",
+ "until": "The last date included in this reporting period.",
+ "values": "Email counts grouped by email type.",
+ },
+ },
+ "raw_data": {
+ "description": "Email delivery and engagement records.",
+ "docs_url": "https://apidocs.yotpo.com/reference/raw-data",
+ "columns": {
+ "email_address": "The recipient's email address.",
+ "email_type": "The type of email sent by Yotpo.",
+ "email_sent_timestamp": "The time Yotpo sent the email.",
+ "opened_timestamp": "The time the recipient opened the email.",
+ "unsubscribed_timestamp": "The time the recipient unsubscribed.",
+ },
+ },
+ "unsubscribers": {
+ "description": "Email addresses excluded from Yotpo email distribution lists.",
+ "docs_url": "https://apidocs.yotpo.com/reference/retrieve-a-list-of-unsubscribers",
+ "columns": {
+ "user_email": "The unsubscribed email address.",
+ "email_type_id": "The email distribution list identifier.",
+ "unsubscribed_by_name": "Who requested the unsubscribe action.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/yotpo/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/yotpo/settings.py
new file mode 100644
index 000000000000..6b44d1879060
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/yotpo/settings.py
@@ -0,0 +1,61 @@
+from dataclasses import field
+
+from posthog.dataclasses import frozen
+
+BASE_URL = "https://api.yotpo.com/"
+REQUEST_TIMEOUT = (10, 30)
+
+
+@frozen
+class YotpoEndpoint:
+ path: str
+ data_selector: str
+ description: str
+ primary_keys: tuple[str, ...] | None = None
+ partition_key: str | None = None
+ page_size_param: str | None = None
+ email_date_range: bool = False
+ params: dict[str, str] = field(default_factory=dict)
+ token_query_param: str | None = None
+
+
+# Timestamp filters have not been verified with an account, so every table uses full refresh.
+ENDPOINTS: dict[str, YotpoEndpoint] = {
+ "reviews": YotpoEndpoint(
+ path="v1/apps/{app_key}/reviews",
+ data_selector="reviews",
+ description="Product and site reviews, including unpublished reviews.",
+ primary_keys=("id",),
+ partition_key="created_at",
+ page_size_param="count",
+ params={"deleted": "true"},
+ ),
+ "email_analytics": YotpoEndpoint(
+ path="analytics/v1/emails/{app_key}/emails_sent",
+ data_selector="date_series_points",
+ description="Daily counts of review request emails sent, grouped by email type, from the configured start date.",
+ primary_keys=("since", "until"),
+ partition_key="since",
+ email_date_range=True,
+ params={"date_bucket": "day", "group_by": "email_type"},
+ token_query_param="token",
+ ),
+ "raw_data": YotpoEndpoint(
+ path="analytics/v1/emails/{app_key}/export/raw_data",
+ data_selector="records",
+ description="Email delivery and engagement records from the configured start date.",
+ # The API exposes no unique email delivery ID, so a guessed key could discard records.
+ primary_keys=None,
+ partition_key="email_sent_timestamp",
+ page_size_param="per_page",
+ email_date_range=True,
+ # The docs name sort directions but do not define their parameter values.
+ ),
+ "unsubscribers": YotpoEndpoint(
+ path="apps/{app_key}/unsubscribers",
+ data_selector="response.unsubscribers",
+ description="Email addresses excluded from Yotpo review request emails.",
+ primary_keys=("user_email", "email_type_id"),
+ page_size_param="count",
+ ),
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/yotpo/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/yotpo/source.py
index 4583b001c543..e62909f48808 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/yotpo/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/yotpo/source.py
@@ -1,25 +1,174 @@
from typing import cast
-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from requests import HTTPError, RequestException
+
+from products.warehouse_sources.backend.facade.source_config import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+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.rest_source.rest_client import (
+ RESTClientRetryableError,
+)
+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,
+ UnknownResourceError,
+ schema_for_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.yotpo import YotpoSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.yotpo.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.yotpo.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.yotpo.yotpo import (
+ YotpoAuthenticationError,
+ YotpoResumeConfig,
+ validate_credentials as validate_yotpo_credentials,
+ validate_start_date,
+ yotpo_source,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class YotpoSource(SimpleSource[YotpoSourceConfig]):
+class YotpoSource(ResumableSource[YotpoSourceConfig, YotpoResumeConfig]):
+ lists_tables_without_credentials = True
+ # Storefront V3 cannot replace the authenticated merchant review and email endpoints.
+ api_docs_url = "https://apidocs.yotpo.com/reference/retrieve-all-reviews"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.YOTPO
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "Yotpo rejected the app key or API secret": "Check your Yotpo app key and API secret, then reconnect.",
+ "Yotpo did not return an access token": "Check your Yotpo API credentials, then reconnect.",
+ "401 Client Error": "Your Yotpo access token is invalid or expired. Check your credentials, then reconnect.",
+ "403 Client Error": "Yotpo denied access to this table. Check your account's API access.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: YotpoSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return [
+ SourceSchema(
+ name=name,
+ supports_incremental=False,
+ supports_append=False,
+ description=settings.description,
+ detected_primary_keys=list(settings.primary_keys) if settings.primary_keys else None,
+ )
+ for name, settings in ENDPOINTS.items()
+ if names is None or name in names
+ ]
+
+ def validate_credentials(
+ self,
+ config: YotpoSourceConfig,
+ team_id: int,
+ schema_name: str | None = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ if not config.app_key.strip() or not config.api_secret.strip():
+ return False, "Enter your Yotpo app key and API secret."
+ if schema_name is not None:
+ try:
+ schema_for_resource(ENDPOINTS, schema_name)
+ except UnknownResourceError:
+ return False, "This Yotpo table is not supported."
+ try:
+ validate_start_date(config.start_date)
+ except ValueError:
+ return False, "Enter a start date in YYYY-MM-DD format that is not in the future."
+ try:
+ validate_yotpo_credentials(config.app_key, config.api_secret, config.start_date, schema_name)
+ except YotpoAuthenticationError as error:
+ return False, str(error)
+ except HTTPError as error:
+ if error.response is not None and error.response.status_code == 401:
+ return False, "Yotpo rejected the access token. Check your app key and API secret."
+ if error.response is not None and error.response.status_code == 403:
+ return False, "Yotpo denied access to this table. Check your account's API access."
+ return False, "Yotpo could not validate your credentials. Try again."
+ except (RequestException, RESTClientRetryableError, ValueError):
+ return False, "Yotpo could not validate your credentials. Try again."
+ return True, None
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[YotpoResumeConfig]:
+ return ResumableSourceManager(inputs, YotpoResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: YotpoSourceConfig,
+ resumable_source_manager: ResumableSourceManager[YotpoResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return yotpo_source(
+ app_key=config.app_key,
+ api_secret=config.api_secret,
+ start_date=config.start_date,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ resumable_source_manager=resumable_source_manager,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=ExternalDataSourceType.YOTPO,
- category=DataWarehouseSourceCategory.E_COMMERCE,
+ category=DataWarehouseSourceCategory.MARKETING___EMAIL,
label="Yotpo",
+ docsUrl="https://posthog.com/docs/cdp/sources/yotpo",
iconPath="/static/services/yotpo.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="app_key",
+ label="App key (store ID)",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="api_secret",
+ label="API secret",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="start_date",
+ label="Start date for email data",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="YYYY-MM-DD",
+ caption="Email tables include data from this date. Reviews and unsubscribers include all available records.",
+ secret=False,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/yotpo/tests/test_yotpo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/yotpo/tests/test_yotpo.py
new file mode 100644
index 000000000000..5a43007345de
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/yotpo/tests/test_yotpo.py
@@ -0,0 +1,129 @@
+from datetime import UTC, datetime
+
+import pytest
+
+from requests import HTTPError
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import UnknownResourceError
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ SourceDriver,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.yotpo import YotpoSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.yotpo.source import YotpoSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.yotpo.yotpo import YotpoResumeConfig
+
+
+ ("endpoint", "envelope", "row", "size_param"),
+ [
+ ("reviews", "reviews", {"id": 1, "created_at": "2020-01-02T00:00:00Z", "deleted": True}, "count"),
+ (
+ "raw_data",
+ "records",
+ {"email_address": "[email protected]", "email_sent_timestamp": "2020-01-02T00:00:00Z"},
+ "per_page",
+ ),
+ ("unsubscribers", "unsubscribers", {"user_email": "[email protected]", "email_type_id": 1}, "count"),
+ ],
+)
+def test_paginated_tables_extract_rows_and_commit_the_next_page(
+ endpoint: str, envelope: str, row: dict[str, object], size_param: str
+) -> None:
+ def page(rows: list[dict[str, object]]) -> ScriptedResponse:
+ payload = {envelope: rows}
+ return ScriptedResponse(json={"response": payload} if endpoint == "unsubscribers" else payload)
+
+ until = datetime.now(UTC).date().isoformat()
+ result = SourceDriver(
+ YotpoSource(), YotpoSourceConfig(app_key="test-store", api_secret="test-secret", start_date="2020-01-01")
+ ).run(
+ endpoint,
+ [ScriptedResponse(json={"access_token": "test-token"}), page([row]), page([row]), page([])],
+ )
+
+ assert result.raised is None
+ assert result.rows == [row, row]
+ assert result.requests[0].path == "/oauth/token"
+ assert result.requests[0].json() == {
+ "client_id": "test-store",
+ "client_secret": "test-secret",
+ "grant_type": "client_credentials",
+ }
+ assert result.params("page")[1:] == ["1", "2", "3"]
+ assert result.params(size_param)[1:] == ["100", "100", "100"]
+ assert all(request.headers["x-yotpo-token"] == "test-token" for request in result.requests[1:])
+ assert result.committed_states == [YotpoResumeConfig(page=2, until=until), YotpoResumeConfig(page=3, until=until)]
+ if endpoint == "reviews":
+ assert result.params("deleted")[1:] == ["true", "true", "true"]
+ assert result.params("since_date")[1:] == [None, None, None]
+ assert result.paths[1:] == ["/v1/apps/test-store/reviews"] * 3
+ elif endpoint == "raw_data":
+ assert result.params("since")[1:] == ["2020-01-01"] * 3
+ assert result.params("until")[1:] == [until] * 3
+ assert result.params("sort")[1:] == [None] * 3
+ assert result.paths[1:] == ["/analytics/v1/emails/test-store/export/raw_data"] * 3
+ else:
+ assert result.paths[1:] == ["/apps/test-store/unsubscribers"] * 3
+ assert result.session_options[0]["capture"] is False
+ assert "test-secret" in result.session_options[0]["redact_values"]
+ assert "test-token" in result.session_options[1]["redact_values"]
+
+
+def test_email_analytics_requests_daily_buckets_with_an_explicit_date_range() -> None:
+ row = {"since": "2020-01-01", "until": "2020-01-01", "values": {"map": 4}}
+ result = SourceDriver(
+ YotpoSource(), YotpoSourceConfig(app_key="test-store", api_secret="test-secret", start_date="2020-01-01")
+ ).run(
+ "email_analytics",
+ [ScriptedResponse(json={"access_token": "test-token"}), ScriptedResponse(json={"date_series_points": [row]})],
+ )
+
+ assert result.raised is None
+ assert result.rows == [row]
+ request = result.requests[1]
+ assert request.path == "/analytics/v1/emails/test-store/emails_sent"
+ assert request.param("token") == "test-token"
+ assert request.param("date_bucket") == "day"
+ assert request.param("group_by") == "email_type"
+ assert request.param("since") == "2020-01-01"
+ assert request.param("until") == datetime.now(UTC).date().isoformat()
+ assert len(result.requests) == 2
+
+
+def test_resume_preserves_the_email_window_and_skips_written_pages() -> None:
+ resume = YotpoResumeConfig(page=4, until="2020-02-01")
+ result = SourceDriver(
+ YotpoSource(), YotpoSourceConfig(app_key="test-store", api_secret="test-secret", start_date="2020-01-01")
+ ).run(
+ "raw_data",
+ [ScriptedResponse(json={"access_token": "test-token"}), ScriptedResponse(json={"records": []})],
+ resume_state=resume,
+ )
+ assert result.raised is None
+ assert result.requests[1].param("page") == "4"
+ assert result.requests[1].param("until") == "2020-02-01"
+
+
+def test_a_failed_next_page_keeps_the_cursor_of_the_written_batch() -> None:
+ result = SourceDriver(
+ YotpoSource(), YotpoSourceConfig(app_key="test-store", api_secret="test-secret", start_date="2020-01-01")
+ ).run(
+ "reviews",
+ [
+ ScriptedResponse(json={"access_token": "test-token"}),
+ ScriptedResponse(json={"reviews": [{"id": 1}]}),
+ ScriptedResponse(status=403, json={}),
+ ],
+ )
+ assert isinstance(result.raised, HTTPError)
+ assert result.rows == [{"id": 1}]
+ assert result.committed_states == [YotpoResumeConfig(page=2, until=datetime.now(UTC).date().isoformat())]
+
+
+def test_unknown_table_fails_before_minting_a_token() -> None:
+ result = SourceDriver(
+ YotpoSource(), YotpoSourceConfig(app_key="test-store", api_secret="test-secret", start_date="2020-01-01")
+ ).run("unknown", [])
+ assert isinstance(result.raised, UnknownResourceError)
+ assert result.requests == []
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/yotpo/tests/test_yotpo_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/yotpo/tests/test_yotpo_source.py
new file mode 100644
index 000000000000..f6b65d75e1a2
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/yotpo/tests/test_yotpo_source.py
@@ -0,0 +1,110 @@
+from datetime import UTC, datetime, timedelta
+
+import pytest
+
+from requests import ConnectionError
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ ScriptedResponse,
+ always,
+ scripted_network,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.yotpo import YotpoSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.yotpo.source import YotpoSource
+
+
+ ("app_key", "secret", "start_date", "schema_name", "message"),
+ [
+ (" ", "test-secret", "2020-01-01", None, "Enter your Yotpo app key and API secret."),
+ ("test-store", "", "2020-01-01", None, "Enter your Yotpo app key and API secret."),
+ ("test-store", "test-secret", "2020-01-01", "unknown", "This Yotpo table is not supported."),
+ (
+ "test-store",
+ "test-secret",
+ "20200101",
+ None,
+ "Enter a start date in YYYY-MM-DD format that is not in the future.",
+ ),
+ (
+ "test-store",
+ "test-secret",
+ "bad-date",
+ None,
+ "Enter a start date in YYYY-MM-DD format that is not in the future.",
+ ),
+ (
+ "test-store",
+ "test-secret",
+ (datetime.now(UTC).date() + timedelta(days=1)).isoformat(),
+ None,
+ "Enter a start date in YYYY-MM-DD format that is not in the future.",
+ ),
+ ],
+)
+def test_invalid_configuration_fails_without_http(
+ app_key: str, secret: str, start_date: str, schema_name: str | None, message: str
+) -> None:
+ with scripted_network([]) as network:
+ result = YotpoSource().validate_credentials(
+ YotpoSourceConfig(app_key=app_key, api_secret=secret, start_date=start_date), 1, schema_name=schema_name
+ )
+ assert result == (False, message)
+ assert network.requests_log == []
+
+
[email protected]("status", [400, 401, 403])
+def test_token_rejection_returns_a_credential_error(status: int) -> None:
+ with scripted_network([ScriptedResponse(status=status, json={"error": "invalid_client"})]):
+ result = YotpoSource().validate_credentials(
+ YotpoSourceConfig(app_key="test-store", api_secret="test-secret", start_date="2020-01-01"), 1
+ )
+ assert result == (False, "Yotpo rejected the app key or API secret.")
+
+
[email protected]("payload", [{}, {"access_token": None}, {"access_token": 1}])
+def test_malformed_token_response_does_not_start_an_import(payload: dict[str, object]) -> None:
+ with scripted_network([ScriptedResponse(json=payload)]) as network:
+ result = YotpoSource().validate_credentials(
+ YotpoSourceConfig(app_key="test-store", api_secret="test-secret", start_date="2020-01-01"), 1
+ )
+ assert result == (False, "Yotpo did not return an access token.")
+ assert len(network.requests_log) == 1
+
+
+ ("response", "expected"),
+ [
+ (ScriptedResponse(json={"reviews": []}), (True, None)),
+ (
+ ScriptedResponse(status=401, json={}),
+ (False, "Yotpo rejected the access token. Check your app key and API secret."),
+ ),
+ (
+ ScriptedResponse(status=403, json={}),
+ (False, "Yotpo denied access to this table. Check your account's API access."),
+ ),
+ (ScriptedResponse(status=404, json={}), (False, "Yotpo could not validate your credentials. Try again.")),
+ (
+ ScriptedResponse(json={"error": "unsupported"}),
+ (False, "Yotpo could not validate your credentials. Try again."),
+ ),
+ ],
+)
+def test_validation_reads_a_table_and_maps_permission_errors(
+ response: ScriptedResponse, expected: tuple[bool, str | None]
+) -> None:
+ with scripted_network([ScriptedResponse(json={"access_token": "test-token"}), response]) as network:
+ result = YotpoSource().validate_credentials(
+ YotpoSourceConfig(app_key="test-store", api_secret="test-secret", start_date="2020-01-01"), 1
+ )
+ assert result == expected
+ assert network.requests_log[1].param("count") == "1"
+
+
+def test_connection_failure_returns_a_safe_error() -> None:
+ with scripted_network(always(ConnectionError("test-secret"))):
+ result = YotpoSource().validate_credentials(
+ YotpoSourceConfig(app_key="test-store", api_secret="test-secret", start_date="2020-01-01"), 1
+ )
+ assert result == (False, "Yotpo could not validate your credentials. Try again.")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/yotpo/yotpo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/yotpo/yotpo.py
new file mode 100644
index 000000000000..884260e97d94
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/yotpo/yotpo.py
@@ -0,0 +1,185 @@
+from collections.abc import Generator
+from datetime import UTC, date, datetime
+from typing import Any, cast
+from urllib.parse import quote
+
+from requests import HTTPError
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
+ RESTAPIConfig,
+ RESTClient,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ PageNumberPaginator,
+ SinglePagePaginator,
+)
+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.schema import schema_for_resource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.yotpo.settings import (
+ BASE_URL,
+ ENDPOINTS,
+ REQUEST_TIMEOUT,
+)
+
+
+class YotpoAuthenticationError(Exception):
+ pass
+
+
+@frozen
+class YotpoResumeConfig:
+ page: int
+ until: str | None = None
+
+
+def validate_start_date(value: str) -> None:
+ parsed = date.fromisoformat(value)
+ if parsed.isoformat() != value or parsed > datetime.now(UTC).date():
+ raise ValueError("Enter a start date in YYYY-MM-DD format that is not in the future.")
+
+
+def get_access_token(app_key: str, api_secret: str) -> str:
+ # JSON is required by Yotpo; the framework OAuth helper sends form data.
+ with make_tracked_session(redact_values=(api_secret,), capture=False) as session:
+ client = RESTClient(
+ base_url=BASE_URL,
+ session=session,
+ allowed_hosts=[],
+ allow_redirects=False,
+ request_timeout=REQUEST_TIMEOUT,
+ retry_budget_seconds=120,
+ retry_after_max_seconds=60,
+ )
+ pages = cast(
+ "Generator[list[Any]]",
+ client.paginate(
+ path="oauth/token",
+ method="POST",
+ json={"client_id": app_key, "client_secret": api_secret, "grant_type": "client_credentials"},
+ paginator=SinglePagePaginator(),
+ data_selector="$",
+ ),
+ )
+ try:
+ rows = next(pages, [])
+ payload = rows[0] if rows else None
+ except HTTPError as error:
+ if error.response is not None and error.response.status_code in (400, 401, 403):
+ raise YotpoAuthenticationError("Yotpo rejected the app key or API secret.") from None
+ raise
+ finally:
+ pages.close()
+ token = payload.get("access_token") if isinstance(payload, dict) else None
+ if not isinstance(token, str) or not token:
+ raise YotpoAuthenticationError("Yotpo did not return an access token.")
+ return token
+
+
+def get_endpoint(endpoint: str, app_key: str, token: str, start_date: str, until: str) -> Endpoint:
+ settings = schema_for_resource(ENDPOINTS, endpoint)
+ params: dict[str, Any] = dict(settings.params)
+ if settings.page_size_param:
+ params[settings.page_size_param] = 100
+ if settings.email_date_range:
+ validate_start_date(start_date)
+ params.update(since=start_date, until=until)
+ if settings.token_query_param:
+ params[settings.token_query_param] = token
+ return {
+ "path": settings.path.format(app_key=quote(app_key, safe="")),
+ "data_selector": settings.data_selector,
+ "data_selector_required": True,
+ "params": params,
+ "paginator": PageNumberPaginator(base_page=1) if settings.page_size_param else "single_page",
+ }
+
+
+def validate_credentials(app_key: str, api_secret: str, start_date: str, schema_name: str | None) -> None:
+ endpoint = schema_name or "reviews"
+ schema_for_resource(ENDPOINTS, endpoint)
+ token = get_access_token(app_key, api_secret)
+ probe = get_endpoint(endpoint, app_key, token, start_date, datetime.now(UTC).date().isoformat())
+ size_param = ENDPOINTS[endpoint].page_size_param
+ params = probe["params"]
+ if size_param and params is not None:
+ params[size_param] = 1
+ resource = rest_api_resource(
+ {
+ "client": {
+ "base_url": BASE_URL,
+ "auth": {"type": "api_key", "name": "X-Yotpo-Token", "api_key": token, "location": "header"},
+ "allowed_hosts": [],
+ "allow_redirects": False,
+ "request_timeout": REQUEST_TIMEOUT,
+ "retry_budget_seconds": 60,
+ "retry_after_max_seconds": 30,
+ },
+ "resources": [{"name": endpoint, "endpoint": {**probe, "paginator": "single_page"}}],
+ },
+ team_id=0,
+ job_id="credential-validation",
+ db_incremental_field_last_value=None,
+ )
+ list(resource)
+
+
+def yotpo_source(
+ app_key: str,
+ api_secret: str,
+ start_date: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[YotpoResumeConfig],
+) -> SourceResponse:
+ settings = schema_for_resource(ENDPOINTS, endpoint)
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ until = resume.until if resume and resume.until else datetime.now(UTC).date().isoformat()
+ token = get_access_token(app_key, api_secret)
+ config: RESTAPIConfig = {
+ "client": {
+ "base_url": BASE_URL,
+ "auth": {"type": "api_key", "name": "X-Yotpo-Token", "api_key": token, "location": "header"},
+ "allowed_hosts": [],
+ "allow_redirects": False,
+ "request_timeout": REQUEST_TIMEOUT,
+ "retry_budget_seconds": 120,
+ "retry_after_max_seconds": 60,
+ },
+ "resources": [
+ {
+ "name": endpoint,
+ "write_disposition": "replace",
+ "endpoint": get_endpoint(endpoint, app_key, token, start_date, until),
+ }
+ ],
+ }
+
+ def save_checkpoint(state: dict[str, Any] | None) -> None:
+ if state is not None:
+ resumable_source_manager.save_state(YotpoResumeConfig(page=int(state["page"]), until=until))
+
+ resource = rest_api_resource(
+ config,
+ team_id=team_id,
+ job_id=job_id,
+ db_incremental_field_last_value=None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state={"page": resume.page} if resume else None,
+ )
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: resource,
+ primary_keys=list(settings.primary_keys) if settings.primary_keys else None,
+ partition_keys=[settings.partition_key] if settings.partition_key else None,
+ partition_mode="datetime" if settings.partition_key else None,
+ partition_format="month" if settings.partition_key else None,
+ sort_mode=None,
+ supports_resume=settings.page_size_param is not None,
+ )