: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 the clover import source (#115485)
Tom Owersa4b75542deb8
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 678a4f2880cc..1355d0c88a3d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -209,6 +209,7 @@ the row lists both.| cloudability | HTTP | requests + `rest_source.RESTClient` | ✅ || cloudinary | HTTP | requests + `rest_source.RESTClient` | ✅ || cloudzero | HTTP | requests + `rest_source.RESTClient` | ✅ |+| clover | HTTP | requests + `rest_source.RESTClient` | ✅ || coassemble | HTTP | requests | ✅ || coda | HTTP | requests | ✅ || codacy | HTTP | requests | ✅ |@@ -1064,7 +1065,6 @@ doesn't conflict with concurrent PRs.- clevertap- clio- cloudbeds-- clover- coassemble- cockroachdb- codacydiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clover/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clover/canonical_descriptions.pynew file mode 100644index 000000000000..ffc0112c85b8--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clover/canonical_descriptions.py@@ -0,0 +1,226 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_DOCS = "https://docs.clover.com/dev/reference/api-reference-overview"++# Clover timestamps are epoch milliseconds throughout, and money amounts are integers in the+# merchant's smallest currency unit (cents for USD).+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "orders": {+ "description": "Orders rung up on the merchant's Clover devices, with amounts and payment states.",+ "docs_url": _DOCS,+ "columns": {+ "id": "Unique identifier for the order.",+ "currency": "ISO 4217 currency the order was priced in.",+ "total": "Order total in the smallest currency unit, including tax and service charge.",+ "state": "Order state, such as open or locked.",+ "title": "Optional label given to the order.",+ "note": "Free-text note attached to the order.",+ "taxRemoved": "Whether tax was removed from the order.",+ "isVat": "Whether the order was priced with VAT-inclusive tax.",+ "testMode": "Whether the order was created in test mode rather than by a real sale.",+ "createdTime": "When the order was created on Clover's servers, in epoch milliseconds.",+ "clientCreatedTime": "When the device created the order, in epoch milliseconds.",+ "modifiedTime": "When the order was last changed, in epoch milliseconds.",+ "employee": "Reference to the employee who took the order.",+ "device": "Reference to the device the order was created on.",+ "customers": "Customers associated with the order.",+ "created_at": "Order creation time in UTC, converted from createdTime.",+ "payments": "Payments applied to the order.",+ },+ },+ "line_items": {+ "description": "Individual items on each order.",+ "docs_url": "https://docs.clover.com/dev/reference/ordergetorderlineitems",+ "columns": {+ "id": "Line item identifier within the order.",+ "order_id": "Identifier of the order that contains this line item.",+ "order_created_time": "Order creation time in epoch milliseconds.",+ "created_at": "Order creation time in UTC.",+ "name": "Line item name.",+ "price": "Price in the smallest currency unit.",+ },+ },+ "payments": {+ "description": "Payments taken against orders, one row per tender attempt.",+ "docs_url": _DOCS,+ "columns": {+ "id": "Unique identifier for the payment.",+ "order": "Reference to the order the payment was applied to.",+ "device": "Reference to the device that took the payment.",+ "tender": "Reference to the tender type used, such as credit card or cash.",+ "amount": "Amount paid in the smallest currency unit.",+ "tipAmount": "Tip included in the payment, in the smallest currency unit.",+ "taxAmount": "Tax included in the payment, in the smallest currency unit.",+ "cashbackAmount": "Cash back given with the payment, in the smallest currency unit.",+ "cashTendered": "Cash handed over by the customer, in the smallest currency unit.",+ "externalPaymentId": "Identifier supplied by the integration that created the payment.",+ "employee": "Reference to the employee who took the payment.",+ "result": "Outcome of the payment, such as SUCCESS or FAIL.",+ "offline": "Whether the payment was captured while the device was offline.",+ "createdTime": "When the payment was recorded, in epoch milliseconds.",+ "clientCreatedTime": "When the device recorded the payment, in epoch milliseconds.",+ "modifiedTime": "When the payment was last changed, in epoch milliseconds.",+ },+ },+ "refunds": {+ "description": "Refunds issued against payments.",+ "docs_url": _DOCS,+ "columns": {+ "id": "Unique identifier for the refund.",+ "orderRef": "Reference to the order being refunded.",+ "payment": "Reference to the payment being refunded.",+ "device": "Reference to the device the refund was issued on.",+ "amount": "Amount refunded in the smallest currency unit.",+ "taxAmount": "Tax portion of the refund, in the smallest currency unit.",+ "serviceCharge": "Service charge returned with the refund.",+ "transactionInfo": "Processor details for the refund transaction.",+ "createdTime": "When the refund was issued, in epoch milliseconds.",+ },+ },+ "credit_refunds": {+ "description": "Credit refunds recorded by the merchant.",+ "docs_url": "https://docs.clover.com/dev/reference/paygetcreditrefunds-3",+ "columns": {+ "id": "Credit refund identifier.",+ "orderRef": "Reference to the associated order.",+ "device": "Reference to the device that recorded the refund.",+ "tender": "Reference to the payment method.",+ "amount": "Refund amount in the smallest currency unit.",+ "taxAmount": "Refund tax amount in the smallest currency unit.",+ "employee": "Reference to the employee who recorded the refund.",+ "createdTime": "Time recorded on the server, in epoch milliseconds.",+ "clientCreatedTime": "Time recorded on the device, in epoch milliseconds.",+ },+ },+ "items": {+ "description": "Inventory items the merchant sells.",+ "docs_url": _DOCS,+ "columns": {+ "id": "Unique identifier for the item.",+ "name": "Item name shown on the register.",+ "alternateName": "Secondary name, often used for a second language.",+ "code": "Merchant-defined product code.",+ "sku": "Stock keeping unit.",+ "price": "Item price in the smallest currency unit.",+ "priceType": "How the price is calculated, such as FIXED, VARIABLE or PER_UNIT.",+ "unitName": "Unit the item is sold by when priced per unit.",+ "cost": "Cost of goods for the item, in the smallest currency unit.",+ "isRevenue": "Whether sales of the item count toward revenue.",+ "hidden": "Whether the item is hidden from the register.",+ "stockCount": "Current tracked stock level.",+ "defaultTaxRates": "Whether the merchant's default tax rates apply to the item.",+ "modifiedTime": "When the item was last changed, in epoch milliseconds.",+ },+ },+ "categories": {+ "description": "Categories used to group inventory items on the register.",+ "docs_url": _DOCS,+ "columns": {+ "id": "Unique identifier for the category.",+ "name": "Category name.",+ "sortOrder": "Position of the category in the register layout.",+ },+ },+ "modifier_groups": {+ "description": "Groups of modifiers (such as toppings or sizes) that can be applied to items.",+ "docs_url": _DOCS,+ "columns": {+ "id": "Unique identifier for the modifier group.",+ "name": "Modifier group name.",+ "showByDefault": "Whether the group is shown automatically when the item is added.",+ "sortOrder": "Position of the group in the register layout.",+ "minRequired": "Minimum number of modifiers the customer must choose.",+ "maxAllowed": "Maximum number of modifiers the customer may choose.",+ },+ },+ "modifiers": {+ "description": "Options that change an inventory item's price or preparation.",+ "docs_url": "https://docs.clover.com/dev/reference/modifiergetmodifiers",+ "columns": {+ "id": "Modifier identifier.",+ "name": "Modifier name.",+ "price": "Additional cost in the smallest currency unit.",+ "modifierGroup": "Reference to the group that contains this modifier.",+ },+ },+ "customers": {+ "description": "Customer records saved on the merchant account.",+ "docs_url": _DOCS,+ "columns": {+ "id": "Unique identifier for the customer.",+ "firstName": "Customer's first name.",+ "lastName": "Customer's last name.",+ "marketingAllowed": "Whether the customer opted in to marketing.",+ "customerSince": "When the customer record was created, in epoch milliseconds.",+ "emailAddresses": "Email addresses on file for the customer.",+ "phoneNumbers": "Phone numbers on file for the customer.",+ "addresses": "Postal addresses on file for the customer.",+ "metadata": "Additional customer details such as business name and notes.",+ },+ },+ "employees": {+ "description": "Employees who can sign in to the merchant's Clover devices.",+ "docs_url": _DOCS,+ "columns": {+ "id": "Unique identifier for the employee.",+ "name": "Employee's full name.",+ "nickname": "Short name shown on the register.",+ "customId": "Merchant-defined employee identifier.",+ "email": "Employee's email address.",+ "role": "Permission role, such as ADMIN, MANAGER or EMPLOYEE.",+ "isOwner": "Whether the employee owns the merchant account.",+ "inviteSent": "Whether an account invitation has been sent.",+ },+ },+ "shifts": {+ "description": "Clock-in and clock-out shifts recorded by employees.",+ "docs_url": _DOCS,+ "columns": {+ "id": "Unique identifier for the shift.",+ "employee": "Reference to the employee who worked the shift.",+ "inTime": "Clock-in time, in epoch milliseconds.",+ "outTime": "Clock-out time, in epoch milliseconds; absent while the shift is open.",+ "cashierRole": "Role the employee worked the shift under.",+ "overrideInEmployee": "Employee who adjusted the clock-in time, when it was overridden.",+ "overrideOutEmployee": "Employee who adjusted the clock-out time, when it was overridden.",+ },+ },+ "tenders": {+ "description": "Tender types the merchant accepts, such as cash, credit or a custom tender.",+ "docs_url": _DOCS,+ "columns": {+ "id": "Unique identifier for the tender.",+ "label": "Tender name shown on the register.",+ "labelKey": "Stable key identifying built-in tenders.",+ "enabled": "Whether the tender can be used.",+ "visible": "Whether the tender is shown on the register.",+ "editable": "Whether the merchant can edit the tender.",+ "opensCashDrawer": "Whether taking this tender opens the cash drawer.",+ "supportsTipping": "Whether tips can be added to this tender.",+ "instructions": "Instructions shown to the cashier for this tender.",+ },+ },+ "discounts": {+ "description": "Discounts configured on the merchant account and available at the register.",+ "docs_url": _DOCS,+ "columns": {+ "id": "Unique identifier for the discount.",+ "name": "Discount name.",+ "amount": "Fixed discount amount in the smallest currency unit, when the discount is a flat amount.",+ "percentage": "Discount percentage, when the discount is proportional.",+ },+ },+ "tax_rates": {+ "description": "Tax rates the merchant applies to items and orders.",+ "docs_url": _DOCS,+ "columns": {+ "id": "Unique identifier for the tax rate.",+ "name": "Tax rate name.",+ "rate": "Tax rate expressed in millionths of a percent.",+ "taxAmount": "Flat tax amount, for per-item flat taxes.",+ "isDefault": "Whether the rate is applied to new items by default.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clover/clover.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clover/clover.pynew file mode 100644index 000000000000..f7a53fdcdcea--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clover/clover.py@@ -0,0 +1,338 @@+import re+import dataclasses+from collections.abc import Iterator+from datetime import UTC, datetime+from typing import Any++from requests import Session+from requests.exceptions import RequestException++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.clover.settings import (+ CLOVER_ENDPOINTS,+ CLOVER_REGION_HOSTS,+ FILTER_WINDOW_MS,+ CloverEndpointConfig,+)+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,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import AuthConfigBase+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ build_dependent_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ ClientConfig,+ Endpoint,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse++MERCHANT_ID_PATTERN = re.compile(r"[A-Za-z0-9]+")+CONNECT_TIMEOUT_SECONDS = 10+READ_TIMEOUT_SECONDS = 120+PROBE_READ_TIMEOUT_SECONDS = 15+REQUEST_HEADERS = {"Accept": "application/json", "User-Agent": "PostHog/1.0"}+++@frozen+class CloverResumeConfig:+ paginator_state: dict[str, Any]+++def base_url(region: str) -> str:+ host = CLOVER_REGION_HOSTS.get(region)+ if host is None:+ raise ValueError(f"Unknown Clover region: {region}")+ return host+++def _now_ms() -> int:+ return round(datetime.now(tz=UTC).timestamp() * 1000)+++def _tracked_session(auth: AuthConfigBase) -> Session:+ # Customer names and payment details must stay out of response samples.+ return make_tracked_session(redact_values=auth.secret_values(), capture=False)+++def _merchant_path(merchant_id: str, path: str, api_version: str) -> str:+ if not MERCHANT_ID_PATTERN.fullmatch(merchant_id):+ raise ValueError("Clover merchant ID must be alphanumeric")+ if api_version != "v3":+ raise ValueError(f"Unsupported Clover API version: {api_version}")+ return f"/{api_version}/merchants/{merchant_id}/{path}".rstrip("/")+++def validate_credentials(+ region: str,+ merchant_id: str,+ auth: AuthConfigBase,+ api_version: str,+ schema_name: str | None = None,+) -> tuple[bool, str | None]:+ config = CLOVER_ENDPOINTS.get(schema_name) if schema_name is not None else None+ if schema_name is not None and config is None:+ return False, "Unknown Clover table. Select a supported table."+ if config is not None and config.fanout is not None:+ config = CLOVER_ENDPOINTS[config.fanout.parent_name]+ try:+ url = base_url(region) + _merchant_path(merchant_id, config.path if config else "", api_version)+ except ValueError as error:+ return False, str(error)++ try:+ with _tracked_session(auth) as session:+ response = session.get(+ url,+ params={"limit": 1} if config else None,+ headers=REQUEST_HEADERS,+ auth=auth,+ allow_redirects=False,+ timeout=(CONNECT_TIMEOUT_SECONDS, PROBE_READ_TIMEOUT_SECONDS),+ )+ except RequestException:+ return False, "Could not connect to Clover. Try again."++ if response.status_code == 401:+ return False, "Clover rejected your credentials. Update the API token."+ if response.status_code == 403:+ if schema_name is None:+ return True, None+ assert config is not None+ return False, f"Clover requires the '{config.permission}' permission. Grant it and try again."+ if response.status_code == 404:+ return False, "Clover could not find this merchant or table. Check the merchant ID and region."+ if response.status_code != 200:+ return False, f"Clover returned HTTP {response.status_code}. Check your connection and try again."+ return True, None+++def endpoint_permissions(+ region: str,+ merchant_id: str,+ endpoints: list[str],+ auth: AuthConfigBase,+ api_version: str,+) -> dict[str, str | None]:+ host = base_url(region)+ results: dict[str, str | None] = {}+ with _tracked_session(auth) as session:+ for name in endpoints:+ config = CLOVER_ENDPOINTS.get(name)+ if config is None:+ results[name] = None+ continue+ probe = CLOVER_ENDPOINTS[config.fanout.parent_name] if config.fanout else config+ try:+ response = session.get(+ host + _merchant_path(merchant_id, probe.path, api_version),+ params={"limit": 1},+ headers=REQUEST_HEADERS,+ auth=auth,+ allow_redirects=False,+ timeout=(CONNECT_TIMEOUT_SECONDS, PROBE_READ_TIMEOUT_SECONDS),+ )+ except RequestException:+ results[name] = None+ continue+ results[name] = (+ f"Clover requires the '{config.permission}' permission. Grant it and try again."+ if response.status_code in (401, 403)+ else None+ )+ return results+++def _endpoint(config: CloverEndpointConfig, path: str) -> Endpoint:+ return {+ "path": path,+ "params": dict(config.params),+ "paginator": {"type": "offset", "limit": config.page_size, "total_path": None},+ "data_selector": "elements",+ "data_selector_required": True,+ }+++def _normalize_row(row: dict[str, Any], config: CloverEndpointConfig, window: tuple[int, int] | None) -> dict[str, Any]:+ if config.partition_field is not None:+ value = row.get(config.partition_field)+ if value is None and window is not None:+ raise ValueError(f"Clover returned no {config.partition_field} timestamp for a history window")+ if value is not None:+ if not isinstance(value, int) or isinstance(value, bool):+ raise ValueError(f"Clover returned an invalid {config.partition_field} timestamp")+ if window is not None and not window[0] <= value <= window[1]:+ raise ValueError("Clover returned a row outside the requested history window")+ row["created_at"] = datetime.fromtimestamp(value / 1000, tz=UTC)+ return row+++def clover_source(+ region: str,+ merchant_id: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[CloverResumeConfig],+ auth: AuthConfigBase,+ api_version: str,+ should_use_incremental_field: bool = False,+) -> SourceResponse:+ if should_use_incremental_field:+ raise ValueError("Clover supports full refresh only. Change the table sync mode to full refresh.")+ config = CLOVER_ENDPOINTS[endpoint]+ host = base_url(region)+ path = _merchant_path(merchant_id, config.path, api_version)+ parent = CLOVER_ENDPOINTS[config.fanout.parent_name] if config.fanout else config++ def items() -> Iterator[list[dict[str, Any]]]:+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ state = resume.paginator_state if resume else {}+ if state.get("completed"):+ return+ end_ms = int(state.get("end_ms", _now_ms()))+ start_ms = int(state.get("window_start_ms") or 0)+ resource_state = state.get("resource_state")+ if resource_state is None and "offset" in state:+ resource_state = {"offset": state["offset"]}++ with _tracked_session(auth) as session:+ client_config: ClientConfig = {+ "base_url": host,+ "headers": REQUEST_HEADERS,+ "auth": auth,+ "session": session,+ "allowed_hosts": [],+ "allow_redirects": False,+ "request_timeout": (CONNECT_TIMEOUT_SECONDS, READ_TIMEOUT_SECONDS),+ }+ first_window = True+ while start_ms <= end_ms:+ window_end = min(start_ms + FILTER_WINDOW_MS - 1, end_ms)+ window = (start_ms, window_end) if parent.history_field else None+ if not first_window:+ # Stage each later window's start before its rows, so no save has to follow a yield.+ resumable_source_manager.save_state(+ CloverResumeConfig(+ paginator_state={+ "window_start_ms": start_ms,+ "end_ms": end_ms,+ "resource_state": None,+ "completed": False,+ }+ )+ )+ params = dict(parent.params)+ if window is not None:+ # Clover can limit unfiltered history to 90 days, so backfills also need date windows.+ params["filter"] = [+ f"{parent.history_field}>={start_ms}",+ f"{parent.history_field}<={window_end}",+ ]++ def save_checkpoint(+ next_state: dict[str, Any] | None,+ *,+ window_start: int = start_ms,+ window_stop: int = window_end,+ has_window: bool = window is not None,+ ) -> None:+ # The framework calls this after yielding each page to prevent skipped rows on retries.+ resumable_source_manager.save_state(+ CloverResumeConfig(+ paginator_state={+ "window_start_ms": window_start if next_state else window_stop + 1,+ "end_ms": end_ms,+ "resource_state": next_state,+ "completed": next_state is None and (not has_window or window_stop == end_ms),+ }+ )+ )++ if config.fanout is not None:+ endpoint_configs = {+ name: dataclasses.replace(value, path=_merchant_path(merchant_id, value.path, api_version))+ for name, value in CLOVER_ENDPOINTS.items()+ }+ resource = build_dependent_resource(+ endpoint_configs=endpoint_configs,+ child_endpoint=endpoint,+ fanout=dataclasses.replace(config.fanout, parent_params=params),+ client_config=client_config,+ path_format_values={},+ team_id=team_id,+ job_id=job_id,+ db_incremental_field_last_value=None,+ parent_endpoint_extra={+ "paginator": {"type": "offset", "limit": parent.page_size, "total_path": None},+ "data_selector": "elements",+ "data_selector_required": True,+ },+ child_endpoint_extra={+ "paginator": {"type": "offset", "limit": config.page_size, "total_path": None},+ "data_selector": "elements",+ "data_selector_required": True,+ },+ child_params_extra=config.params,+ resume_hook=save_checkpoint,+ initial_paginator_state=resource_state,+ )+ for page in resource:+ yield [_normalize_row(row, config, window) for row in page]+ resumable_source_manager.safe_point()+ else:+ endpoint_config = _endpoint(config, path)+ endpoint_config["params"] = params+ rest_config: RESTAPIConfig = {+ "client": client_config,+ "resources": [+ {+ "name": endpoint,+ "table_name": endpoint,+ "write_disposition": "replace",+ "endpoint": endpoint_config,+ "table_format": "delta",+ }+ ],+ }+ resource = rest_api_resource(+ rest_config,+ team_id,+ job_id,+ None,+ resume_hook=save_checkpoint,+ initial_paginator_state=resource_state,+ )+ for page in resource:+ yield [_normalize_row(row, config, window) for row in page]+ resumable_source_manager.safe_point()+ if window is None:+ break+ start_ms = window_end + 1+ resource_state = None+ first_window = False+ resumable_source_manager.save_state(+ CloverResumeConfig(+ paginator_state={+ "window_start_ms": start_ms,+ "end_ms": end_ms,+ "resource_state": None,+ "completed": True,+ }+ )+ )++ return SourceResponse(+ name=endpoint,+ items=items,+ primary_keys=config.primary_keys,+ partition_keys=["created_at"] if config.partition_field else config.primary_keys,+ partition_mode="datetime" if config.partition_field else "md5",+ partition_format="month" if config.partition_field else None,+ partition_count=None if config.partition_field else 16,+ sort_mode="desc",+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clover/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clover/settings.pynew file mode 100644index 000000000000..406c8718e2e5--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clover/settings.py@@ -0,0 +1,96 @@+from dataclasses import field+from typing import Any++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ DependentEndpointConfig,+)+from products.warehouse_sources.backend.types import IncrementalField++CLOVER_REGION_HOSTS: dict[str, str] = {+ "na": "https://api.clover.com",+ "eu": "https://api.eu.clover.com",+ "latam": "https://api.la.clover.com",+ "sandbox": "https://apisandbox.dev.clover.com",+}+DEFAULT_REGION = "na"+PAGE_SIZE = 1000+FILTER_WINDOW_MS = 89 * 24 * 60 * 60 * 1000+++@frozen+class CloverEndpointConfig:+ name: str+ path: str+ permission: str+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ params: dict[str, Any] = field(default_factory=dict)+ partition_field: str | None = None+ history_field: str | None = None+ fanout: DependentEndpointConfig | None = None+ page_size: int = PAGE_SIZE+ # Enable incremental sync only after a live account confirms that timestamp filters work.+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ default_incremental_field: str | None = None+++CLOVER_ENDPOINTS: dict[str, CloverEndpointConfig] = {+ "orders": CloverEndpointConfig(+ name="orders",+ path="orders",+ permission="Read orders",+ partition_field="createdTime",+ history_field="createdTime",+ ),+ "line_items": CloverEndpointConfig(+ name="line_items",+ path="orders/{order_id}/line_items",+ permission="Read orders",+ primary_keys=["order_id", "id"],+ partition_field="order_created_time",+ fanout=DependentEndpointConfig(+ parent_name="orders",+ resolve_param="order_id",+ resolve_field="id",+ include_from_parent=["id", "createdTime"],+ parent_field_renames={"id": "order_id", "createdTime": "order_created_time"},+ ),+ ),+ "payments": CloverEndpointConfig(+ name="payments",+ path="payments",+ permission="Read payments",+ partition_field="createdTime",+ history_field="createdTime",+ ),+ "refunds": CloverEndpointConfig(+ name="refunds",+ path="refunds",+ permission="Read payments",+ partition_field="createdTime",+ history_field="createdTime",+ ),+ "credit_refunds": CloverEndpointConfig(+ name="credit_refunds", path="credit_refunds", permission="Read payments", partition_field="createdTime"+ ),+ "items": CloverEndpointConfig(name="items", path="items", permission="Read inventory"),+ "categories": CloverEndpointConfig(name="categories", path="categories", permission="Read inventory"),+ "modifier_groups": CloverEndpointConfig(+ name="modifier_groups", path="modifier_groups", permission="Read inventory"+ ),+ "modifiers": CloverEndpointConfig(name="modifiers", path="modifiers", permission="Read inventory"),+ "customers": CloverEndpointConfig(+ name="customers", path="customers", permission="Read customers", partition_field="customerSince"+ ),+ "employees": CloverEndpointConfig(name="employees", path="employees", permission="Read employees"),+ "shifts": CloverEndpointConfig(name="shifts", path="shifts", permission="Read employees"),+ "tenders": CloverEndpointConfig(name="tenders", path="tenders", permission="Read merchant"),+ "discounts": CloverEndpointConfig(name="discounts", path="discounts", permission="Read inventory"),+ "tax_rates": CloverEndpointConfig(name="tax_rates", path="tax_rates", permission="Read inventory"),+}++ENDPOINTS = tuple(CLOVER_ENDPOINTS)+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in CLOVER_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clover/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clover/source.pyindex 39739de4e627..8ceb29f3f68b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/clover/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clover/source.py@@ -1,14 +1,72 @@-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 posthog.dataclasses import frozen++from products.warehouse_sources.backend.facade.source_config import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.clover.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.clover.clover import (+ CloverResumeConfig,+ clover_source,+ endpoint_permissions as clover_endpoint_permissions,+ validate_credentials as validate_clover_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.clover.settings import (+ CLOVER_ENDPOINTS,+ DEFAULT_REGION,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+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.auth import (+ AuthConfigBase,+ BearerTokenAuth,+)+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, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.clover import CloverSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType+_REGION_LABELS = {+ "na": "North America",+ "eu": "Europe",+ "latam": "Latin America",+ "sandbox": "Sandbox",+}+++@frozen+class CloverConnection:+ region: str+ merchant_id: str+ auth: AuthConfigBase+@SourceRegistry.register-class CloverSource(SimpleSource[CloverSourceConfig]):+class CloverSource(ResumableSource[CloverSourceConfig, CloverResumeConfig]):+ lists_tables_without_credentials = True++ supported_versions = ("v3",)+ default_version = "v3"+ api_docs_url = "https://docs.clover.com/dev/reference/api-reference-overview"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.CLOVER@@ -18,8 +76,148 @@ class CloverSource(SimpleSource[CloverSourceConfig]):return SourceConfig(name=ExternalDataSourceType.CLOVER,category=DataWarehouseSourceCategory.PAYMENTS___BILLING,+ keywords=["pos", "point of sale", "fiserv"],label="Clover (Fiserv)",+ releaseStatus=ReleaseStatus.ALPHA,+ caption=(+ "Import data from one Clover merchant. Use a separate source for each merchant. "+ "Enter a merchant API token. "+ "Grant the permissions for the tables you select: Read orders, Read payments, "+ "Read inventory, Read customers, Read employees, and Read merchant. "+ "All tables use full refresh."+ ),iconPath="/static/services/clover.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/clover",+ fields=cast(+ list[FieldType],+ [+ SourceFieldSelectConfig(+ name="region",+ label="Region",+ required=True,+ defaultValue=DEFAULT_REGION,+ options=[+ SourceFieldSelectConfigOption(label=label, value=region)+ for region, label in _REGION_LABELS.items()+ ],+ ),+ SourceFieldInputConfig(+ name="merchant_id",+ label="Merchant ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="api_token",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url": "Clover rejected your credentials. Generate a new API token and update the source.",+ "403 Client Error: Forbidden for url": "Your Clover connection is missing read access for this table. Grant it in the Clover dashboard and sync again.",+ "Missing Clover API token": "The Clover API token is missing. Enter a merchant API token.",+ "Missing Clover merchant ID": "The Clover merchant ID is missing. Copy it from your Clover dashboard.",+ "Clover supports full refresh only": "Change the Clover table sync mode to full refresh.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: CloverSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ schemas = build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)+ for schema in schemas:+ schema.detected_primary_keys = CLOVER_ENDPOINTS[schema.name].primary_keys+ return schemas++ def _connection(self, config: CloverSourceConfig) -> CloverConnection:+ if not config.api_token:+ raise ValueError("Missing Clover API token")+ if not config.merchant_id:+ raise ValueError("Missing Clover merchant ID")+ return CloverConnection(+ region=config.region, merchant_id=config.merchant_id, auth=BearerTokenAuth(config.api_token)+ )++ def validate_credentials(+ self,+ config: CloverSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ try:+ connection = self._connection(config)+ except ValueError as e:+ raw = str(e)+ for pattern, friendly in self.get_non_retryable_errors().items():+ if friendly and pattern in raw:+ return False, friendly+ return False, raw++ return validate_clover_credentials(+ region=connection.region,+ merchant_id=connection.merchant_id,+ auth=connection.auth,+ schema_name=schema_name,+ api_version=self.resolve_api_version(api_version),+ )++ def get_endpoint_permissions(+ self,+ config: CloverSourceConfig,+ team_id: int,+ endpoints: list[str],+ api_version: str | None = None,+ ) -> dict[str, str | None]:+ try:+ connection = self._connection(config)+ except ValueError:+ return dict.fromkeys(endpoints)++ return clover_endpoint_permissions(+ region=connection.region,+ merchant_id=connection.merchant_id,+ endpoints=endpoints,+ auth=connection.auth,+ api_version=self.resolve_api_version(api_version),+ )++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[CloverResumeConfig]:+ return ResumableSourceManager[CloverResumeConfig](inputs, CloverResumeConfig)++ def source_for_pipeline(+ self,+ config: CloverSourceConfig,+ resumable_source_manager: ResumableSourceManager[CloverResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ connection = self._connection(config)+ return clover_source(+ region=connection.region,+ merchant_id=connection.merchant_id,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ resumable_source_manager=resumable_source_manager,+ auth=connection.auth,+ api_version=self.resolve_api_version(inputs.api_version),+ should_use_incremental_field=inputs.should_use_incremental_field,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clover/tests/test_clover.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clover/tests/test_clover.pynew file mode 100644index 000000000000..5e702fb127d4--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clover/tests/test_clover.py@@ -0,0 +1,266 @@+import json+from collections.abc import Iterator+from contextlib import contextmanager+from datetime import UTC, datetime+from typing import Any, cast+from urllib.parse import parse_qs, urlsplit++from unittest import mock++from django.test import SimpleTestCase++from parameterized import parameterized+from requests import PreparedRequest, Response+from requests.exceptions import HTTPError++from products.warehouse_sources.backend.temporal.data_imports.sources.clover.clover import (+ CloverResumeConfig,+ clover_source,+ endpoint_permissions,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.clover.settings import (+ ENDPOINTS,+ FILTER_WINDOW_MS,+ PAGE_SIZE,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import BearerTokenAuth+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse++MERCHANT_ID = "6MRDFDQMRSSTZ"+NOW_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.clover.clover._now_ms"+++def response(rows: list[dict[str, Any]], status: int = 200) -> Response:+ result = Response()+ result.status_code = status+ result._content = json.dumps({"elements": rows}).encode()+ result.headers["Content-Type"] = "application/json"+ return result+++@contextmanager+def http_responses(responses: list[Response]) -> Iterator[list[PreparedRequest]]:+ requests: list[PreparedRequest] = []+ pending = iter(responses)++ def send(session: Any, request: PreparedRequest, **kwargs: Any) -> Response:+ requests.append(request)+ result = next(pending)+ result.url = request.url or ""+ result.request = request+ return result++ with mock.patch("requests.sessions.Session.send", autospec=True, side_effect=send):+ yield requests+++def manager(state: dict[str, Any] | None = None) -> mock.MagicMock:+ result = mock.MagicMock()+ result.can_resume.return_value = state is not None+ result.load_state.return_value = CloverResumeConfig(paginator_state=state) if state is not None else None+ return result+++def source(endpoint: str, resume_manager: mock.MagicMock, **kwargs: Any) -> SourceResponse:+ return clover_source(+ region="na",+ merchant_id=MERCHANT_ID,+ endpoint=endpoint,+ team_id=1,+ job_id="job-1",+ resumable_source_manager=resume_manager,+ auth=BearerTokenAuth("test-token"),+ api_version="v3",+ **kwargs,+ )+++def rows(result: SourceResponse) -> list[dict[str, Any]]:+ return [row for page in cast(Iterator[list[dict[str, Any]]], result.items()) for row in page]+++def params(request: PreparedRequest) -> dict[str, list[str]]:+ return parse_qs(urlsplit(request.url or "").query)+++class TestCloverTransport(SimpleTestCase):+ @parameterized.expand(ENDPOINTS)+ @mock.patch(NOW_PATCH, return_value=1000)+ def test_each_table_reads_the_collection_and_preserves_fields(self, endpoint: str, now: mock.MagicMock) -> None:+ record = {"id": "row1", "createdTime": 1, "customerSince": 1, "name": "example"}+ pages = (+ [response([{"id": "order1", "createdTime": 1}]), response([record])]+ if endpoint == "line_items"+ else [response([record])]+ )+ with http_responses(pages) as requests:+ result = source(endpoint, manager())+ imported = rows(result)+ self.assertEqual(imported[0]["name"], "example")+ self.assertEqual(imported[0]["id"], "row1")+ self.assertEqual(result.name, endpoint)+ self.assertTrue(all(request.headers["Authorization"] == "Bearer test-token" for request in requests))+ expected_path = (+ f"/v3/merchants/{MERCHANT_ID}/orders/order1/line_items"+ if endpoint == "line_items"+ else f"/v3/merchants/{MERCHANT_ID}/{endpoint}"+ )+ self.assertEqual(urlsplit(requests[-1].url or "").path, expected_path)+ self.assertEqual(params(requests[-1])["limit"], [str(PAGE_SIZE)])+ if result.partition_mode == "datetime":+ self.assertEqual(imported[0]["created_at"], datetime.fromtimestamp(0.001, tz=UTC))+ self.assertEqual(result.partition_keys, ["created_at"])+ if endpoint == "line_items":+ self.assertEqual(imported[0]["order_id"], "order1")+ self.assertEqual(result.primary_keys, ["order_id", "id"])+ else:+ self.assertEqual(result.primary_keys, ["id"])++ def test_full_refresh_paginates_and_checkpoints_after_yield(self) -> None:+ first = [{"id": str(i)} for i in range(PAGE_SIZE)]+ resume_manager = manager()+ with http_responses([response(first), response([{"id": "last"}])]) as requests:+ iterator = iter(cast(Iterator[list[dict[str, Any]]], source("items", resume_manager).items()))+ self.assertEqual(len(next(iterator)), PAGE_SIZE)+ resume_manager.save_state.assert_not_called()+ self.assertEqual(next(iterator), [{"id": "last"}])+ state = resume_manager.save_state.call_args.args[0].paginator_state+ self.assertEqual(state["resource_state"], {"offset": PAGE_SIZE})+ self.assertEqual(list(iterator), [])+ self.assertEqual([params(request)["offset"] for request in requests], [["0"], [str(PAGE_SIZE)]])+ self.assertNotIn("filter", params(requests[0]))+ self.assertTrue(resume_manager.save_state.call_args.args[0].paginator_state["completed"])++ @parameterized.expand([(0,), (PAGE_SIZE,), (3000,)])+ def test_resumes_saved_offset(self, offset: int) -> None:+ with http_responses([response([{"id": "next"}])]) as requests:+ imported = rows(source("items", manager({"resource_state": {"offset": offset}})))+ self.assertEqual(imported, [{"id": "next"}])+ self.assertEqual(params(requests[0])["offset"], [str(offset)])++ @mock.patch(NOW_PATCH, return_value=FILTER_WINDOW_MS * 2 + 1)+ def test_backfill_windows_cover_history_without_overlapping(self, now: mock.MagicMock) -> None:+ records = [{"id": str(i), "createdTime": i * FILTER_WINDOW_MS} for i in range(3)]+ with http_responses([response([record]) for record in records]) as requests:+ imported = rows(source("payments", manager()))+ self.assertEqual([row["id"] for row in imported], ["0", "1", "2"])+ self.assertEqual(+ [params(request)["filter"] for request in requests],+ [+ ["createdTime>=0", f"createdTime<={FILTER_WINDOW_MS - 1}"],+ [f"createdTime>={FILTER_WINDOW_MS}", f"createdTime<={FILTER_WINDOW_MS * 2 - 1}"],+ [f"createdTime>={FILTER_WINDOW_MS * 2}", f"createdTime<={FILTER_WINDOW_MS * 2 + 1}"],+ ],+ )+ self.assertTrue(all(params(request)["offset"] == ["0"] for request in requests))++ @mock.patch(NOW_PATCH, return_value=FILTER_WINDOW_MS * 2)+ def test_resume_keeps_the_original_history_end(self, now: mock.MagicMock) -> None:+ state = {+ "window_start_ms": FILTER_WINDOW_MS,+ "end_ms": FILTER_WINDOW_MS + 10,+ "resource_state": {"offset": PAGE_SIZE},+ }+ with http_responses([response([{"id": "next", "createdTime": FILTER_WINDOW_MS}])]) as requests:+ rows(source("refunds", manager(state)))+ self.assertEqual(len(requests), 1)+ self.assertEqual(+ params(requests[0])["filter"], [f"createdTime>={FILTER_WINDOW_MS}", f"createdTime<={FILTER_WINDOW_MS + 10}"]+ )+ self.assertEqual(params(requests[0])["offset"], [str(PAGE_SIZE)])++ @mock.patch(NOW_PATCH, return_value=1000)+ def test_line_items_page_children_instead_of_expanding_truncated_collections(self, now: mock.MagicMock) -> None:+ first = [{"id": str(i)} for i in range(PAGE_SIZE)]+ parents = [{"id": "order1", "createdTime": 10}, {"id": "order2", "createdTime": 20}]+ with http_responses(+ [response(parents), response(first), response([{"id": "last"}]), response([{"id": "last"}])]+ ) as requests:+ imported = rows(source("line_items", manager()))+ self.assertEqual(len(imported), PAGE_SIZE + 2)+ self.assertEqual([row["order_id"] for row in imported[-2:]], ["order1", "order2"])+ self.assertEqual([params(request)["offset"] for request in requests], [["0"], ["0"], [str(PAGE_SIZE)], ["0"]])+ self.assertTrue(all("expand" not in params(request) for request in requests))++ @mock.patch(NOW_PATCH, return_value=1000)+ def test_fanout_resume_skips_completed_orders_and_resumes_the_child(self, now: mock.MagicMock) -> None:+ path1 = f"/v3/merchants/{MERCHANT_ID}/orders/order1/line_items"+ path2 = f"/v3/merchants/{MERCHANT_ID}/orders/order2/line_items"+ state = {+ "window_start_ms": 0,+ "end_ms": 1000,+ "resource_state": {"completed": [path1], "current": path2, "child_state": {"offset": PAGE_SIZE}},+ }+ parents = [{"id": "order1", "createdTime": 10}, {"id": "order2", "createdTime": 20}]+ with http_responses([response(parents), response([{"id": "last"}])]) as requests:+ imported = rows(source("line_items", manager(state)))+ self.assertEqual(len(requests), 2)+ self.assertEqual(urlsplit(requests[-1].url or "").path, path2)+ self.assertEqual(params(requests[-1])["offset"], [str(PAGE_SIZE)])+ self.assertEqual(imported[0]["order_id"], "order2")++ @parameterized.expand([("missing", None), ("string", "123"), ("boolean", True), ("outside", 1001)])+ @mock.patch(NOW_PATCH, return_value=1000)+ def test_invalid_or_ignored_history_filters_fail_instead_of_losing_data(+ self, name: str, timestamp: Any, now: mock.MagicMock+ ) -> None:+ with http_responses([response([{"id": "row", "createdTime": timestamp}])]):+ with self.assertRaisesRegex(ValueError, "timestamp|outside"):+ rows(source("orders", manager()))++ def test_changed_collection_envelope_fails_instead_of_erasing_a_table(self) -> None:+ bad_response = response([])+ bad_response._content = b'{"unexpected": []}'+ with http_responses([bad_response]):+ with self.assertRaisesRegex(ValueError, "data_selector"):+ rows(source("items", manager()))++ @parameterized.expand([(401,), (403,)])+ def test_auth_errors_propagate_without_source_retries(self, status: int) -> None:+ with http_responses([response([], status)]) as requests:+ with self.assertRaises(HTTPError):+ rows(source("items", manager()))+ self.assertEqual(len(requests), 1)++ def test_incremental_config_is_rejected_until_filters_are_verified(self) -> None:+ with self.assertRaisesRegex(ValueError, "full refresh only"):+ source("items", manager(), should_use_incremental_field=True)++ @parameterized.expand(+ [+ (200, None, True),+ (401, None, False),+ (403, None, True),+ (403, "items", False),+ (404, None, False),+ (302, None, False),+ (500, None, False),+ ]+ )+ def test_credential_status_mapping(self, status: int, schema: str | None, valid: bool) -> None:+ with http_responses([response([], status)]) as requests:+ result = validate_credentials("na", MERCHANT_ID, BearerTokenAuth("test-token"), "v3", schema)+ self.assertEqual(result[0], valid)+ expected_path = f"/v3/merchants/{MERCHANT_ID}" + ("/items" if schema else "")+ self.assertEqual(urlsplit(requests[0].url or "").path, expected_path)+ if schema:+ self.assertIn("Read inventory", result[1] or "")++ def test_permission_probes_name_scopes_and_ignore_transient_failures(self) -> None:+ with http_responses([response([], 403), response([], 500), response([], 200)]) as requests:+ result = endpoint_permissions(+ "na", MERCHANT_ID, ["orders", "items", "line_items"], BearerTokenAuth("test-token"), "v3"+ )+ self.assertIn("Read orders", result["orders"] or "")+ self.assertIsNone(result["items"])+ self.assertIsNone(result["line_items"])+ self.assertTrue(all(params(request)["limit"] == ["1"] for request in requests))+ self.assertTrue((requests[-1].url or "").endswith("/orders?limit=1"))++ @parameterized.expand([("../oauth",), ("",), ("M\n",)])+ def test_invalid_merchant_ids_cannot_change_the_request_path(self, merchant_id: str) -> None:+ with http_responses([]) as requests:+ result = validate_credentials("na", merchant_id, BearerTokenAuth("test-token"), "v3")+ self.assertFalse(result[0])+ self.assertEqual(requests, [])diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/clover/tests/test_clover_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/clover/tests/test_clover_source.pynew file mode 100644index 000000000000..d92e364e8563--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/clover/tests/test_clover_source.py@@ -0,0 +1,179 @@+from typing import Literal+from urllib.parse import urlsplit++from unittest import mock++from django.test import SimpleTestCase++import structlog+from parameterized import parameterized+from requests.exceptions import ConnectionError++from products.warehouse_sources.backend.facade.source_config import ReleaseStatus, SourceFieldInputConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.clover.clover import CloverResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.clover.source import CloverSource+from products.warehouse_sources.backend.temporal.data_imports.sources.clover.tests.test_clover import (+ MERCHANT_ID,+ NOW_PATCH,+ http_responses,+ manager,+ response,+ rows,+)+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 SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.clover import CloverSourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType++TABLES = {+ "orders",+ "line_items",+ "payments",+ "refunds",+ "credit_refunds",+ "items",+ "categories",+ "modifier_groups",+ "modifiers",+ "customers",+ "employees",+ "shifts",+ "tenders",+ "discounts",+ "tax_rates",+}+++def token_config(region: Literal["na", "eu", "latam", "sandbox"] = "na") -> CloverSourceConfig:+ return CloverSourceConfig(region=region, merchant_id=MERCHANT_ID, api_token="test-token")+++def inputs(schema: str = "items", incremental: bool = False, version: str | None = None) -> SourceInputs:+ return SourceInputs(+ schema_name=schema,+ schema_id="schema1",+ source_id="source1",+ team_id=1,+ should_use_incremental_field=incremental,+ db_incremental_field_last_value=None,+ db_incremental_field_earliest_value=None,+ incremental_field=None,+ incremental_field_type=None,+ job_id="job1",+ logger=structlog.get_logger(),+ reset_pipeline=False,+ api_version=version,+ )+++class TestCloverSource(SimpleTestCase):+ def setUp(self) -> None:+ self.source = CloverSource()+ self.config = token_config()++ def test_connection_form_is_visible_and_keeps_api_tokens_secret(self) -> None:+ config = self.source.get_source_config+ self.assertEqual(self.source.source_type, ExternalDataSourceType.CLOVER)+ self.assertEqual(config.label, "Clover (Fiserv)")+ self.assertEqual(config.releaseStatus, ReleaseStatus.ALPHA)+ self.assertFalse(config.unreleasedSource)+ self.assertEqual(config.iconPath, "/static/services/clover.png")+ self.assertEqual(config.docsUrl, "https://posthog.com/docs/cdp/sources/clover")+ secrets = {field.name for field in config.fields if isinstance(field, SourceFieldInputConfig) and field.secret}+ self.assertEqual(secrets, {"api_token"})++ def test_catalog_lists_full_refresh_tables_without_credentials(self) -> None:+ schemas = self.source.get_schemas(self.config, 1)+ self.assertEqual({schema.name for schema in schemas}, TABLES)+ self.assertTrue(all(not schema.supports_incremental and not schema.supports_append for schema in schemas))+ self.assertTrue(all(not schema.incremental_fields for schema in schemas))+ tables = self.source.get_documented_tables()+ self.assertEqual({table["name"] for table in tables}, TABLES)+ self.assertTrue(all(table["description"] and table["primary_keys"] for table in tables))+ self.assertTrue(all(table["sync_methods"] == ["Full refresh"] for table in tables))+ self.assertEqual(+ [schema.name for schema in self.source.get_schemas(self.config, 1, names=["modifiers"])], ["modifiers"]+ )+ self.assertEqual(self.source.get_schemas(self.config, 1, names=[]), [])++ @parameterized.expand([(200, None, True), (401, None, False), (403, None, True), (403, "payments", False)])+ def test_credentials_probe_the_requested_scope(self, status: int, schema: str | None, valid: bool) -> None:+ with http_responses([response([], status)]) as requests:+ result = self.source.validate_credentials(self.config, 1, schema_name=schema)+ self.assertEqual(result[0], valid)+ path = f"/v3/merchants/{MERCHANT_ID}" + ("/payments" if schema else "")+ self.assertEqual(urlsplit(requests[0].url or "").path, path)+ self.assertEqual(requests[0].headers["Authorization"], "Bearer test-token")++ @parameterized.expand(+ [+ ("na", "api.clover.com"),+ ("eu", "api.eu.clover.com"),+ ("latam", "api.la.clover.com"),+ ("sandbox", "apisandbox.dev.clover.com"),+ ]+ )+ def test_pipeline_uses_the_selected_regional_host(+ self, region: Literal["na", "eu", "latam", "sandbox"], host: str+ ) -> None:+ with http_responses([response([{"id": "item1"}])]) as requests:+ imported = rows(self.source.source_for_pipeline(token_config(region), manager(), inputs()))+ self.assertEqual(imported, [{"id": "item1"}])+ self.assertEqual(urlsplit(requests[0].url or "").hostname, host)++ @parameterized.expand(+ [+ ("", MERCHANT_ID, "Missing Clover API token"),+ ("test-token", "", "Missing Clover merchant ID"),+ ]+ )+ def test_missing_credentials_fail_before_http(self, api_token: str, merchant_id: str, pattern: str) -> None:+ config = CloverSourceConfig(region="na", merchant_id=merchant_id, api_token=api_token)+ with http_responses([]) as requests:+ result = self.source.validate_credentials(config, 1)+ self.assertFalse(result[0])+ self.assertTrue(result[1])+ self.assertEqual(requests, [])+ self.assertIn(pattern, self.source.get_non_retryable_errors())++ def test_network_failure_is_reported_without_exposing_request_details(self) -> None:+ with mock.patch("requests.sessions.Session.send", side_effect=ConnectionError("private request detail")):+ valid, message = self.source.validate_credentials(self.config, 1)+ self.assertFalse(valid)+ self.assertEqual(message, "Could not connect to Clover. Try again.")++ @parameterized.expand([(401, True), (403, True), (429, False), (500, False)])+ def test_only_permanent_http_errors_are_non_retryable(self, status: int, permanent: bool) -> None:+ message = (+ f"{status} Client Error: "+ + ({401: "Unauthorized", 403: "Forbidden"}.get(status, "Transient"))+ + " for url: https://api.clover.com"+ )+ self.assertEqual(any(key in message for key in self.source.get_non_retryable_errors()), permanent)++ def test_manager_serializes_the_resume_data_class(self) -> None:+ resume_manager = self.source.get_resumable_source_manager(inputs())+ self.assertIsInstance(resume_manager, ResumableSourceManager)+ state = CloverResumeConfig(paginator_state={"resource_state": {"offset": 1000}, "end_ms": 2000})+ self.assertEqual(resume_manager._load_json(resume_manager._dump_json(state)), state)++ @mock.patch(NOW_PATCH, return_value=1000)+ def test_pipeline_uses_saved_state_and_stable_creation_partitions(self, now: mock.MagicMock) -> None:+ resume_manager = manager({"window_start_ms": 10, "end_ms": 1000, "resource_state": {"offset": 1000}})+ with http_responses([response([{"id": "order", "createdTime": 20, "modifiedTime": 999}])]) as requests:+ result = self.source.source_for_pipeline(self.config, resume_manager, inputs("orders"))+ imported = rows(result)+ self.assertEqual(imported[0]["created_at"].timestamp(), 0.02)+ self.assertEqual(result.partition_keys, ["created_at"])+ self.assertIn("offset=1000", requests[0].url or "")++ @parameterized.expand([(True, "v3", "full refresh only"), (False, "v4", "Unsupported Clover API version")])+ def test_pipeline_rejects_unverified_modes_and_versions(+ self, incremental: bool, version: str, message: str+ ) -> None:+ with http_responses([]) as requests:+ with self.assertRaisesRegex(ValueError, message):+ self.source.source_for_pipeline(+ self.config, manager(), inputs(incremental=incremental, version=version)+ )+ self.assertEqual(requests, [])diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/clover.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/clover.pyindex 8375770e9a15..9d50c3963ae7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/clover.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/clover.py@@ -1,9 +1,13 @@# This file is automatically generated from `SourceRegistry.get_all_sources()`# Do not edit manually - run `pnpm generate:source-configs` to regenerate.+from typing import Literal+from products.warehouse_sources.backend.temporal.data_imports.sources.common import config@config.configclass CloverSourceConfig(config.Config):- pass+ merchant_id: str+ api_token: str+ region: Literal["na", "eu", "latam", "sandbox"] = config.value(default="na")