Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): implement picqer import source (#67838)

Tom Owers146b88ebf236
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 20c4d6b4235c..269caae187e0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -248,6 +248,7 @@ the row lists both.
| persona | HTTP | requests | ✅ |
| personio | HTTP | requests | ✅ |
| pexels | HTTP | requests | ✅ |
+| picqer | HTTP | requests | ✅ |
| pingdom | HTTP | requests | ✅ |
| pinterest_ads | HTTP | requests | ✅ |
| pipedrive | HTTP | requests | ✅ |
@@ -580,7 +581,6 @@ doesn't conflict with concurrent PRs.
- persona
- pexels
- phyllo
-- picqer
- pipeliner
- pivotal_tracker
- piwik
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index e7999de961e6..59f4cd8f9c85 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
@@ -2469,7 +2469,8 @@ class PhylloSourceConfig(config.Config):
@config.config
class PicqerSourceConfig(config.Config):
- pass
+ account_name: str
+ api_key: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/picqer/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/picqer/canonical_descriptions.py
new file mode 100644
index 000000000000..c8a778047fa9
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/picqer/canonical_descriptions.py
@@ -0,0 +1,159 @@
+"""Canonical, documentation-sourced descriptions for Picqer endpoints and columns.
+
+Sourced from the official Picqer API reference (https://picqer.com/en/api). Keyed by the endpoint
+names in `settings.py` `PICQER_ENDPOINTS`, which match the `ExternalDataSchema.name` of a synced
+Picqer table. Columns absent here fall back to LLM enrichment.
+"""
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+_DOCS = "https://picqer.com/en/api"
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "orders": {
+ "description": "A sales order in Picqer, containing the products a customer ordered and their fulfilment state.",
+ "docs_url": f"{_DOCS}/orders",
+ "columns": {
+ "idorder": "Unique Picqer reference for the order.",
+ "orderid": "Per-account order number.",
+ "idcustomer": "Reference to the customer the order belongs to.",
+ "reference": "External reference for the order.",
+ "status": "Current status of the order (e.g. concept, expected, processing, completed, cancelled).",
+ "created": "Datetime the order was created.",
+ "updated": "Datetime the order was last changed.",
+ },
+ },
+ "picklists": {
+ "description": "A picklist — the set of products to pick from stock to fulfil one or more orders.",
+ "docs_url": f"{_DOCS}/picklists",
+ "columns": {
+ "idpicklist": "Unique Picqer reference for the picklist.",
+ "picklistid": "Per-account picklist number.",
+ "idorder": "Reference to the order this picklist fulfils.",
+ "idwarehouse": "Reference to the warehouse the picklist is picked from.",
+ "status": "Current status of the picklist.",
+ "created": "Datetime the picklist was created.",
+ },
+ },
+ "purchaseorders": {
+ "description": "A purchase order sent to a supplier to replenish stock.",
+ "docs_url": f"{_DOCS}/purchaseorders",
+ "columns": {
+ "idpurchaseorder": "Unique Picqer reference for the purchase order.",
+ "purchaseorderid": "Per-account purchase order number.",
+ "idsupplier": "Reference to the supplier the purchase order is placed with.",
+ "idwarehouse": "Reference to the warehouse the goods are received into.",
+ "status": "Current status of the purchase order.",
+ "created": "Datetime the purchase order was created.",
+ "updated": "Datetime the purchase order was last changed.",
+ },
+ },
+ "receipts": {
+ "description": "A receipt recording the goods received against a purchase order.",
+ "docs_url": f"{_DOCS}/receipts",
+ "columns": {
+ "idreceipt": "Unique Picqer reference for the receipt.",
+ "receiptid": "Per-account receipt number.",
+ "idpurchaseorder": "Reference to the purchase order the receipt belongs to.",
+ "idwarehouse": "Reference to the warehouse the goods were received into.",
+ "status": "Current status of the receipt.",
+ "created": "Datetime the receipt was created.",
+ },
+ },
+ "returns": {
+ "description": "A return (RMA) of products a customer sent back.",
+ "docs_url": f"{_DOCS}/returns",
+ "columns": {
+ "idreturn": "Unique Picqer reference for the return.",
+ "returnid": "Per-account return number.",
+ "idcustomer": "Reference to the customer the return belongs to.",
+ "status": "Current status of the return.",
+ "created_at": "Datetime the return was created.",
+ "updated_at": "Datetime the return was last changed.",
+ },
+ },
+ "products": {
+ "description": "A product in the Picqer catalog, including its stock and supplier information.",
+ "docs_url": f"{_DOCS}/products",
+ "columns": {
+ "idproduct": "Unique Picqer reference for the product.",
+ "productcode": "The product's SKU / product code.",
+ "name": "The product's name.",
+ "price": "Sales price of the product.",
+ "fixedstockprice": "Fixed stock price of the product.",
+ "idsupplier": "Reference to the product's default supplier.",
+ "created": "Datetime the product was created.",
+ "updated": "Datetime the product was last changed.",
+ },
+ },
+ "customers": {
+ "description": "A customer record in Picqer.",
+ "docs_url": f"{_DOCS}/customers",
+ "columns": {
+ "idcustomer": "Unique Picqer reference for the customer.",
+ "customerid": "Per-account customer number.",
+ "name": "The customer's name.",
+ "contactname": "Name of the primary contact.",
+ "emailaddress": "The customer's email address.",
+ },
+ },
+ "suppliers": {
+ "description": "A supplier products can be purchased from.",
+ "docs_url": f"{_DOCS}/suppliers",
+ "columns": {
+ "idsupplier": "Unique Picqer reference for the supplier.",
+ "name": "The supplier's name.",
+ },
+ },
+ "warehouses": {
+ "description": "A warehouse where stock is held and orders are fulfilled.",
+ "docs_url": f"{_DOCS}/warehouses",
+ "columns": {
+ "idwarehouse": "Unique Picqer reference for the warehouse.",
+ "name": "The warehouse's name.",
+ "accept_orders": "Whether the warehouse accepts new orders.",
+ "priority": "Priority used when allocating stock across warehouses.",
+ "active": "Whether the warehouse is active.",
+ },
+ },
+ "locations": {
+ "description": "A physical stock location within a warehouse.",
+ "docs_url": f"{_DOCS}/locations",
+ "columns": {
+ "idlocation": "Unique Picqer reference for the location.",
+ "name": "The location's name / code.",
+ "idwarehouse": "Reference to the warehouse the location belongs to.",
+ },
+ },
+ "users": {
+ "description": "A user account in the Picqer application.",
+ "docs_url": f"{_DOCS}/users",
+ "columns": {
+ "iduser": "Unique Picqer reference for the user.",
+ "firstname": "The user's first name.",
+ "lastname": "The user's last name.",
+ "emailaddress": "The user's email address.",
+ "active": "Whether the user account is active.",
+ },
+ },
+ "vatgroups": {
+ "description": "A VAT (tax) group applied to products and orders.",
+ "docs_url": f"{_DOCS}/vatgroups",
+ "columns": {
+ "idvatgroup": "Unique Picqer reference for the VAT group.",
+ "name": "The VAT group's name.",
+ "percentage": "The VAT percentage.",
+ },
+ },
+ "tags": {
+ "description": "A tag that can be attached to orders, customers, and other records.",
+ "docs_url": f"{_DOCS}/tags",
+ "columns": {
+ "idtag": "Unique Picqer reference for the tag.",
+ "title": "The tag's title.",
+ "color": "The tag's display color.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/picqer/picqer.py b/products/warehouse_sources/backend/temporal/data_imports/sources/picqer/picqer.py
new file mode 100644
index 000000000000..648fea2bcd7b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/picqer/picqer.py
@@ -0,0 +1,191 @@
+import re
+import dataclasses
+from collections.abc import Iterator
+from datetime import date, datetime
+from typing import Any, Optional
+
+from requests import Session
+from requests.exceptions import RequestException
+from structlog.types import FilteringBoundLogger
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.picqer.settings import (
+ PAGE_SIZE,
+ PICQER_ENDPOINTS,
+ PicqerEndpointConfig,
+)
+
+PICQER_API_PATH = "/api/v1"
+
+# Picqer requires a descriptive User-Agent identifying the application plus contact info.
+PICQER_USER_AGENT = "PostHog (https://posthog.com - [email protected])"
+
+# A single DNS label: letters, digits, hyphens. Rejects anything that could retarget the host
+# (slashes, `@`, dots) so the stored API key is only ever sent to `<account>.picqer.com`.
+_ACCOUNT_RE = re.compile(r"^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?$")
+
+
+class PicqerResumeConfig:
+ # Next offset to fetch. None means "start from offset 0".
+ offset: int | None = None
+
+
+def normalize_account(account: str) -> str:
+ """Reduce user input to a bare, validated Picqer account subdomain.
+
+ Accepts either the full host (``yourcompany.picqer.com``) or the bare subdomain
+ (``yourcompany``). Raises ``ValueError`` on anything that isn't a single DNS label so the
+ API key can never be retargeted away from ``<account>.picqer.com``.
+ """
+ cleaned = account.strip().removeprefix("https://").removeprefix("http://")
+ cleaned = cleaned.strip("/")
+ cleaned = cleaned.removesuffix(".picqer.com")
+ if not _ACCOUNT_RE.match(cleaned):
+ raise ValueError(
+ f"Invalid Picqer account: {account!r}. Enter just your account name, e.g. 'yourcompany' "
+ "for yourcompany.picqer.com."
+ )
+ return cleaned
+
+
+def _base_url(account: str) -> str:
+ return f"https://{normalize_account(account)}.picqer.com{PICQER_API_PATH}"
+
+
+def to_picqer_datetime(value: Any) -> str:
+ """Format an incremental cursor value into Picqer's ``YYYY-MM-DD HH:MM:SS`` filter format.
+
+ The persisted last value arrives as a ``datetime`` for DateTime incremental fields. Picqer's
+ timestamps carry no timezone, so we format the wall-clock components directly (no timezone
+ shift) to round-trip against the same values the API returned.
+ """
+ if isinstance(value, datetime):
+ return value.strftime("%Y-%m-%d %H:%M:%S")
+ if isinstance(value, date):
+ return datetime.combine(value, datetime.min.time()).strftime("%Y-%m-%d %H:%M:%S")
+ # Defensive: an ISO string ("2013-07-17T16:01:42") reduced to Picqer's space-separated form.
+ return str(value).replace("T", " ")[:19]
+
+
+def _make_session(api_key: str) -> Session:
+ session = make_tracked_session(redact_values=(api_key,))
+ session.headers.update({"User-Agent": PICQER_USER_AGENT, "Accept": "application/json"})
+ # Picqer uses HTTP Basic auth with the API key as the username and a blank password.
+ session.auth = (api_key, "")
+ return session
+
+
+def _fetch_page(session: Session, url: str, params: dict[str, Any]) -> Any:
+ """Fetch a single Picqer list page. Rate limits (429) and transient 5xx are retried by the
+ tracked session's adapter; a persistent auth/permission error raises via `raise_for_status`."""
+ response = session.get(url, params=params, timeout=60)
+ response.raise_for_status()
+ return response.json()
+
+
+def _build_params(
+ config: PicqerEndpointConfig,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> dict[str, Any]:
+ """Query params kept on every offset page. Picqer applies a filter server-side across the whole
+ result set, so the `updated_after` cursor narrows every page and pagination ends naturally. Only
+ endpoints with a genuine update-based filter are ever narrowed — full-refresh endpoints must
+ never leak a cursor into the request."""
+ params: dict[str, Any] = {}
+ if (
+ config.supports_incremental
+ and should_use_incremental_field
+ and db_incremental_field_last_value is not None
+ and config.incremental_filter_param is not None
+ ):
+ params[config.incremental_filter_param] = to_picqer_datetime(db_incremental_field_last_value)
+ return params
+
+
+def get_rows(
+ account: str,
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[PicqerResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = PICQER_ENDPOINTS[endpoint]
+ url = f"{_base_url(account)}{config.path}"
+ session = _make_session(api_key)
+
+ params = _build_params(config, should_use_incremental_field, db_incremental_field_last_value)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ offset = resume.offset if resume is not None and resume.offset is not None else 0
+ if offset:
+ logger.debug(f"Picqer: resuming {endpoint} from offset {offset}")
+
+ while True:
+ items = _fetch_page(session, url, {**params, "offset": offset})
+
+ if not isinstance(items, list) or not items:
+ break
+
+ yield items
+
+ # A short page means we've reached the end of the (optionally filtered) result set.
+ if len(items) < PAGE_SIZE:
+ break
+
+ offset += PAGE_SIZE
+ # Save AFTER yielding so a crash re-runs from the next page rather than losing the last one —
+ # merge dedupes on the primary key.
+ resumable_source_manager.save_state(PicqerResumeConfig(offset=offset))
+
+
+def picqer_source(
+ account: str,
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[PicqerResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = PICQER_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ account=account,
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ primary_keys=config.primary_keys,
+ 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,
+ )
+
+
+def validate_credentials(account: str, api_key: str) -> tuple[bool, int | None]:
+ """Probe a cheap Picqer list endpoint to confirm the API key is genuine.
+
+ Returns ``(ok, status_code)``. ``status_code`` is ``None`` on a transport error. Raises
+ ``ValueError`` if the account is malformed so the caller can surface a precise message. A
+ ``403`` (valid key, insufficient scope) is treated as reachable — fulfilment keys legitimately
+ have narrow scopes and per-table access is reported separately.
+ """
+ url = f"{_base_url(account)}/warehouses"
+ try:
+ response = _make_session(api_key).get(url, params={"offset": 0}, timeout=10)
+ except RequestException:
+ return False, None
+ return response.status_code in (200, 403), response.status_code
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/picqer/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/picqer/settings.py
new file mode 100644
index 000000000000..3e1fd8141d99
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/picqer/settings.py
@@ -0,0 +1,142 @@
+from dataclasses import dataclass
+from typing import Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# Picqer caps every list endpoint at 100 results per page and advances with the `offset`
+# query param. There is no `limit`/`per_page` override, so the page size is fixed.
+PAGE_SIZE = 100
+
+
+def _incremental_fields(cursor_field: str) -> list[IncrementalField]:
+ # Picqer's server-side time filters key off a single timestamp column per endpoint (the field
+ # the `updated_after` filter compares against). Advertise just that column so the user's chosen
+ # cursor always matches what the API actually filters on.
+ return [
+ {
+ "label": cursor_field,
+ "type": IncrementalFieldType.DateTime,
+ "field": cursor_field,
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ]
+
+
+@dataclass
+class PicqerEndpointConfig:
+ name: str
+ path: str # Path under /api/v1, e.g. "/orders"
+ primary_keys: list[str]
+ # Query param that filters the list by modification time (e.g. `updated_after`). Only set when
+ # the API documents a genuine server-side UPDATE-based filter — creation-only filters
+ # (`sincedate`) are deliberately left off, since using them as an incremental cursor would miss
+ # updates to mutable records. None => full refresh.
+ incremental_filter_param: Optional[str] = None
+ # Response field the `incremental_filter_param` compares against, and the cursor the pipeline
+ # tracks. Must be present in every row so the watermark can advance. None => full refresh.
+ incremental_cursor_field: Optional[str] = None
+ # Stable creation-time field to partition by (never `updated`, which rewrites partitions on every
+ # sync). None when the resource exposes no reliable creation timestamp.
+ partition_key: Optional[str] = None
+ should_sync_default: bool = True
+
+ @property
+ def supports_incremental(self) -> bool:
+ return self.incremental_filter_param is not None and self.incremental_cursor_field is not None
+
+ @property
+ def incremental_fields(self) -> list[IncrementalField]:
+ if self.incremental_cursor_field is None:
+ return []
+ return _incremental_fields(self.incremental_cursor_field)
+
+
+PICQER_ENDPOINTS: dict[str, PicqerEndpointConfig] = {
+ # Transactional resources. Orders and picklists only expose a creation-date filter (`sincedate`),
+ # which cannot catch status updates, so they sync full refresh. Purchase orders and returns
+ # expose an `updated_after` ("changed since") filter, so they sync incrementally.
+ "orders": PicqerEndpointConfig(
+ name="orders",
+ path="/orders",
+ primary_keys=["idorder"],
+ partition_key="created",
+ ),
+ "picklists": PicqerEndpointConfig(
+ name="picklists",
+ path="/picklists",
+ primary_keys=["idpicklist"],
+ partition_key="created",
+ ),
+ "purchaseorders": PicqerEndpointConfig(
+ name="purchaseorders",
+ path="/purchaseorders",
+ primary_keys=["idpurchaseorder"],
+ incremental_filter_param="updated_after",
+ incremental_cursor_field="updated",
+ partition_key="created",
+ ),
+ # Receipts document an `updated_after` filter, but the list object's update field isn't confirmed,
+ # so this stays full refresh until verified against the live API (see PR notes).
+ "receipts": PicqerEndpointConfig(
+ name="receipts",
+ path="/receipts",
+ primary_keys=["idreceipt"],
+ partition_key="created",
+ ),
+ "returns": PicqerEndpointConfig(
+ name="returns",
+ path="/returns",
+ primary_keys=["idreturn"],
+ incremental_filter_param="updated_after",
+ incremental_cursor_field="updated_at",
+ partition_key="created_at",
+ ),
+ # Catalog / reference resources. Products carry a `created` field but expose no time filter.
+ "products": PicqerEndpointConfig(
+ name="products",
+ path="/products",
+ primary_keys=["idproduct"],
+ partition_key="created",
+ ),
+ "customers": PicqerEndpointConfig(
+ name="customers",
+ path="/customers",
+ primary_keys=["idcustomer"],
+ ),
+ "suppliers": PicqerEndpointConfig(
+ name="suppliers",
+ path="/suppliers",
+ primary_keys=["idsupplier"],
+ ),
+ "warehouses": PicqerEndpointConfig(
+ name="warehouses",
+ path="/warehouses",
+ primary_keys=["idwarehouse"],
+ ),
+ "locations": PicqerEndpointConfig(
+ name="locations",
+ path="/locations",
+ primary_keys=["idlocation"],
+ ),
+ "users": PicqerEndpointConfig(
+ name="users",
+ path="/users",
+ primary_keys=["iduser"],
+ ),
+ "vatgroups": PicqerEndpointConfig(
+ name="vatgroups",
+ path="/vatgroups",
+ primary_keys=["idvatgroup"],
+ ),
+ "tags": PicqerEndpointConfig(
+ name="tags",
+ path="/tags",
+ primary_keys=["idtag"],
+ ),
+}
+
+ENDPOINTS = tuple(PICQER_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in PICQER_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/picqer/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/picqer/source.py
index 3c6388e54348..a60dc7274223 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/picqer/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/picqer/source.py
@@ -1,30 +1,157 @@
-from typing import cast
+from typing import Optional, cast
from 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
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import PicqerSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.picqer.picqer import (
+ PicqerResumeConfig,
+ picqer_source,
+ validate_credentials as validate_picqer_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.picqer.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ PICQER_ENDPOINTS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class PicqerSource(SimpleSource[PicqerSourceConfig]):
+class PicqerSource(ResumableSource[PicqerSourceConfig, PicqerResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.PICQER
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # The API key is sent to `<account_name>.picqer.com`, so changing the account must re-require it.
+ return ["account_name"]
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # 401/403 surface as a requests HTTPError when the transport calls `raise_for_status()`.
+ # Retrying can never fix a credential/permission problem, so fail the sync.
+ "401 Client Error: Unauthorized": "Your Picqer API key is invalid or has been revoked. Create a new key in Settings → API keys, then reconnect.",
+ "403 Client Error: Forbidden": "Your Picqer API key is missing the permissions needed to sync this data. Check the key's scope, then reconnect.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.picqer.canonical_descriptions import ( # noqa: PLC0415
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: PicqerSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ def _build_schema(endpoint: str) -> SourceSchema:
+ endpoint_config = PICQER_ENDPOINTS[endpoint]
+ return SourceSchema(
+ name=endpoint,
+ supports_incremental=endpoint_config.supports_incremental,
+ supports_append=endpoint_config.supports_incremental,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ should_sync_default=endpoint_config.should_sync_default,
+ )
+
+ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: PicqerSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ try:
+ ok, status_code = validate_picqer_credentials(config.account_name, config.api_key)
+ except ValueError as e:
+ return False, str(e)
+
+ if ok:
+ return True, None
+ if status_code == 401:
+ return False, "Invalid Picqer API key"
+ return False, "Could not connect to Picqer with the provided account name and API key"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[PicqerResumeConfig]:
+ return ResumableSourceManager[PicqerResumeConfig](inputs, PicqerResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: PicqerSourceConfig,
+ resumable_source_manager: ResumableSourceManager[PicqerResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return picqer_source(
+ account=config.account_name,
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.PICQER,
category=DataWarehouseSourceCategory.E_COMMERCE,
label="Picqer",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Picqer account name and API key to pull your Picqer warehouse and fulfilment data into the PostHog Data warehouse.
+
+Create an API key under **Settings → API keys** in your Picqer account. The key inherits its permissions from its scope, so it can read the records that scope allows.""",
iconPath="/static/services/picqer.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/picqer",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="account_name",
+ label="Account name",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="yourcompany",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/picqer/tests/test_picqer.py b/products/warehouse_sources/backend/temporal/data_imports/sources/picqer/tests/test_picqer.py
new file mode 100644
index 000000000000..edd21678046a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/picqer/tests/test_picqer.py
@@ -0,0 +1,196 @@
+from datetime import date, datetime
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock
+
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.picqer import picqer
+from products.warehouse_sources.backend.temporal.data_imports.sources.picqer.picqer import (
+ PicqerResumeConfig,
+ _base_url,
+ _build_params,
+ get_rows,
+ normalize_account,
+ to_picqer_datetime,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.picqer.settings import PAGE_SIZE, PICQER_ENDPOINTS
+
+
+class TestNormalizeAccount:
+ @parameterized.expand(
+ [
+ ("bare", "acme", "acme"),
+ ("full_host", "acme.picqer.com", "acme"),
+ ("https_url", "https://acme.picqer.com", "acme"),
+ ("trailing_slash", "acme.picqer.com/", "acme"),
+ ("with_hyphen", "acme-corp", "acme-corp"),
+ ("whitespace", " acme ", "acme"),
+ ]
+ )
+ def test_valid_accounts(self, _name: str, value: str, expected: str) -> None:
+ assert normalize_account(value) == expected
+
+ @parameterized.expand(
+ [
+ ("path_injection", "acme/../evil"),
+ ("host_injection", "acme.evil.com"),
+ ("userinfo_injection", "[email protected]"),
+ ("empty", ""),
+ ("space_inside", "ac me"),
+ ("trailing_hyphen", "acme-"),
+ ]
+ )
+ def test_invalid_accounts_raise(self, _name: str, value: str) -> None:
+ # The account is the host the stored API key is sent to; a loosened regex would let an org
+ # member retarget the credential at a server they control.
+ with pytest.raises(ValueError):
+ normalize_account(value)
+
+ def test_base_url(self) -> None:
+ assert _base_url("acme") == "https://acme.picqer.com/api/v1"
+
+
+class TestToPicqerDatetime:
+ @parameterized.expand(
+ [
+ ("naive_datetime", datetime(2020, 1, 2, 3, 4, 5), "2020-01-02 03:04:05"),
+ ("date_value", date(2020, 1, 2), "2020-01-02 00:00:00"),
+ ("iso_string", "2020-01-02T03:04:05", "2020-01-02 03:04:05"),
+ ("already_spaced_string", "2020-01-02 03:04:05", "2020-01-02 03:04:05"),
+ ]
+ )
+ def test_format(self, _name: str, value: Any, expected: str) -> None:
+ # Picqer's `updated_after` filter expects `YYYY-MM-DD HH:MM:SS`; a broken format silently
+ # returns wrong/empty incremental pages.
+ assert to_picqer_datetime(value) == expected
+
+
+class TestBuildParams:
+ def test_incremental_endpoint_adds_filter(self) -> None:
+ params = _build_params(
+ PICQER_ENDPOINTS["purchaseorders"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2020, 1, 2, 3, 4, 5),
+ )
+ assert params == {"updated_after": "2020-01-02 03:04:05"}
+
+ def test_incremental_endpoint_without_cursor_omits_filter(self) -> None:
+ params = _build_params(
+ PICQER_ENDPOINTS["purchaseorders"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=None,
+ )
+ assert params == {}
+
+ def test_full_refresh_endpoint_never_filters(self) -> None:
+ # orders exposes only a creation-date filter (`sincedate`), so it syncs full refresh; a
+ # cursor must never leak into the request and silently drop updated rows.
+ params = _build_params(
+ PICQER_ENDPOINTS["orders"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2020, 1, 2, 3, 4, 5),
+ )
+ assert params == {}
+
+
+class _FakeResumableManager:
+ def __init__(self, state: PicqerResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[PicqerResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> PicqerResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: PicqerResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _patch_fetch(monkeypatch: Any, responses: list[Any]) -> list[dict[str, Any]]:
+ """Return pages in order, recording the params (offset + any filter) of each request."""
+ calls: list[dict[str, Any]] = []
+ pages = iter(responses)
+
+ def fake_fetch(session: Any, url: str, params: dict[str, Any]) -> Any:
+ calls.append(params)
+ return next(pages)
+
+ monkeypatch.setattr(picqer, "_fetch_page", fake_fetch)
+ monkeypatch.setattr(picqer, "_make_session", lambda api_key: MagicMock())
+ return calls
+
+
+def _collect(monkeypatch: Any, manager: _FakeResumableManager, **kwargs: Any) -> list[dict]:
+ rows: list[dict] = []
+ for batch in get_rows(
+ account="acme",
+ api_key="key",
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ **kwargs,
+ ):
+ rows.extend(batch)
+ return rows
+
+
+def _page(n: int) -> list[dict]:
+ return [{"idorder": i} for i in range(n)]
+
+
+class TestGetRows:
+ def test_paginates_by_offset_until_short_page(self, monkeypatch: Any) -> None:
+ calls = _patch_fetch(monkeypatch, [_page(PAGE_SIZE), _page(3)])
+ rows = _collect(monkeypatch, _FakeResumableManager(), endpoint="orders")
+
+ assert len(rows) == PAGE_SIZE + 3
+ assert [c["offset"] for c in calls] == [0, PAGE_SIZE]
+
+ def test_stops_on_empty_first_page(self, monkeypatch: Any) -> None:
+ calls = _patch_fetch(monkeypatch, [[]])
+ rows = _collect(monkeypatch, _FakeResumableManager(), endpoint="orders")
+
+ assert rows == []
+ assert [c["offset"] for c in calls] == [0]
+
+ def test_saves_next_offset_only_while_more_pages_remain(self, monkeypatch: Any) -> None:
+ _patch_fetch(monkeypatch, [_page(PAGE_SIZE), _page(1)])
+ manager = _FakeResumableManager()
+ _collect(monkeypatch, manager, endpoint="orders")
+
+ # State is saved after the full first page (advance to PAGE_SIZE), never after the short last page.
+ assert manager.saved == [PicqerResumeConfig(offset=PAGE_SIZE)]
+
+ def test_resumes_from_saved_offset(self, monkeypatch: Any) -> None:
+ calls = _patch_fetch(monkeypatch, [_page(2)])
+ rows = _collect(monkeypatch, _FakeResumableManager(PicqerResumeConfig(offset=PAGE_SIZE)), endpoint="orders")
+
+ assert len(rows) == 2
+ assert [c["offset"] for c in calls] == [PAGE_SIZE]
+
+ def test_incremental_filter_present_on_every_page(self, monkeypatch: Any) -> None:
+ calls = _patch_fetch(monkeypatch, [_page(PAGE_SIZE), _page(1)])
+ _collect(
+ monkeypatch,
+ _FakeResumableManager(),
+ endpoint="purchaseorders",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2020, 1, 2, 3, 4, 5),
+ )
+ # The filter must stay on the paginated request so pagination walks only the filtered set.
+ assert all(c.get("updated_after") == "2020-01-02 03:04:05" for c in calls)
+ assert [c["offset"] for c in calls] == [0, PAGE_SIZE]
+
+ def test_full_refresh_endpoint_sends_no_filter(self, monkeypatch: Any) -> None:
+ calls = _patch_fetch(monkeypatch, [_page(1)])
+ _collect(
+ monkeypatch,
+ _FakeResumableManager(),
+ endpoint="orders",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2020, 1, 2, 3, 4, 5),
+ )
+ assert "updated_after" not in calls[0]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/picqer/tests/test_picqer_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/picqer/tests/test_picqer_source.py
new file mode 100644
index 000000000000..0e286954bc23
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/picqer/tests/test_picqer_source.py
@@ -0,0 +1,203 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import PicqerSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.picqer.picqer import (
+ PicqerResumeConfig,
+ picqer_source,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.picqer.settings import ENDPOINTS, PICQER_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.picqer.source import PicqerSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+# Endpoints whose Picqer list action exposes a genuine update-based `updated_after` filter.
+_INCREMENTAL_ENDPOINTS = {"purchaseorders", "returns"}
+_FULL_REFRESH_ENDPOINTS = set(ENDPOINTS) - _INCREMENTAL_ENDPOINTS
+
+
+class TestPicqerSource:
+ def setup_method(self):
+ self.source = PicqerSource()
+ self.team_id = 123
+ self.config = PicqerSourceConfig(account_name="acme", api_key="key")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.PICQER
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Picqer"
+ assert config.label == "Picqer"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is None
+ assert config.iconPath == "/static/services/picqer.png"
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/picqer"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["account_name", "api_key"]
+
+ def test_api_key_field_is_secret_password(self):
+ config = self.source.get_source_config
+ api_key_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")
+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key_field.secret is True
+ assert api_key_field.required is True
+
+ def test_account_listed_as_connection_host_field(self):
+ # The API key is sent to <account_name>.picqer.com, so retargeting it must re-require the key.
+ assert self.source.connection_host_fields == ["account_name"]
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://acme.picqer.com/api/v1/orders?offset=0",
+ "403 Client Error: Forbidden for url: https://acme.picqer.com/api/v1/returns?offset=0",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ @pytest.mark.parametrize(
+ "other_error",
+ [
+ "429 Client Error: Too Many Requests for url: https://acme.picqer.com/api/v1/orders",
+ "500 Server Error: Internal Server Error for url: https://acme.picqer.com/api/v1/orders",
+ "HTTPSConnectionPool(host='acme.picqer.com', port=443): Read timed out.",
+ ],
+ )
+ def test_non_retryable_errors_do_not_match_transient(self, other_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(key in other_error for key in non_retryable_errors)
+
+ def test_get_schemas_match_endpoints_with_correct_sync_modes(self):
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+
+ assert set(schemas) == set(ENDPOINTS)
+ for name in _INCREMENTAL_ENDPOINTS:
+ assert schemas[name].supports_incremental is True
+ assert schemas[name].supports_append is True
+ assert len(schemas[name].incremental_fields) == 1
+ for name in _FULL_REFRESH_ENDPOINTS:
+ assert schemas[name].supports_incremental is False
+ assert schemas[name].supports_append is False
+ assert schemas[name].incremental_fields == []
+
+ def test_incremental_cursor_is_an_update_field(self):
+ # The cursor must be an update timestamp so incremental catches modifications, not just new rows.
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+ assert [f["field"] for f in schemas["purchaseorders"].incremental_fields] == ["updated"]
+ assert [f["field"] for f in schemas["returns"].incremental_fields] == ["updated_at"]
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["orders"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "orders"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ def test_lists_tables_without_credentials_publishes_catalog(self):
+ assert self.source.lists_tables_without_credentials is True
+ documented = self.source.get_documented_tables()
+ assert {table["name"] for table in documented} == set(ENDPOINTS)
+
+ def test_canonical_descriptions_cover_every_endpoint(self):
+ canonical = self.source.get_canonical_descriptions()
+ assert set(canonical) == set(PICQER_ENDPOINTS)
+
+ @pytest.mark.parametrize(
+ "mock_return, expected_valid, expected_message",
+ [
+ ((True, 200), True, None),
+ # 403 = valid key, insufficient scope — accepted at source-create (per-table scope reported separately).
+ ((True, 403), True, None),
+ ((False, 401), False, "Invalid Picqer API key"),
+ ((False, None), False, "Could not connect to Picqer with the provided account name and API key"),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.picqer.source.validate_picqer_credentials"
+ )
+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):
+ mock_validate.return_value = mock_return
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is expected_valid
+ assert error_message == expected_message
+ mock_validate.assert_called_once_with("acme", "key")
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.picqer.source.validate_picqer_credentials"
+ )
+ def test_validate_credentials_surfaces_bad_account(self, mock_validate):
+ mock_validate.side_effect = ValueError("Invalid Picqer account: 'a/b'.")
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is False
+ assert "Invalid Picqer account" in (error_message or "")
+
+ def test_get_resumable_source_manager_bound_to_resume_config(self):
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+ assert manager._data_class is PicqerResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.picqer.source.picqer_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_picqer_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "purchaseorders"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2020-01-02 03:04:05"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ kwargs = mock_picqer_source.call_args.kwargs
+ assert kwargs["account"] == "acme"
+ assert kwargs["api_key"] == "key"
+ assert kwargs["endpoint"] == "purchaseorders"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["db_incremental_field_last_value"] == "2020-01-02 03:04:05"
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.picqer.source.picqer_source")
+ def test_source_for_pipeline_omits_cursor_when_not_incremental(self, mock_picqer_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "orders"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2020-01-02 03:04:05"
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_picqer_source.call_args.kwargs["db_incremental_field_last_value"] is None
+
+
+class TestPicqerSourceResponse:
+ def test_partitioned_endpoint_uses_stable_created_field(self):
+ # purchaseorders is incremental on `updated`, but must partition on the stable `created` field —
+ # partitioning on `updated` would rewrite partitions on every sync.
+ response = picqer_source(
+ account="acme",
+ api_key="key",
+ endpoint="purchaseorders",
+ logger=mock.MagicMock(),
+ resumable_source_manager=mock.MagicMock(),
+ )
+ assert response.primary_keys == ["idpurchaseorder"]
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == ["created"]
+
+ def test_endpoint_without_created_field_is_unpartitioned(self):
+ response = picqer_source(
+ account="acme",
+ api_key="key",
+ endpoint="warehouses",
+ logger=mock.MagicMock(),
+ resumable_source_manager=mock.MagicMock(),
+ )
+ assert response.primary_keys == ["idwarehouse"]
+ assert response.partition_mode is None
+ assert response.partition_keys is None