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 wix import source (#108027)

Tom Owers61578c9950c6
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 06c85657b553..67fea5e3686d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -764,6 +764,7 @@ the row lists both.
| whop | HTTP + Webhook | requests + `rest_source.RESTClient` + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |
| wikipedia_pageviews | HTTP | requests | ✅ |
| windmill | HTTP | requests | ✅ |
+| wix | HTTP | requests | ✅ |
| woocommerce | HTTP + Webhook | requests + `rest_source.RESTClient` + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |
| wordpress | HTTP | requests | ✅ |
| workable | HTTP | requests | ✅ |
@@ -1485,7 +1486,6 @@ doesn't conflict with concurrent PRs.
- wikipedia_pageviews
- windsor_ai
- wisprflow
-- wix
- wiz
- wompi
- workato
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/wix.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/wix.py
index 569c9bea6131..85bf430bcbcb 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/wix.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/wix.py
@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class WixSourceConfig(config.Config):
- pass
+ api_key: str
+ site_id: str
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/wix/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/wix/canonical_descriptions.py
new file mode 100644
index 000000000000..2f90f7bae1e6
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/wix/canonical_descriptions.py
@@ -0,0 +1,87 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "orders": {
+ "description": "An eCommerce order placed on the site, with its buyer, line items, totals, and payment and fulfillment state.",
+ "docs_url": "https://dev.wix.com/docs/rest/business-solutions/e-commerce/orders/orders/order-object",
+ "columns": {
+ "id": "Unique identifier for the order.",
+ "number": "Running order number shown to the buyer and the site owner.",
+ "createdDate": "Date and time the order was created.",
+ "updatedDate": "Date and time the order was last updated.",
+ "status": "Order status: INITIALIZED, APPROVED, CANCELED, PENDING, or REJECTED.",
+ "paymentStatus": "Payment state of the order, such as PAID, NOT_PAID, or FULLY_REFUNDED.",
+ "fulfillmentStatus": "Fulfillment state of the order: NOT_FULFILLED, FULFILLED, or PARTIALLY_FULFILLED.",
+ "buyerInfo": "Identity of the buyer, including the contact and member IDs where known.",
+ "lineItems": "Items purchased in the order, each with quantity, price, and catalog reference.",
+ "priceSummary": "Order totals, broken into subtotal, shipping, tax, discount, and total.",
+ "currency": "Currency the order was placed in, as a three-letter code.",
+ "channelInfo": "Sales channel the order came through, such as the web store or a point of sale.",
+ },
+ },
+ "products": {
+ "description": "A product in the Wix Stores catalog, with its media, options, and pricing.",
+ "docs_url": "https://dev.wix.com/docs/rest/business-solutions/stores/catalog-v3/products-v3/product-object",
+ "columns": {
+ "id": "Unique identifier for the product.",
+ "name": "Product name shown to shoppers.",
+ "slug": "URL-friendly version of the product name.",
+ "visible": "Whether the product is visible in the storefront.",
+ "createdDate": "Date and time the product was created.",
+ "updatedDate": "Date and time the product was last updated.",
+ "productType": "Product type, such as PHYSICAL or DIGITAL.",
+ "brand": "Brand assigned to the product.",
+ "media": "Images and videos attached to the product.",
+ "options": "Product options, such as size or color, that generate variants.",
+ },
+ },
+ "contacts": {
+ "description": "A contact in the site's CRM, collected from forms, orders, or manual entry.",
+ "docs_url": "https://dev.wix.com/docs/rest/crm/members-contacts/contacts/contacts/contact-v4/contact-object",
+ "columns": {
+ "id": "Unique identifier for the contact.",
+ "revision": "Revision number, incremented each time the contact is updated.",
+ "createdDate": "Date and time the contact was created.",
+ "updatedDate": "Date and time the contact was last updated.",
+ "primaryInfo": "The contact's primary email and phone number.",
+ "info": "Contact details, including name, emails, phones, addresses, and labels.",
+ "lastActivity": "The contact's most recent activity on the site, with its type and date.",
+ "source": "How the contact was added, such as a form submission or an order.",
+ },
+ },
+ "members": {
+ "description": "A site member, meaning a contact who has signed up for an account on the site.",
+ "docs_url": "https://dev.wix.com/docs/rest/crm/members-contacts/members/members/member-object",
+ "columns": {
+ "id": "Unique identifier for the member.",
+ "contactId": "ID of the contact this member is linked to.",
+ "loginEmail": "Email address the member signs in with.",
+ "loginEmailVerified": "Whether the member has verified their login email.",
+ "status": "Member status, such as APPROVED, PENDING, or BLOCKED.",
+ "createdDate": "Date and time the member signed up.",
+ "updatedDate": "Date and time the member record was last updated.",
+ "lastLoginDate": "Date and time the member last signed in.",
+ "profile": "The member's public profile, including nickname and photo.",
+ "privacyStatus": "Whether the member's profile is PUBLIC or PRIVATE.",
+ },
+ },
+ "blog_posts": {
+ "description": "A post on the site's blog, with its author, categories, and engagement counters.",
+ "docs_url": "https://dev.wix.com/docs/rest/business-solutions/blog/posts/post-object",
+ "columns": {
+ "id": "Unique identifier for the post.",
+ "title": "Post title.",
+ "slug": "URL-friendly version of the post title.",
+ "memberId": "ID of the site member who wrote the post.",
+ "firstPublishedDate": "Date and time the post was first published.",
+ "lastPublishedDate": "Date and time the post was last published.",
+ "categoryIds": "IDs of the categories the post belongs to.",
+ "tagIds": "IDs of the tags applied to the post.",
+ "minutesToRead": "Estimated reading time in minutes.",
+ "pinned": "Whether the post is pinned to the top of the blog feed.",
+ "featured": "Whether the post is marked as featured.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/wix/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/wix/settings.py
new file mode 100644
index 000000000000..da2eebd363df
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/wix/settings.py
@@ -0,0 +1,100 @@
+from dataclasses import field
+from typing import Optional
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+_ORDER_INCREMENTAL_FIELDS: list[IncrementalField] = [
+ {
+ "label": "updatedDate",
+ "type": IncrementalFieldType.DateTime,
+ "field": "updatedDate",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ {
+ "label": "createdDate",
+ "type": IncrementalFieldType.DateTime,
+ "field": "createdDate",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+]
+
+
+@frozen
+class WixEndpointConfig:
+ name: str
+ path: str
+ # Wix wraps the request criteria under "search" on its search endpoints and "query" on its
+ # query endpoints, and the response carries the cursors under a matching key.
+ body_key: str
+ data_key: str
+ cursors_key: str
+ # Sort field requested on every page so paging stays stable while rows are written.
+ sort_field: str
+ # Permission a site owner grants the API key for this endpoint, quoted back when Wix returns 403.
+ permission: str
+ primary_key: str = "id"
+ partition_key: Optional[str] = None
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+
+
+WIX_ENDPOINTS: dict[str, WixEndpointConfig] = {
+ "orders": WixEndpointConfig(
+ name="orders",
+ path="/ecom/v1/orders/search",
+ body_key="search",
+ data_key="orders",
+ cursors_key="metadata",
+ sort_field="createdDate",
+ permission="Read eCommerce Orders",
+ partition_key="createdDate",
+ incremental_fields=list(_ORDER_INCREMENTAL_FIELDS),
+ ),
+ "products": WixEndpointConfig(
+ name="products",
+ path="/stores/v3/products/search",
+ body_key="search",
+ data_key="products",
+ cursors_key="pagingMetadata",
+ sort_field="createdDate",
+ permission="Read Stores - all read permissions",
+ partition_key="createdDate",
+ ),
+ "contacts": WixEndpointConfig(
+ name="contacts",
+ path="/contacts/v4/contacts/query",
+ body_key="query",
+ data_key="contacts",
+ cursors_key="pagingMetadata",
+ sort_field="createdDate",
+ permission="Read Contacts",
+ partition_key="createdDate",
+ ),
+ "members": WixEndpointConfig(
+ name="members",
+ path="/members/v1/members/query",
+ body_key="query",
+ data_key="members",
+ cursors_key="pagingMetadata",
+ sort_field="createdDate",
+ permission="Read Members",
+ partition_key="createdDate",
+ ),
+ "blog_posts": WixEndpointConfig(
+ name="blog_posts",
+ path="/blog/v3/posts/query",
+ body_key="query",
+ data_key="posts",
+ cursors_key="pagingMetadata",
+ sort_field="firstPublishedDate",
+ permission="Read Blog",
+ partition_key="firstPublishedDate",
+ ),
+}
+
+ENDPOINTS = tuple(WIX_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in WIX_ENDPOINTS.items() if config.incremental_fields
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/wix/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/wix/source.py
index aa3af47fa1e6..ef2bdf2393da 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/wix/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/wix/source.py
@@ -1,25 +1,145 @@
-from typing import cast
+from typing import Optional, 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 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.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (
+ SourceSchema,
+ build_endpoint_schemas,
+)
+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.wix import WixSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.wix.settings import ENDPOINTS, INCREMENTAL_FIELDS
+from products.warehouse_sources.backend.temporal.data_imports.sources.wix.wix import (
+ WixResumeConfig,
+ check_endpoint_permissions,
+ validate_credentials as validate_wix_credentials,
+ wix_source,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class WixSource(SimpleSource[WixSourceConfig]):
+class WixSource(ResumableSource[WixSourceConfig, WixResumeConfig]):
+ # Wix versions each API family in its path rather than the account as a whole, so there is no
+ # single account-wide version to pin.
+ api_docs_url = "https://dev.wix.com/docs/rest/api-reference"
+
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.WIX
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://www.wixapis.com": "Wix rejected this API key. Create a new key in the Wix API Key Manager and reconnect the source.",
+ "403 Client Error: Forbidden for url: https://www.wixapis.com": "This API key is missing a permission for this table. Grant it in the Wix API Key Manager and reconnect the source.",
+ "428 Client Error": "Wix could not find this site. Check the site ID matches the site you want to sync.",
+ }
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=ExternalDataSourceType.WIX,
category=DataWarehouseSourceCategory.E_COMMERCE,
label="Wix",
+ caption="""Enter a Wix API key and the ID of the site you want to sync, to pull your orders, products, contacts, members, and blog posts into the PostHog Data warehouse.
+
+Create an API key in the [Wix API Key Manager](https://manage.wix.com/account/api-keys) and give it read access to the areas you want to sync: eCommerce Orders, Stores, Contacts, Members, and Blog. Only an account owner or a co-owner with full permissions can create one.
+
+Find the site ID in the Wix dashboard URL for your site, in the part after `/dashboard/`. A key that is missing a permission still connects, and the table picker marks the tables it cannot read.""",
iconPath="/static/services/wix.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/wix",
+ keywords=["wix", "website builder", "ecommerce"],
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ caption="Create this in the Wix API Key Manager under your account settings.",
+ ),
+ SourceFieldInputConfig(
+ name="site_id",
+ label="Site ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="12345678-1234-1234-1234-123456789012",
+ secret=False,
+ caption="The site's ID, shown in your Wix dashboard URL after `/dashboard/`.",
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.wix.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: WixSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+
+ def validate_credentials(
+ self,
+ config: WixSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ return validate_wix_credentials(config.api_key, config.site_id)
+
+ def get_endpoint_permissions(
+ self, config: WixSourceConfig, team_id: int, endpoints: list[str], api_version: str | None = None
+ ) -> dict[str, str | None]:
+ return check_endpoint_permissions(config.api_key, config.site_id, endpoints)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[WixResumeConfig]:
+ return ResumableSourceManager[WixResumeConfig](inputs, WixResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: WixSourceConfig,
+ resumable_source_manager: ResumableSourceManager[WixResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ if inputs.schema_name not in ENDPOINTS:
+ raise ValueError(f"Unknown Wix endpoint: {inputs.schema_name}")
+
+ return wix_source(
+ api_key=config.api_key,
+ site_id=config.site_id,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ incremental_field=inputs.incremental_field if inputs.should_use_incremental_field else None,
+ 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/wix/tests/test_wix.py b/products/warehouse_sources/backend/temporal/data_imports/sources/wix/tests/test_wix.py
new file mode 100644
index 000000000000..1d743fafdd18
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/wix/tests/test_wix.py
@@ -0,0 +1,243 @@
+from datetime import UTC, datetime
+from typing import Any, Optional
+
+import pytest
+from unittest import mock
+
+import requests
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.wix.settings import WIX_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.wix.wix import (
+ PAGE_SIZE,
+ WixResumeConfig,
+ _to_wix_datetime,
+ check_endpoint_permissions,
+ get_rows,
+ validate_credentials,
+)
+
+_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.wix.wix"
+
+
+def _manager(resume_state: WixResumeConfig | 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 _response(
+ status_code: int = 200,
+ payload: Optional[dict[str, Any]] = None,
+) -> mock.MagicMock:
+ response = mock.MagicMock()
+ response.status_code = status_code
+ response.ok = status_code < 400
+ response.json.return_value = payload or {}
+ response.text = ""
+ if status_code >= 400:
+ error = requests.HTTPError(f"{status_code} Client Error", response=response)
+ response.raise_for_status.side_effect = error
+ return response
+
+
+def _page(items: list[dict[str, Any]], data_key: str, cursors_key: str, next_cursor: str | None) -> dict[str, Any]:
+ return {
+ data_key: items,
+ cursors_key: {"cursors": {"next": next_cursor}, "hasNext": next_cursor is not None},
+ }
+
+
+class TestWixTransport:
+ def test_walks_cursor_pages_until_the_api_stops_returning_one(self) -> None:
+ session = mock.MagicMock()
+ session.post.side_effect = [
+ _response(payload=_page([{"id": "1"}], "orders", "metadata", "cursor-2")),
+ _response(payload=_page([{"id": "2"}], "orders", "metadata", None)),
+ ]
+ manager = _manager()
+
+ with mock.patch(f"{_MODULE}._get_session", return_value=session):
+ batches = list(get_rows("key", "site", "orders", mock.MagicMock(), manager))
+
+ assert batches == [[{"id": "1"}], [{"id": "2"}]]
+ assert session.post.call_count == 2
+
+ def test_repeated_cursor_raises_instead_of_paging_forever(self) -> None:
+ session = mock.MagicMock()
+ session.post.side_effect = [
+ _response(payload=_page([{"id": "1"}], "orders", "metadata", "cursor-2")),
+ _response(payload=_page([{"id": "2"}], "orders", "metadata", "cursor-2")),
+ ]
+
+ with mock.patch(f"{_MODULE}._get_session", return_value=session):
+ with pytest.raises(RuntimeError, match="repeated cursor"):
+ list(get_rows("key", "site", "orders", mock.MagicMock(), _manager()))
+
+ assert session.post.call_count == 2
+
+ def test_follow_up_pages_send_the_cursor_without_filter_or_sort(self) -> None:
+ # Wix encodes the filter and sort into the cursor and rejects a request that repeats them.
+ session = mock.MagicMock()
+ session.post.side_effect = [
+ _response(payload=_page([{"id": "1"}], "orders", "metadata", "cursor-2")),
+ _response(payload=_page([{"id": "2"}], "orders", "metadata", None)),
+ ]
+
+ with mock.patch(f"{_MODULE}._get_session", return_value=session):
+ list(get_rows("key", "site", "orders", mock.MagicMock(), _manager()))
+
+ second_body = session.post.call_args_list[1].kwargs["json"]["search"]
+ assert second_body == {"cursorPaging": {"limit": PAGE_SIZE, "cursor": "cursor-2"}}
+
+ def test_incremental_run_filters_and_sorts_on_the_chosen_field(self) -> None:
+ session = mock.MagicMock()
+ session.post.return_value = _response(payload=_page([], "orders", "metadata", None))
+
+ with mock.patch(f"{_MODULE}._get_session", return_value=session):
+ list(
+ get_rows(
+ "key",
+ "site",
+ "orders",
+ mock.MagicMock(),
+ _manager(),
+ incremental_field="updatedDate",
+ db_incremental_field_last_value=datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC),
+ )
+ )
+
+ body = session.post.call_args.kwargs["json"]["search"]
+ assert body["filter"] == {"updatedDate": {"$gte": "2026-01-02T03:04:05Z"}}
+ assert body["sort"] == [{"fieldName": "updatedDate", "order": "ASC"}]
+
+ def test_full_refresh_run_sends_no_watermark_filter(self) -> None:
+ session = mock.MagicMock()
+ session.post.return_value = _response(payload=_page([], "orders", "metadata", None))
+
+ with mock.patch(f"{_MODULE}._get_session", return_value=session):
+ list(get_rows("key", "site", "orders", mock.MagicMock(), _manager()))
+
+ body = session.post.call_args.kwargs["json"]["search"]
+ assert "filter" not in body
+ assert body["sort"] == [{"fieldName": "createdDate", "order": "ASC"}]
+
+ def test_resumes_from_the_saved_cursor(self) -> None:
+ session = mock.MagicMock()
+ session.post.return_value = _response(payload=_page([{"id": "9"}], "orders", "metadata", None))
+
+ with mock.patch(f"{_MODULE}._get_session", return_value=session):
+ list(get_rows("key", "site", "orders", mock.MagicMock(), _manager(WixResumeConfig(cursor="saved"))))
+
+ body = session.post.call_args.kwargs["json"]["search"]
+ assert body["cursorPaging"]["cursor"] == "saved"
+
+ def test_expired_resume_cursor_restarts_the_stream(self) -> None:
+ # Wix cursors are time-limited, so a resumed run can open with one the API no longer accepts.
+ session = mock.MagicMock()
+ session.post.side_effect = [
+ _response(status_code=400),
+ _response(payload=_page([{"id": "1"}], "orders", "metadata", None)),
+ ]
+
+ with mock.patch(f"{_MODULE}._get_session", return_value=session):
+ batches = list(get_rows("key", "site", "orders", mock.MagicMock(), _manager(WixResumeConfig("stale"))))
+
+ assert batches == [[{"id": "1"}]]
+ retried_body = session.post.call_args_list[1].kwargs["json"]["search"]
+ assert "cursor" not in retried_body["cursorPaging"]
+
+ def test_a_400_on_the_first_page_is_not_swallowed(self) -> None:
+ session = mock.MagicMock()
+ response = _response(status_code=400)
+ response.text = "potentially sensitive upstream error"
+ session.post.return_value = response
+ logger = mock.MagicMock()
+
+ with mock.patch(f"{_MODULE}._get_session", return_value=session):
+ with pytest.raises(requests.HTTPError):
+ list(get_rows("key", "site", "orders", logger, _manager()))
+
+ assert "potentially sensitive upstream error" not in str(logger.error.call_args)
+
+ def test_state_is_saved_for_each_page_that_has_a_successor(self) -> None:
+ session = mock.MagicMock()
+ session.post.side_effect = [
+ _response(payload=_page([{"id": "1"}], "orders", "metadata", "cursor-2")),
+ _response(payload=_page([{"id": "2"}], "orders", "metadata", None)),
+ ]
+ manager = _manager()
+
+ with mock.patch(f"{_MODULE}._get_session", return_value=session):
+ list(get_rows("key", "site", "orders", mock.MagicMock(), manager))
+
+ assert manager.save_state.call_args_list == [mock.call(WixResumeConfig(cursor="cursor-2"))]
+
+ @pytest.mark.parametrize("endpoint", sorted(WIX_ENDPOINTS))
+ def test_every_endpoint_reads_rows_from_its_own_envelope(self, endpoint: str) -> None:
+ config = WIX_ENDPOINTS[endpoint]
+ session = mock.MagicMock()
+ session.post.return_value = _response(payload=_page([{"id": "1"}], config.data_key, config.cursors_key, None))
+
+ with mock.patch(f"{_MODULE}._get_session", return_value=session):
+ batches = list(get_rows("key", "site", endpoint, mock.MagicMock(), _manager()))
+
+ assert batches == [[{"id": "1"}]]
+ assert session.post.call_args.kwargs["json"].keys() == {config.body_key}
+
+
+class TestWixCredentials:
+ @pytest.mark.parametrize(
+ "status_code,expected_valid",
+ [(200, True), (403, True), (401, False), (428, False), (500, False)],
+ )
+ def test_status_maps_to_a_verdict(self, status_code: int, expected_valid: bool) -> None:
+ session = mock.MagicMock()
+ session.post.return_value = _response(status_code=status_code)
+
+ with mock.patch(f"{_MODULE}._get_session", return_value=session):
+ valid, message = validate_credentials("key", "site")
+
+ assert valid is expected_valid
+ assert (message is None) is expected_valid
+
+ def test_unreachable_api_is_reported_rather_than_raised(self) -> None:
+ session = mock.MagicMock()
+ session.post.side_effect = requests.ConnectionError("no route")
+
+ with mock.patch(f"{_MODULE}._get_session", return_value=session):
+ valid, message = validate_credentials("key", "site")
+
+ assert valid is False
+ assert message is not None
+
+ def test_permission_probe_names_the_missing_wix_permission(self) -> None:
+ session = mock.MagicMock()
+ session.post.side_effect = [_response(status_code=403), _response(status_code=200)]
+
+ with mock.patch(f"{_MODULE}._get_session", return_value=session):
+ results = check_endpoint_permissions("key", "site", ["orders", "contacts"])
+
+ assert results["orders"] == "This API key is missing the 'Read eCommerce Orders' permission in Wix."
+ assert results["contacts"] is None
+
+ def test_permission_probe_keeps_a_table_selectable_when_the_request_fails(self) -> None:
+ session = mock.MagicMock()
+ session.post.side_effect = requests.ConnectionError("no route")
+
+ with mock.patch(f"{_MODULE}._get_session", return_value=session):
+ assert check_endpoint_permissions("key", "site", ["orders"]) == {"orders": None}
+
+
+class TestWixTimestamps:
+ @pytest.mark.parametrize(
+ "value,expected",
+ [
+ (datetime(2026, 5, 6, 7, 8, 9, tzinfo=UTC), "2026-05-06T07:08:09Z"),
+ (datetime(2026, 5, 6, 7, 8, 9), "2026-05-06T07:08:09Z"),
+ ("2026-05-06T07:08:09Z", "2026-05-06T07:08:09Z"),
+ (None, None),
+ ],
+ )
+ def test_values_render_as_rfc_3339(self, value: Any, expected: str | None) -> None:
+ assert _to_wix_datetime(value) == expected
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/wix/tests/test_wix_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/wix/tests/test_wix_source.py
new file mode 100644
index 000000000000..d7f7fd463cf0
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/wix/tests/test_wix_source.py
@@ -0,0 +1,46 @@
+import pytest
+from unittest import mock
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.wix import WixSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.wix.source import WixSource
+
+_SOURCE = "products.warehouse_sources.backend.temporal.data_imports.sources.wix.source"
+
+
+def _config() -> WixSourceConfig:
+ return WixSourceConfig(api_key="key", site_id="site")
+
+
+class TestWixSource:
+ def test_an_unknown_schema_fails_before_any_request_goes_out(self) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "not_a_wix_table"
+
+ with pytest.raises(ValueError, match="Unknown Wix endpoint"):
+ WixSource().source_for_pipeline(_config(), mock.MagicMock(), inputs)
+
+ def test_the_users_chosen_incremental_field_reaches_the_transport(self) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "orders"
+ inputs.should_use_incremental_field = True
+ inputs.incremental_field = "updatedDate"
+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"
+
+ with mock.patch(f"{_SOURCE}.wix_source") as wix_source:
+ WixSource().source_for_pipeline(_config(), mock.MagicMock(), inputs)
+
+ assert wix_source.call_args.kwargs["incremental_field"] == "updatedDate"
+ assert wix_source.call_args.kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"
+
+ def test_a_full_refresh_run_passes_no_watermark(self) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "orders"
+ inputs.should_use_incremental_field = False
+ inputs.incremental_field = "updatedDate"
+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"
+
+ with mock.patch(f"{_SOURCE}.wix_source") as wix_source:
+ WixSource().source_for_pipeline(_config(), mock.MagicMock(), inputs)
+
+ assert wix_source.call_args.kwargs["incremental_field"] is None
+ assert wix_source.call_args.kwargs["db_incremental_field_last_value"] is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/wix/wix.py b/products/warehouse_sources/backend/temporal/data_imports/sources/wix/wix.py
new file mode 100644
index 000000000000..c2bffccbf7e7
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/wix/wix.py
@@ -0,0 +1,220 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+
+import requests
+from structlog.types import FilteringBoundLogger
+
+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.common.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.wix.settings import WIX_ENDPOINTS
+
+WIX_BASE_URL = "https://www.wixapis.com"
+PAGE_SIZE = 100
+REQUEST_TIMEOUT_SECONDS = 60
+
+
[email protected](frozen=True)
+class WixResumeConfig:
+ cursor: str
+
+
+def _get_session(api_key: str, site_id: str) -> requests.Session:
+ return make_tracked_session(
+ headers={
+ "Authorization": api_key,
+ "wix-site-id": site_id,
+ "Content-Type": "application/json",
+ },
+ redact_values=(api_key,),
+ )
+
+
+def _to_wix_datetime(value: Any) -> Optional[str]:
+ """Wix filters take RFC 3339 timestamps with a Z suffix."""
+ if isinstance(value, str):
+ return value
+ if isinstance(value, datetime):
+ stamped = value if value.tzinfo else value.replace(tzinfo=UTC)
+ return stamped.astimezone(UTC).isoformat().replace("+00:00", "Z")
+ if isinstance(value, date):
+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).isoformat().replace("+00:00", "Z")
+ return None
+
+
+def _next_cursor(payload: dict[str, Any], cursors_key: str) -> Optional[str]:
+ metadata = payload.get(cursors_key) or {}
+ if metadata.get("hasNext") is False:
+ return None
+ cursor = (metadata.get("cursors") or {}).get("next")
+ return cursor or None
+
+
+def _first_page_criteria(
+ endpoint: str,
+ incremental_field: Optional[str],
+ incremental_last_value: Any,
+) -> dict[str, Any]:
+ config = WIX_ENDPOINTS[endpoint]
+ sort_field = incremental_field or config.sort_field
+ criteria: dict[str, Any] = {
+ "cursorPaging": {"limit": PAGE_SIZE},
+ "sort": [{"fieldName": sort_field, "order": "ASC"}],
+ }
+ watermark = _to_wix_datetime(incremental_last_value) if incremental_field else None
+ if watermark is not None:
+ criteria["filter"] = {sort_field: {"$gte": watermark}}
+ return criteria
+
+
+def validate_credentials(api_key: str, site_id: str) -> tuple[bool, Optional[str]]:
+ """Probe one cheap query to tell a bad key (401) from a key missing a permission (403)."""
+ try:
+ response = _get_session(api_key, site_id).post(
+ f"{WIX_BASE_URL}/contacts/v4/contacts/query",
+ json={"query": {"cursorPaging": {"limit": 1}}},
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+ except Exception:
+ return False, "Could not reach the Wix API. Check your connection and try again."
+
+ if response.ok:
+ return True, None
+ if response.status_code == 403:
+ # The key is genuine; the site owner has not granted Contacts. Other tables may still sync,
+ # and the schema picker reports per-table permissions separately.
+ return True, None
+ if response.status_code == 401:
+ return False, "Wix rejected this API key. Check the key in the Wix API Key Manager and try again."
+ if response.status_code == 428:
+ return False, (
+ "Wix could not find this site. Check the site ID matches the site you want to sync, and that the "
+ "API key belongs to the same account."
+ )
+ return False, f"Wix returned an unexpected error ({response.status_code}) while checking these credentials."
+
+
+def check_endpoint_permissions(api_key: str, site_id: str, endpoints: list[str]) -> dict[str, Optional[str]]:
+ """Report which endpoints this API key can read, so the picker can flag the rest."""
+ session = _get_session(api_key, site_id)
+ results: dict[str, Optional[str]] = {}
+ for name in endpoints:
+ config = WIX_ENDPOINTS.get(name)
+ if config is None:
+ results[name] = None
+ continue
+ try:
+ response = session.post(
+ f"{WIX_BASE_URL}{config.path}",
+ json={config.body_key: {"cursorPaging": {"limit": 1}}},
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+ except Exception:
+ # A network blip is not a permission problem, so leave the table selectable.
+ results[name] = None
+ continue
+
+ if response.status_code == 403:
+ results[name] = f"This API key is missing the '{config.permission}' permission in Wix."
+ elif response.status_code == 404:
+ results[name] = "This app is not installed on the site."
+ else:
+ results[name] = None
+ return results
+
+
+def get_rows(
+ api_key: str,
+ site_id: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[WixResumeConfig],
+ incremental_field: Optional[str] = None,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = WIX_ENDPOINTS[endpoint]
+ session = _get_session(api_key, site_id)
+ url = f"{WIX_BASE_URL}{config.path}"
+
+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ cursor = resume_config.cursor if resume_config is not None else None
+ if cursor is not None:
+ logger.debug(f"Wix: resuming {endpoint} from a saved cursor")
+
+ def fetch(page_cursor: Optional[str]) -> dict[str, Any]:
+ if page_cursor is None:
+ criteria = _first_page_criteria(endpoint, incremental_field, db_incremental_field_last_value)
+ else:
+ # Wix encodes the filter and sort into the cursor, and rejects a request that repeats
+ # them, so a follow-up page carries the cursor alone.
+ criteria = {"cursorPaging": {"limit": PAGE_SIZE, "cursor": page_cursor}}
+ response = session.post(url, json={config.body_key: criteria}, timeout=REQUEST_TIMEOUT_SECONDS)
+ if not response.ok:
+ logger.error(f"Wix API request failed for {endpoint}: status={response.status_code}")
+ response.raise_for_status()
+ return response.json()
+
+ seen_cursors = {cursor} if cursor is not None else set()
+ while True:
+ try:
+ payload = fetch(cursor)
+ except requests.HTTPError as error:
+ response = error.response
+ if cursor is None or response is None or response.status_code != 400:
+ raise
+ # Wix cursors expire, so a resumed run can open with a cursor the API no longer accepts.
+ # Restarting the stream is safe: merge dedupes on the primary key.
+ logger.warning(f"Wix: {endpoint} cursor expired, restarting the stream from the first page")
+ cursor = None
+ seen_cursors.clear()
+ payload = fetch(None)
+
+ items = payload.get(config.data_key) or []
+ cursor = _next_cursor(payload, config.cursors_key)
+
+ if cursor is not None:
+ if cursor in seen_cursors:
+ raise RuntimeError(f"Wix returned a repeated cursor while paging {endpoint}")
+ seen_cursors.add(cursor)
+ resumable_source_manager.save_state(WixResumeConfig(cursor=cursor))
+
+ if items:
+ yield items
+
+ if cursor is None or not items:
+ break
+
+
+def wix_source(
+ api_key: str,
+ site_id: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[WixResumeConfig],
+ incremental_field: Optional[str] = None,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = WIX_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ site_id=site_id,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ incremental_field=incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ primary_keys=[config.primary_key],
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ # Every page is requested with an ascending sort on the cursor field.
+ sort_mode="asc",
+ )