: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 veeqo import source (#72627)
Tom Owers628362a32115
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex e8ffcb84a0de..b5b995b5e958 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -559,6 +559,7 @@ the row lists both.| vantage | HTTP | requests | ✅ || vapi | HTTP | requests | ✅ || vellum | HTTP | requests | ✅ |+| veeqo | HTTP | requests + `rest_source.RESTClient` | ✅ || veracode | HTTP | requests (custom HMAC signing) | ✅ || vercel | HTTP | requests | ✅ || vitally | HTTP | requests + `rest_source.RESTClient` | ✅ |@@ -981,7 +982,6 @@ doesn't conflict with concurrent PRs.- uppromote- uptick- uservoice-- veeqo- vespa- visma_economic- vwodiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/veeqo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/veeqo.pyindex f9625a29baee..620382f2fd26 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/veeqo.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/veeqo.py@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass VeeqoSourceConfig(config.Config):- pass+ api_key: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/veeqo/api_inventory.md b/products/warehouse_sources/backend/temporal/data_imports/sources/veeqo/api_inventory.mdnew file mode 100644index 000000000000..9ac86b4ad9a4--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/veeqo/api_inventory.md@@ -0,0 +1,49 @@+# Veeqo API inventory++Source: Veeqo — multichannel ecommerce inventory, order and shipping management (Amazon-owned).++- **API version:** unversioned (no version path segment, header, or param).+- **Base URL:** `https://api.veeqo.com`+- **Auth:** API key in the `x-api-key` header. Keys carry full account access (no scopes) and+ must be enabled by Veeqo support before they appear in account settings. OAuth2 exists but is+ only required for public Appstore apps.+- **Docs:** <https://developers.veeqo.com/api>+- **Pagination:** page-number (`page`, 1-based, + `page_size`). Responses carry+ `X-Total-Count`, `X-Total-Pages-Count`, `X-Page-Index` and `X-Per-Page` headers. Defaults are+ tiny (12 on most endpoints, 10 on warehouses); `/products` documents a max `page_size` of 100,+ the rest document no max — we send 100 everywhere.+- **Incremental:** server-side `updated_at_min` / `created_at_min` (format+ `YYYY-MM-DD HH:MM:SS`) and `since_id` filters on orders and products. No sort param is+ documented on any list endpoint, so ordering is undeclared — the source uses+ `sort_mode="desc"` semantics (watermark commits only after a successful sync).+- **Rate limiting:** leaky bucket — 5 requests/second sustained with burst capacity up to 100;+ exceeding returns HTTP 429 (retried by the tracked transport honoring `Retry-After`).+- **Response shape:** bare JSON arrays on list endpoints (no wrapper key); enforced with+ `data_selector_required` so a shape change fails loud.++> ⚠️ **Unverified against a live account.** Endpoint params below come from the public docs at+> developers.veeqo.com; they were not curl-verified during implementation (Veeqo API keys must+> be enabled by their support team, and no test credentials were available). Only the 401 error+> shape was probed live. Treat the incremental-filter and pagination assumptions as+> conservative until confirmed against a real account.++## Endpoints++| Schema | Path | Primary key | Partition key | Incremental | Notes |+| ------------------ | ------------------- | ----------- | ------------- | ----------- | --------------------------------------------------------------- |+| `orders` | `/orders` | `id` | `created_at` | ✅ | `updated_at_min` / `created_at_min` / `since_id`. |+| `products` | `/products` | `id` | `created_at` | ✅ | `updated_at_min` / `created_at_min` / `since_id`; max page 100. |+| `customers` | `/customers` | `id` | — | ➖ full | Only `page`/`page_size`/`query`/`customer_type` documented. |+| `purchase_orders` | `/purchase_orders` | `id` | `created_at` | ➖ full | `show_complete=true` sent so completed POs are included. |+| `suppliers` | `/suppliers` | `id` | — | ➖ full | |+| `warehouses` | `/warehouses` | `id` | — | ➖ full | |+| `stores` | `/channels` | `id` | — | ➖ full | Veeqo calls stores "channels" in the API. |+| `tags` | `/tags` | `id` | — | ➖ full | No pagination params documented; fetched as a single page. |+| `delivery_methods` | `/delivery_methods` | `id` | `created_at` | ➖ full | |++## Possible future work++- **Nested resources.** Order allocations/shipments, product sellables and per-warehouse stock+ entries are nested in the orders/products payloads today; dedicated fan-out endpoints+ (`/sellables/{id}/warehouses/{id}/stock_entry`) exist if flattened tables are ever needed.+- **Webhooks.** Veeqo has no webhook API, so `WebhookSource` is not applicable.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/veeqo/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/veeqo/canonical_descriptions.pynew file mode 100644index 000000000000..ab4c97cc8191--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/veeqo/canonical_descriptions.py@@ -0,0 +1,163 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "orders": {+ "description": "A sales order placed on any of your connected sales channels, including its line items, allocations and payment.",+ "docs_url": "https://developers.veeqo.com/api/operations/list-all-orders/",+ "columns": {+ "id": "Unique identifier for the order.",+ "number": "The order's reference number.",+ "status": "Order status (awaiting_payment, awaiting_stock, awaiting_fulfillment, shipped, on_hold, cancelled or refunded).",+ "created_at": "The date and time when the order was created.",+ "updated_at": "The date and time when the order was last updated.",+ "cancelled_at": "The date and time when the order was cancelled, if applicable.",+ "shipped_at": "The date and time when the order was shipped, if applicable.",+ "due_date": "The date the order is due.",+ "dispatch_date": "The date the order was dispatched, if applicable.",+ "delivery_cost": "The delivery cost charged on the order.",+ "subtotal_price": "The order subtotal before discounts, tax and fees.",+ "total_price": "The total price of the order.",+ "total_tax": "The total tax on the order.",+ "total_discounts": "The total discounts applied to the order.",+ "total_fees": "The total fees on the order.",+ "international": "Whether the order ships internationally.",+ "notes": "Internal notes attached to the order.",+ "customer_viewable_notes": "Notes on the order that the customer can see.",+ "cancel_reason": "The reason the order was cancelled, if applicable.",+ "refund_amount": "The amount refunded on the order, if applicable.",+ "buyer_user_id": "ID of the buyer user associated with the order, if any.",+ "created_by_id": "ID of the user who created the order.",+ "fulfilled_by_amazon": "Whether the order is fulfilled by Amazon (FBA).",+ "is_amazon_prime": "Whether the order is an Amazon Prime order.",+ },+ },+ "products": {+ "description": "A product in your Veeqo inventory, including its variants (sellables), images and stock information.",+ "docs_url": "https://developers.veeqo.com/api/operations/list-all-products/",+ "columns": {+ "id": "ID of the product.",+ "title": "The product's title.",+ "created_at": "The time the product was created.",+ "updated_at": "The date and time this product was last updated.",+ "created_by_id": "ID of the user who created the product.",+ "updated_by_id": "ID of the user that last updated the product.",+ "origin_country": "Two letter country code where this product was manufactured, for customs declarations.",+ "hs_tariff_number": "The Harmonized System code (tariff number) of this product, used for international shipments.",+ "notes": "Notes associated with this product.",+ "tax_rate": "The tax rate of this product.",+ "estimated_delivery": "Number of days this product will take to ship.",+ "hazmat": "Whether this product contains hazardous goods, required to be declared by certain carriers.",+ "total_quantity_sold": "Number of units this product has sold.",+ },+ },+ "customers": {+ "description": "A customer who has placed orders on any of your connected sales channels.",+ "docs_url": "https://developers.veeqo.com/api/operations/list-all-customers/",+ "columns": {+ "id": "Unique identifier for the customer.",+ "email": "The customer's email address.",+ "phone": "The customer's phone number.",+ "mobile": "The customer's mobile number.",+ "notes": "Internal notes about the customer.",+ "created_by_id": "ID of the user who created the customer.",+ "billing_address": "The customer's billing address.",+ "shipping_addresses": "The customer's saved shipping addresses.",+ "last_used_shipping_address": "The shipping address most recently used by the customer.",+ },+ },+ "purchase_orders": {+ "description": "A purchase order raised against a supplier to replenish stock, including its line items and delivery details.",+ "docs_url": "https://developers.veeqo.com/api/operations/list-all-purchase-orders/",+ "columns": {+ "id": "Unique identifier for the purchase order.",+ "number": "The purchase order's reference number.",+ "created_at": "The date and time when the purchase order was created.",+ "completed_at": "The date and time when the purchase order was completed, if applicable.",+ "created_by_id": "ID of the user who created the purchase order.",+ "destination_warehouse_id": "ID of the warehouse the purchase order will be delivered to.",+ "estimated_delivery_days": "Estimated number of days for the order to be delivered.",+ "line_items": "The products and quantities ordered from the supplier.",+ },+ },+ "suppliers": {+ "description": "A supplier you raise purchase orders against, including contact and payment details.",+ "docs_url": "https://developers.veeqo.com/api/operations/list-all-suppliers/",+ "columns": {+ "id": "Unique identifier for the supplier.",+ "name": "The supplier's name.",+ "address_line_1": "The first line of the supplier's address.",+ "address_line_2": "The second line of the supplier's address.",+ "city": "The supplier's city.",+ "region": "The supplier's state or county.",+ "post_code": "The supplier's postal/ZIP code.",+ "currency_code": "The currency the supplier trades in.",+ "sales_contact_name": "Name of the supplier's sales contact.",+ "sales_contact_email": "Email address of the supplier's sales contact.",+ "accounting_contact_name": "Name of the supplier's accounting contact.",+ "credit_limit": "The credit limit agreed with the supplier.",+ "active_purchase_order_count": "Number of active purchase orders with the supplier.",+ "completed_purchase_order_count": "Number of completed purchase orders with the supplier.",+ "created_at": "The date and time when the supplier was created.",+ "updated_at": "The date and time when the supplier was last updated.",+ },+ },+ "warehouses": {+ "description": "A physical or virtual location where you hold inventory.",+ "docs_url": "https://developers.veeqo.com/api/operations/list-all-warehouses/",+ "columns": {+ "id": "Unique identifier for the warehouse.",+ "name": "The name of the warehouse.",+ "address_line_1": "The first line of the warehouse address.",+ "address_line_2": "The second line of the warehouse address.",+ "city": "The warehouse's city.",+ "region": "The warehouse's state or county.",+ "country": "The warehouse's country.",+ "post_code": "The warehouse's postal/ZIP code.",+ "phone": "The warehouse's phone number, if applicable.",+ "cut_off_times_enabled": "Whether cut-off times are enabled for this warehouse.",+ "cut_off_times": "Cut-off times for the warehouse.",+ },+ },+ "stores": {+ "description": "A sales channel (store) connected to Veeqo, such as Shopify, eBay or Amazon.",+ "docs_url": "https://developers.veeqo.com/api/operations/list-all-stores/",+ "columns": {+ "id": "Unique identifier for the store.",+ "name": "The store's name.",+ "short_name": "The store's short name.",+ "type_code": "The channel type of the store (e.g. Shopify, eBay, Amazon).",+ "currency_code": "The currency the store trades in.",+ "state": "The connection state of the store.",+ "url": "The store's URL.",+ "country": "The store's country.",+ "created_by_id": "ID of the user who connected the store.",+ "pulled_products_at": "The last time products were pulled from the store.",+ "pulled_orders_at": "The last time orders were pulled from the store.",+ },+ },+ "tags": {+ "description": "A tag used to label and organize orders and products.",+ "docs_url": "https://developers.veeqo.com/api/operations/list-all-tags/",+ "columns": {+ "id": "Unique identifier for the tag.",+ "name": "The tag's name.",+ "colour": "The tag's display color (hex code).",+ "company_id": "ID of the Veeqo company the tag belongs to.",+ "taggings_count": "Number of records labeled with this tag.",+ },+ },+ "delivery_methods": {+ "description": "A delivery method offered on your orders, with its shipping cost.",+ "docs_url": "https://developers.veeqo.com/api/operations/list-all-delivery-methods/",+ "columns": {+ "id": "ID of this delivery method.",+ "name": "The name of the delivery method.",+ "cost": "The cost to ship orders with this delivery method.",+ "user_id": "ID of the user who created the delivery method.",+ "created_at": "The date and time when the delivery method was created.",+ "updated_at": "The date and time when the delivery method was last updated.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/veeqo/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/veeqo/settings.pynew file mode 100644index 000000000000..cc43826a5444--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/veeqo/settings.py@@ -0,0 +1,125 @@+from dataclasses import dataclass, field+from typing import Any, Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# Veeqo defaults to tiny pages (12 on most endpoints, 10 on warehouses), so the page+# size is always set explicitly. `/products` documents a maximum of 100; the other+# endpoints document no maximum, so 100 is used everywhere for consistency.+DEFAULT_PAGE_SIZE = 100+++@dataclass+class VeeqoEndpointConfig:+ """Declarative metadata for a single Veeqo list endpoint.++ `path` is appended to the API base URL. `partition_key` must be a STABLE field+ (`created_at`) so partitions are never rewritten — never `updated_at`; endpoints+ whose list response doesn't document a `created_at` column leave it unset.++ `incremental_fields` is the menu of advertised cursor options; the user's actual+ choice arrives via `inputs.incremental_field`. It is only populated for endpoints+ where Veeqo documents server-side filters (`updated_at_min` / `created_at_min` /+ `since_id`). Endpoints without a documented server-side filter ship full-refresh.+ """++ name: str+ path: str+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ partition_key: Optional[str] = None+ # Static query params sent on every request (e.g. purchase_orders' show_complete).+ extra_params: dict[str, Any] = field(default_factory=dict)+ page_size: int = DEFAULT_PAGE_SIZE+ # True for endpoints that document no pagination params: the whole list arrives in+ # one response, so a page-number paginator would refetch the same full list forever+ # once it holds page_size or more rows.+ single_page: bool = False++ @property+ def supports_incremental(self) -> bool:+ return bool(self.incremental_fields)+++def _timestamp_field(name: str) -> IncrementalField:+ return {+ "label": name,+ "type": IncrementalFieldType.DateTime,+ "field": name,+ "field_type": IncrementalFieldType.DateTime,+ }+++def _id_field() -> IncrementalField:+ return {+ "label": "id",+ "type": IncrementalFieldType.Integer,+ "field": "id",+ "field_type": IncrementalFieldType.Integer,+ }+++# Orders and products document all three server-side filters: `updated_at_min`,+# `created_at_min`, and `since_id`. `updated_at` is the better default (catches+# mutations); `created_at` and `id` suit append-only consumers.+_FULL_INCREMENTAL_MENU = [_timestamp_field("updated_at"), _timestamp_field("created_at"), _id_field()]+++VEEQO_ENDPOINTS: dict[str, VeeqoEndpointConfig] = {+ "orders": VeeqoEndpointConfig(+ name="orders",+ path="/orders",+ incremental_fields=_FULL_INCREMENTAL_MENU,+ partition_key="created_at",+ ),+ "products": VeeqoEndpointConfig(+ name="products",+ path="/products",+ incremental_fields=_FULL_INCREMENTAL_MENU,+ partition_key="created_at",+ ),+ # `/customers` only documents page/page_size/query/customer_type — no timestamp+ # or since_id filter, so full-refresh only.+ "customers": VeeqoEndpointConfig(+ name="customers",+ path="/customers",+ ),+ # `/purchase_orders` hides completed POs by default; show_complete=true includes+ # them so the warehouse table reflects the full history.+ "purchase_orders": VeeqoEndpointConfig(+ name="purchase_orders",+ path="/purchase_orders",+ partition_key="created_at",+ extra_params={"show_complete": "true"},+ ),+ "suppliers": VeeqoEndpointConfig(+ name="suppliers",+ path="/suppliers",+ ),+ "warehouses": VeeqoEndpointConfig(+ name="warehouses",+ path="/warehouses",+ ),+ # Veeqo calls stores "channels" in the API.+ "stores": VeeqoEndpointConfig(+ name="stores",+ path="/channels",+ ),+ # `/tags` documents no pagination params at all, so it's fetched as a single page —+ # paginating an endpoint that ignores `page` would refetch the same full list forever.+ "tags": VeeqoEndpointConfig(+ name="tags",+ path="/tags",+ single_page=True,+ ),+ "delivery_methods": VeeqoEndpointConfig(+ name="delivery_methods",+ path="/delivery_methods",+ partition_key="created_at",+ ),+}++ENDPOINTS = tuple(VEEQO_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in VEEQO_ENDPOINTS.items() if config.supports_incremental+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/veeqo/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/veeqo/source.pyindex e18367ef6fd1..e3e31add1926 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/veeqo/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/veeqo/source.py@@ -1,19 +1,48 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.veeqo import VeeqoSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.veeqo.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.veeqo.veeqo import (+ VeeqoResumeConfig,+ validate_credentials as validate_veeqo_credentials,+ veeqo_source,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class VeeqoSource(SimpleSource[VeeqoSourceConfig]):+class VeeqoSource(ResumableSource[VeeqoSourceConfig, VeeqoResumeConfig]):+ # Veeqo's API is unversioned (no version path segment, header, or param).+ api_docs_url = "https://developers.veeqo.com/api"++ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.VEEQO@@ -24,7 +53,81 @@ class VeeqoSource(SimpleSource[VeeqoSourceConfig]):name=SchemaExternalDataSourceType.VEEQO,category=DataWarehouseSourceCategory.E_COMMERCE,label="Veeqo",+ caption="""Enter your Veeqo API key to automatically pull your Veeqo inventory, order and shipping data into the PostHog Data warehouse.++You can find your API key in your Veeqo account under **Settings > Users**, on your user's profile. Veeqo support must enable API access for your account before the key appears there — contact them if you don't see it.++The API key gives full account access, so store it securely.+""",iconPath="/static/services/veeqo.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/veeqo",+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="Enter your Veeqo API key",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.veeqo.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://api.veeqo.com": (+ "Veeqo rejected the API key. Check the key in your Veeqo account settings and reconnect — "+ "Veeqo support must enable API access before a key works."+ ),+ "403 Client Error: Forbidden for url: https://api.veeqo.com": (+ "The Veeqo API key does not have access to this resource. Check the key and try again."+ ),+ }++ def get_schemas(+ self,+ config: VeeqoSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)++ def validate_credentials(+ self, config: VeeqoSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_veeqo_credentials(config.api_key)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[VeeqoResumeConfig]:+ return ResumableSourceManager[VeeqoResumeConfig](inputs, VeeqoResumeConfig)++ def source_for_pipeline(+ self,+ config: VeeqoSourceConfig,+ resumable_source_manager: ResumableSourceManager[VeeqoResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return veeqo_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,+ incremental_field=inputs.incremental_field,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/veeqo/tests/test_veeqo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/veeqo/tests/test_veeqo.pynew file mode 100644index 000000000000..9a8c6fb1a74d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/veeqo/tests/test_veeqo.py@@ -0,0 +1,380 @@+import json+from datetime import UTC, date, datetime, timedelta, timezone+from typing import Any++import pytest+from unittest import mock++from parameterized import parameterized+from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.veeqo.settings import VEEQO_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.veeqo.veeqo import (+ VeeqoPaginator,+ VeeqoResumeConfig,+ _build_initial_params,+ _format_incremental_value,+ validate_credentials,+ veeqo_source,+)++# RESTClient builds its session via make_tracked_session in the rest_client module.+CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+# validate_credentials builds its own tracked session in the veeqo module.+VEEQO_SESSION_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.veeqo.veeqo.make_tracked_session"+)+++def _response(body: Any, status_code: int = 200, headers: dict[str, str] | None = None) -> Response:+ resp = Response()+ resp.status_code = status_code+ resp._content = json.dumps(body).encode()+ resp.headers.update(headers or {})+ return resp+++def _make_manager(resume_state: VeeqoResumeConfig | 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 _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:+ """Wire a mock session and capture each request's params AT SEND TIME.++ ``request.params`` is mutated in place across pages, so inspecting it after the+ run shows only the final state — snapshot a copy when each request is prepared.+ """+ session.headers = {}+ param_snapshots: list[dict[str, Any]] = []++ def _prepare(request: Any) -> mock.MagicMock:+ param_snapshots.append(dict(request.params or {}))+ return mock.MagicMock()++ session.prepare_request.side_effect = _prepare+ session.send.side_effect = responses+ return param_snapshots+++def _rows(source_response) -> list[dict[str, Any]]:+ return [row for page in source_response.items() for row in page]+++def _full_page(page_size: int = 100) -> list[dict[str, Any]]:+ return [{"id": i} for i in range(page_size)]+++class TestVeeqoPaginator:+ def test_stops_via_total_pages_header_without_extra_request(self) -> None:+ # With X-Total-Pages-Count=1 a full first page must terminate immediately+ # instead of paying one extra empty-page request.+ paginator = VeeqoPaginator(page_size=100)+ paginator.update_state(_response(_full_page(), headers={"X-Total-Pages-Count": "1"}), _full_page())+ assert paginator.has_next_page is False++ def test_continues_when_more_pages_remain(self) -> None:+ paginator = VeeqoPaginator(page_size=100)+ paginator.update_state(_response(_full_page(), headers={"X-Total-Pages-Count": "3"}), _full_page())+ assert paginator.has_next_page is True+ assert paginator.page == 2++ def test_short_page_stops_even_without_headers(self) -> None:+ # A partial page is always the last page for offset-backed page-number+ # pagination; without this stop the terminal page costs one extra+ # empty-page request whenever the total-pages header is missing.+ paginator = VeeqoPaginator(page_size=100)+ short_page = [{"id": 1}, {"id": 2}]+ paginator.update_state(_response(short_page), short_page)+ assert paginator.has_next_page is False++ def test_empty_page_stops(self) -> None:+ paginator = VeeqoPaginator(page_size=100)+ paginator.update_state(_response([]), [])+ assert paginator.has_next_page is False++ def test_malformed_total_pages_header_falls_back_to_page_size_check(self) -> None:+ paginator = VeeqoPaginator(page_size=100)+ paginator.update_state(_response(_full_page(), headers={"X-Total-Pages-Count": "unknown"}), _full_page())+ # A full page with an unparseable header keeps paginating rather than crashing.+ assert paginator.has_next_page is True++ def test_resume_state_round_trip(self) -> None:+ paginator = VeeqoPaginator(page_size=100)+ paginator.update_state(_response(_full_page(), headers={"X-Total-Pages-Count": "5"}), _full_page())+ state = paginator.get_resume_state()+ assert state == {"page": 2}++ resumed = VeeqoPaginator(page_size=100)+ resumed.set_resume_state(state)+ request = mock.MagicMock(params=None)+ resumed.init_request(request)+ assert request.params["page"] == 2++ def test_no_resume_state_on_terminal_page(self) -> None:+ paginator = VeeqoPaginator(page_size=100)+ paginator.update_state(_response([]), [])+ assert paginator.get_resume_state() is None+++class TestFormatIncrementalValue:+ @parameterized.expand(+ [+ ("utc_datetime", "updated_at", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04 02:58:14"),+ ("naive_datetime", "updated_at", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04 02:58:14"),+ (+ "non_utc_datetime_normalized",+ "created_at",+ datetime(2026, 3, 4, 4, 58, 14, tzinfo=timezone(timedelta(hours=2))),+ "2026-03-04 02:58:14",+ ),+ ("date_value", "created_at", date(2026, 3, 4), "2026-03-04 00:00:00"),+ ("string_passthrough", "updated_at", "2026-03-04 00:00:00", "2026-03-04 00:00:00"),+ ("id_as_int", "id", 12345, 12345),+ ("id_string_coerced", "id", "12345", 12345),+ ]+ )+ def test_format_incremental_value(self, _name: str, field: str, value: object, expected: object) -> None:+ assert _format_incremental_value(field, value) == expected+++class TestBuildInitialParams:+ @parameterized.expand(+ [+ ("updated_at", "updated_at_min", "2026-03-04 02:58:14"),+ ("created_at", "created_at_min", "2026-03-04 02:58:14"),+ ]+ )+ def test_incremental_maps_user_field_to_documented_param(+ self, incremental_field: str, expected_param: str, expected_value: str+ ) -> None:+ params = _build_initial_params(+ VEEQO_ENDPOINTS["orders"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),+ incremental_field=incremental_field,+ )+ assert params[expected_param] == expected_value+ assert params["page_size"] == 100++ def test_incremental_on_id_uses_since_id(self) -> None:+ params = _build_initial_params(+ VEEQO_ENDPOINTS["products"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=99887,+ incremental_field="id",+ )+ assert params["since_id"] == 99887+ assert "updated_at_min" not in params++ def test_first_incremental_sync_without_last_value_sends_no_filter(self) -> None:+ params = _build_initial_params(+ VEEQO_ENDPOINTS["orders"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=None,+ incremental_field="updated_at",+ )+ assert not any(k.endswith("_min") or k == "since_id" for k in params)++ def test_full_refresh_endpoint_ignores_incremental_inputs(self) -> None:+ # Endpoints without a documented server-side filter must never emit one,+ # even when incremental inputs are supplied.+ params = _build_initial_params(+ VEEQO_ENDPOINTS["customers"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),+ incremental_field="updated_at",+ )+ assert params == {"page_size": 100}++ def test_purchase_orders_include_completed(self) -> None:+ # show_complete defaults to false server-side, which would silently drop+ # completed purchase orders from the warehouse table.+ params = _build_initial_params(+ VEEQO_ENDPOINTS["purchase_orders"],+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ incremental_field=None,+ )+ assert params["show_complete"] == "true"+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("ok", 200, True),+ ("unauthorized", 401, False),+ ("forbidden", 403, False),+ ("server_error", 500, False),+ ]+ )+ @mock.patch(VEEQO_SESSION_PATCH)+ def test_status_mapping(+ self, _name: str, status_code: int, expected_ok: bool, mock_session: mock.MagicMock+ ) -> None:+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=status_code)+ ok, error = validate_credentials("key")+ assert ok is expected_ok+ if not expected_ok:+ assert error is not None++ @mock.patch(VEEQO_SESSION_PATCH)+ def test_network_error_returns_false(self, mock_session: mock.MagicMock) -> None:+ mock_session.return_value.get.side_effect = Exception("boom")+ ok, error = validate_credentials("key")+ assert ok is False+ assert error is not None++ @mock.patch(VEEQO_SESSION_PATCH)+ def test_key_is_redacted_from_captured_samples(self, mock_session: mock.MagicMock) -> None:+ # `x-api-key` isn't in the shared auth-header denylist, so the key must be+ # passed as a `redact_values` literal to keep it out of captured HTTP samples.+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)+ validate_credentials("secret-key")+ assert mock_session.call_args.kwargs["redact_values"] == ("secret-key",)+++class TestPagination:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_paginates_and_saves_state_after_each_non_terminal_page(self, MockSession) -> None:+ session = MockSession.return_value+ params = _wire(+ session,+ [+ _response(_full_page(), headers={"X-Total-Pages-Count": "2"}),+ _response([{"id": 900}], headers={"X-Total-Pages-Count": "2"}),+ ],+ )++ manager = _make_manager()+ rows = _rows(veeqo_source("key", "orders", team_id=1, job_id="j", resumable_source_manager=manager))++ assert len(rows) == 101+ assert [p["page"] for p in params] == [1, 2]+ assert params[0]["page_size"] == 100+ # State saved once — only while a next page remains to resume from.+ manager.save_state.assert_called_once()+ assert manager.save_state.call_args.args[0] == VeeqoResumeConfig(endpoint="orders", page=2)++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_resumes_from_saved_page_when_endpoint_matches(self, MockSession) -> None:+ session = MockSession.return_value+ params = _wire(session, [_response([{"id": 1}])])++ manager = _make_manager(VeeqoResumeConfig(endpoint="orders", page=7))+ _rows(veeqo_source("key", "orders", team_id=1, job_id="j", resumable_source_manager=manager))++ assert params[0]["page"] == 7++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_ignores_resume_state_from_different_endpoint(self, MockSession) -> None:+ session = MockSession.return_value+ params = _wire(session, [_response([{"id": 1}])])++ manager = _make_manager(VeeqoResumeConfig(endpoint="orders", page=7))+ _rows(veeqo_source("key", "products", team_id=1, job_id="j", resumable_source_manager=manager))++ assert params[0]["page"] == 1++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_incremental_first_page_sends_min_filter_on_every_page(self, MockSession) -> None:+ session = MockSession.return_value+ params = _wire(+ session,+ [+ _response(_full_page(), headers={"X-Total-Pages-Count": "2"}),+ _response([{"id": 900}]),+ ],+ )++ _rows(+ veeqo_source(+ "key",+ "orders",+ team_id=1,+ job_id="j",+ resumable_source_manager=_make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),+ incremental_field="updated_at",+ )+ )++ # The filter must stay on every page — the paginator only advances `page`.+ assert all(p["updated_at_min"] == "2026-01-01 00:00:00" for p in params)++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_tags_fetches_a_single_unpaginated_page(self, MockSession) -> None:+ # `/tags` documents no pagination params. If the API ignores `page` and an+ # account has page_size-or-more tags, a page-number paginator would refetch+ # the same full list forever — tags must issue exactly one request, without+ # pagination params.+ session = MockSession.return_value+ params = _wire(session, [_response(_full_page(150))])++ manager = _make_manager()+ rows = _rows(veeqo_source("key", "tags", team_id=1, job_id="j", resumable_source_manager=manager))++ assert len(rows) == 150+ assert session.send.call_count == 1+ assert "page" not in params[0]+ assert "page_size" not in params[0]+ manager.save_state.assert_not_called()++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_redirects_are_refused(self, MockSession) -> None:+ # requests preserves the custom x-api-key header across redirects, so a+ # redirect response could replay the full-account key to another host —+ # every sync request must be sent with redirects disabled.+ session = MockSession.return_value+ _wire(session, [_response([{"id": 1}])])++ _rows(veeqo_source("key", "orders", team_id=1, job_id="j", resumable_source_manager=_make_manager()))++ assert session.send.call_args.kwargs["allow_redirects"] is False++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_non_list_body_fails_loud(self, MockSession) -> None:+ # Veeqo list responses are documented as bare arrays; a wrapper object on a+ # 200 means the response shape changed and must not sync as a single row.+ session = MockSession.return_value+ _wire(session, [_response({"orders": [{"id": 1}]})])++ with pytest.raises(ValueError, match="list"):+ _rows(veeqo_source("key", "orders", team_id=1, job_id="j", resumable_source_manager=_make_manager()))++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_api_key_is_redacted_from_captured_samples(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(session, [_response([{"id": 1}])])++ _rows(veeqo_source("secret-key", "orders", team_id=1, job_id="j", resumable_source_manager=_make_manager()))+ # The framework api_key auth exposes the key via secret_values(), which the+ # tracked session receives as redact_values.+ assert "secret-key" in MockSession.call_args.kwargs["redact_values"]+++class TestVeeqoSourceResponse:+ @parameterized.expand([(name,) for name in VEEQO_ENDPOINTS])+ def test_source_response_shape(self, endpoint: str) -> None:+ response = veeqo_source(+ "key",+ endpoint,+ team_id=1,+ job_id="j",+ resumable_source_manager=_make_manager(),+ )+ config = VEEQO_ENDPOINTS[endpoint]+ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ # Veeqo documents no list ordering, so the watermark must only commit after+ # a successful sync (desc semantics) — asc would checkpoint ≈now mid-sync.+ assert response.sort_mode == "desc"+ if config.partition_key:+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [config.partition_key]+ else:+ assert response.partition_mode is None+ assert response.partition_keys is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/veeqo/tests/test_veeqo_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/veeqo/tests/test_veeqo_source.pynew file mode 100644index 000000000000..0cab3835e7fd--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/veeqo/tests/test_veeqo_source.py@@ -0,0 +1,131 @@+from unittest.mock import MagicMock, patch++import requests++from posthog.schema import SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.veeqo import VeeqoSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.veeqo.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.veeqo.source import VeeqoSource+from products.warehouse_sources.backend.temporal.data_imports.sources.veeqo.veeqo import VeeqoResumeConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _config(api_key: str = "test-key") -> VeeqoSourceConfig:+ return VeeqoSourceConfig(api_key=api_key)+++class TestVeeqoSourceType:+ def test_source_type(self) -> None:+ assert VeeqoSource().source_type == ExternalDataSourceType.VEEQO+++class TestVeeqoSourceConfigFields:+ def test_exposes_required_secret_api_key(self) -> None:+ cfg = VeeqoSource().get_source_config++ assert cfg.unreleasedSource is None+ names = {f.name for f in cfg.fields}+ assert names == {"api_key"}++ api_key_field = next(f for f in cfg.fields if f.name == "api_key")+ assert isinstance(api_key_field, SourceFieldInputConfig)+ assert api_key_field.required is True+ assert api_key_field.secret is True+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD+++class TestVeeqoSourceGetSchemas:+ def test_lists_every_endpoint(self) -> None:+ schemas = VeeqoSource().get_schemas(_config(), team_id=1)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ def test_incremental_support_matches_settings(self) -> None:+ schemas = VeeqoSource().get_schemas(_config(), team_id=1)+ for schema in schemas:+ expected = schema.name in INCREMENTAL_FIELDS+ assert schema.supports_incremental is expected+ assert schema.supports_append is expected++ def test_filters_by_names(self) -> None:+ schemas = VeeqoSource().get_schemas(_config(), team_id=1, names=["orders", "products"])+ assert {s.name for s in schemas} == {"orders", "products"}+++class TestVeeqoSourceValidateCredentials:+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.veeqo.source.validate_veeqo_credentials")+ def test_delegates_to_client(self, mock_validate: MagicMock) -> None:+ mock_validate.return_value = (True, None)+ ok, error = VeeqoSource().validate_credentials(_config("key"), team_id=1)+ assert ok is True+ assert error is None+ mock_validate.assert_called_once_with("key")+++class TestVeeqoSourceNonRetryableErrors:+ def test_http_error_message_format_matches_patterns(self) -> None:+ # The patterns must match the exact message `raise_for_status` produces,+ # otherwise auth failures retry forever instead of failing permanently.+ for status, reason in ((401, "Unauthorized"), (403, "Forbidden")):+ response = requests.Response()+ response.status_code = status+ response.reason = reason+ response.url = "https://api.veeqo.com/orders?page=1"++ try:+ response.raise_for_status()+ raise AssertionError("raise_for_status did not raise")+ except requests.HTTPError as e:+ error_msg = str(e)++ patterns = VeeqoSource().get_non_retryable_errors()+ assert any(pattern in error_msg for pattern in patterns), (+ f"HTTPError message '{error_msg}' did not match any non-retryable pattern"+ )+++class TestVeeqoSourceResumableManager:+ def test_returns_manager_bound_to_resume_config(self) -> None:+ manager = VeeqoSource().get_resumable_source_manager(MagicMock())+ assert manager._data_class is VeeqoResumeConfig+++class TestVeeqoSourcePipelinePlumbing:+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.veeqo.source.veeqo_source")+ def test_passes_through_inputs(self, mock_veeqo_source: MagicMock) -> None:+ sentinel = object()+ mock_veeqo_source.return_value = sentinel++ inputs = MagicMock()+ inputs.schema_name = "orders"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-01-01 00:00:00"+ inputs.incremental_field = "updated_at"++ manager = MagicMock()+ result = VeeqoSource().source_for_pipeline(_config("key"), manager, inputs)++ assert result is sentinel+ kwargs = mock_veeqo_source.call_args.kwargs+ assert kwargs["api_key"] == "key"+ assert kwargs["endpoint"] == "orders"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01 00:00:00"+ assert kwargs["incremental_field"] == "updated_at"++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.veeqo.source.veeqo_source")+ def test_clears_last_value_when_not_incremental(self, mock_veeqo_source: MagicMock) -> None:+ inputs = MagicMock()+ inputs.schema_name = "customers"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2026-01-01 00:00:00"+ inputs.incremental_field = None++ VeeqoSource().source_for_pipeline(_config("key"), MagicMock(), inputs)++ kwargs = mock_veeqo_source.call_args.kwargs+ assert kwargs["db_incremental_field_last_value"] is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/veeqo/veeqo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/veeqo/veeqo.pynew file mode 100644index 000000000000..b3ee78109845--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/veeqo/veeqo.py@@ -0,0 +1,275 @@+"""Veeqo API client used by the data warehouse source.++Spec: https://developers.veeqo.com/api++Veeqo is a multichannel ecommerce inventory, order and shipping management+platform. The API is pure REST/JSON with API-key auth (`x-api-key` header),+page-number pagination (`page` / `page_size`, with `X-Total-Pages-Count` /+`X-Total-Count` response headers), and server-side filters (`updated_at_min` /+`created_at_min` / `since_id`) on orders and products for incremental syncs.++Built on the shared ``rest_source`` framework: the framework ``api_key`` auth+carries the token in the ``x-api-key`` header and redacts it from logs and+error messages, and a small paginator extends the framework page-number+paginator with Veeqo's total-pages header and a short-page stop.++NOTE: these endpoint params were taken from the public API docs and could not+be curl-verified against a live account during implementation (Veeqo API keys+must be enabled by their support team). The pagination/filter handling is+intentionally conservative — see inline comments where behavior is assumed+rather than confirmed.+"""++import dataclasses+from datetime import UTC, date, datetime+from typing import Any, Optional++from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ PageNumberPaginator,+ SinglePagePaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe+from products.warehouse_sources.backend.temporal.data_imports.sources.veeqo.settings import (+ VEEQO_ENDPOINTS,+ VeeqoEndpointConfig,+)++VEEQO_BASE_URL = "https://api.veeqo.com"++# User-chosen incremental field -> the documented server-side filter param it maps to.+INCREMENTAL_PARAM_BY_FIELD = {+ "updated_at": "updated_at_min",+ "created_at": "created_at_min",+ "id": "since_id",+}+++class VeeqoResumeConfig:+ """Page cursor for resumable list iteration.++ ``page`` is the next page to fetch. ``endpoint`` scopes the state to a single+ endpoint so we never replay an orders page number against products.+ """++ endpoint: str+ page: int+++class VeeqoPaginator(PageNumberPaginator):+ """Page-number pagination for Veeqo list endpoints (1-based ``page`` param).++ Extends the framework paginator with two extra stop conditions:++ - the ``X-Total-Pages-Count`` response header, so the terminal page doesn't+ cost one extra empty-page request;+ - a short (partial) page, which is always the last page for offset-backed+ page-number pagination.++ Endpoints that document no pagination params at all (``/tags``) must not use+ this paginator — they're configured ``single_page`` instead, because an API+ that ignores ``page`` and returns ``page_size``-or-more rows would loop on+ the same full list forever.+ """++ def __init__(self, page_size: int) -> None:+ super().__init__(base_page=1, page_param="page", stop_after_empty_page=True)+ self.page_size = page_size++ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:+ super().update_state(response, data)+ if not self._has_next_page:+ return++ # After super().update_state, self.page points at the NEXT page to fetch.+ total_pages_header = response.headers.get("X-Total-Pages-Count")+ if total_pages_header is not None:+ try:+ if self.page > int(total_pages_header):+ self._has_next_page = False+ return+ except (TypeError, ValueError):+ pass++ if data is not None and len(data) < self.page_size:+ self._has_next_page = False++ def __str__(self) -> str:+ return f"VeeqoPaginator(page={self.page}, page_size={self.page_size})"+++def _format_incremental_value(incremental_field: str, value: Any) -> Any:+ """Format an incremental cursor value for Veeqo's server-side filters.++ ``updated_at_min`` / ``created_at_min`` expect ``YYYY-MM-DD HH:MM:SS``; the+ docs don't state a timezone, so we normalize to UTC (Veeqo returns UTC+ timestamps) to keep behavior deterministic. ``since_id`` expects an integer.+ """+ if incremental_field == "id":+ return int(value)+ if isinstance(value, datetime):+ utc_dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ return utc_dt.strftime("%Y-%m-%d %H:%M:%S")+ if isinstance(value, date):+ return value.strftime("%Y-%m-%d 00:00:00")+ return str(value)+++def _build_initial_params(+ config: VeeqoEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ incremental_field: str | None,+) -> dict[str, Any]:+ """Query params for the first page (the paginator only advances ``page``)."""+ # Single-page endpoints document no pagination params, so none are sent.+ params: dict[str, Any] = {} if config.single_page else {"page_size": config.page_size}+ params.update(config.extra_params)++ use_incremental = (+ config.supports_incremental+ and should_use_incremental_field+ and incremental_field in INCREMENTAL_PARAM_BY_FIELD+ and db_incremental_field_last_value is not None+ )++ if use_incremental and incremental_field is not None:+ params[INCREMENTAL_PARAM_BY_FIELD[incremental_field]] = _format_incremental_value(+ incremental_field, db_incremental_field_last_value+ )++ return params+++def validate_credentials(api_key: str) -> tuple[bool, str | None]:+ """Probe ``/warehouses`` — a cheap list call every account can serve.++ Veeqo API keys carry full account access (no scopes), so one probe confirms+ the key. A 401 means the key is invalid or not yet enabled by Veeqo support.+ """+ ok, status = validate_via_probe(+ lambda: make_tracked_session(redact_values=(api_key,)),+ f"{VEEQO_BASE_URL}/warehouses?page_size=1&page=1",+ headers={"x-api-key": api_key, "Accept": "application/json"},+ allow_redirects=False,+ )+ if ok:+ return True, None+ if status == 401:+ return False, (+ "Invalid Veeqo API key. Check the key in your Veeqo account settings — "+ "Veeqo support must enable API access before a key appears there."+ )+ if status is None:+ return False, "Could not reach Veeqo. Please check your connection and try again."+ return False, f"Veeqo rejected the request (HTTP {status})."+++def veeqo_source(+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[VeeqoResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ config = VEEQO_ENDPOINTS[endpoint]++ params = _build_initial_params(+ config, should_use_incremental_field, db_incremental_field_last_value, incremental_field+ )++ rest_config: RESTAPIConfig = {+ "client": {+ "base_url": VEEQO_BASE_URL,+ "headers": {"Accept": "application/json"},+ # api_key auth injects the key into the `x-api-key` header and redacts+ # it from logs and raised error messages.+ "auth": {+ "type": "api_key",+ "api_key": api_key,+ "name": "x-api-key",+ "location": "header",+ },+ # requests preserves the custom x-api-key header when following a+ # redirect, so a redirect response could replay the full-account key+ # to another host — refuse redirects outright.+ "allow_redirects": False,+ },+ "resource_defaults": {+ "write_disposition": {+ "disposition": "merge",+ "strategy": "upsert",+ }+ if should_use_incremental_field+ else "replace",+ },+ "resources": [+ {+ "name": endpoint,+ "table_name": endpoint,+ "endpoint": {+ "path": config.path,+ "params": params,+ # Veeqo list responses are bare JSON arrays (no wrapper key) —+ # fail loud if the response shape ever changes.+ "data_selector_required": True,+ "paginator": SinglePagePaginator()+ if config.single_page+ else VeeqoPaginator(page_size=config.page_size),+ },+ "table_format": "delta",+ }+ ],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume = resumable_source_manager.load_state()+ # Only replay a page number saved for THIS endpoint.+ if resume is not None and resume.endpoint == endpoint:+ initial_paginator_state = {"page": resume.page}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Persist only when a next page remains; the hook fires AFTER a page is+ # yielded so a crash re-yields the last page (merge dedupes) rather than+ # skipping it.+ if state and state.get("page"):+ resumable_source_manager.save_state(VeeqoResumeConfig(endpoint=endpoint, page=int(state["page"])))++ resource = rest_api_resource(+ rest_config,+ team_id,+ job_id,+ db_incremental_field_last_value,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )++ return SourceResponse(+ name=endpoint,+ items=lambda: resource,+ primary_keys=["id"],+ 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,+ # Veeqo documents no sort param and no ordering guarantee for list+ # endpoints, so declare "desc": the incremental watermark then commits+ # only after a successful sync instead of checkpointing per batch, which+ # is safe whatever order rows actually arrive in.+ sort_mode="desc",+ column_hints=resource.column_hints,+ )