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(warehouse): implement bol retailer source (#118204)

Daniel RCf6137bb89f97
diff --git a/frontend/public/services/bol_retailer.png b/frontend/public/services/bol_retailer.png
index c5736e43b50d..2ebb618561ca 100644
Binary files a/frontend/public/services/bol_retailer.png and b/frontend/public/services/bol_retailer.png differ
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 95ac6061045a..a9ca99352b5c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -158,6 +158,7 @@ the row lists both.
| bloomerang | HTTP | requests + `rest_source.RESTClient` | ✅ |
| bluesky | HTTP | requests + `rest_source.RESTClient` | ✅ |
| bluetally | HTTP | requests | ✅ |
+| bol_retailer | HTTP | requests + `rest_source.RESTClient` | ✅ |
| boldsign | HTTP | requests | ✅ |
| braintree | HTTP (GraphQL) | requests | ✅ |
| braintrust | HTTP | requests | ✅ |
@@ -1056,7 +1057,6 @@ doesn't conflict with concurrent PRs.
- blackbaud_raisers_edge_nxt
- blackboard_learn
- bling
-- bol_retailer
- boulevard
- box
- branch
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bol_retailer/bol_retailer.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bol_retailer/bol_retailer.py
new file mode 100644
index 000000000000..ea2e0a2dfe50
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bol_retailer/bol_retailer.py
@@ -0,0 +1,330 @@
+from collections.abc import Callable, Iterator
+from datetime import UTC, date, datetime, timedelta
+from typing import Any, Optional
+
+from requests.auth import HTTPBasicAuth
+from urllib3.util.retry import Retry
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.bol_retailer.settings import (
+ BOL_BASE_URL,
+ BOL_ENDPOINTS,
+ BOL_TOKEN_URL,
+ INVOICE_HISTORY_DAYS,
+ INVOICE_WINDOW_DAYS,
+ OFFERS_PAGE_SIZE,
+ ORDER_HISTORY_DAYS,
+ BolEndpointConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import OAuth2Auth
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ JSONResponseCursorPaginator,
+ PageNumberPaginator,
+ SinglePagePaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import RESTClient
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+
+REQUEST_TIMEOUT = (10, 120)
+TOKEN_TIMEOUT = 30
+
+
+@frozen
+class BolRetailerResumeConfig:
+ pass_index: int = 0
+ page: int = 1
+ # The first day of the run's order or invoice windows, so a resumed attempt rebuilds the same passes.
+ window_start: str | None = None
+ cursor: str | None = None
+ # The `last-modified-date-time` the interrupted attempt sent, so resumed pages come from the same result set.
+ modified_since: str | None = None
+
+
+def _auth(client_id: str, client_secret: str) -> OAuth2Auth:
+ return OAuth2Auth(
+ token_url=BOL_TOKEN_URL,
+ client_id=client_id,
+ client_secret=client_secret,
+ grant_type="client_credentials",
+ client_auth_method="basic",
+ # bol's token service only answers JSON when the request asks for it.
+ token_request_headers={"Accept": "application/json"},
+ )
+
+
+def format_modified_since(value: Any) -> str:
+ if isinstance(value, datetime):
+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)
+ return aware.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
+ if isinstance(value, date):
+ return f"{value.isoformat()}T00:00:00Z"
+ return str(value)
+
+
+def flatten_order_items(order: dict[str, Any]) -> list[dict[str, Any]]:
+ """One row per order item, carrying the order's id and placement time."""
+ return [
+ {"orderId": order.get("orderId"), "orderPlacedDateTime": order.get("orderPlacedDateTime"), **item}
+ for item in order.get("orderItems") or []
+ if isinstance(item, dict)
+ ]
+
+
+def _paged_passes(
+ client: RESTClient,
+ path: str,
+ data_selector: str,
+ passes: list[dict[str, Any]],
+ manager: ResumableSourceManager[BolRetailerResumeConfig],
+ resume: BolRetailerResumeConfig | None,
+ window_start: str | None = None,
+ row_map: Callable[[dict[str, Any]], list[dict[str, Any]]] | None = None,
+ stop_before: tuple[str, datetime] | None = None,
+) -> Iterator[list[Any]]:
+ start_pass = resume.pass_index if resume is not None else 0
+ for pass_index in range(start_pass, len(passes)):
+ first_page = resume.page if resume is not None and pass_index == start_pass else 1
+
+ def stage(state: Optional[dict[str, Any]], has_next_page: bool, pass_index: int = pass_index) -> None:
+ if has_next_page and state:
+ manager.save_state(
+ BolRetailerResumeConfig(pass_index=pass_index, page=int(state["page"]), window_start=window_start)
+ )
+ elif pass_index + 1 < len(passes):
+ manager.save_state(BolRetailerResumeConfig(pass_index=pass_index + 1, window_start=window_start))
+
+ # bol ends a list with an empty page and reports no total, so each pass costs one empty request.
+ for rows in client.paginate(
+ path,
+ params=passes[pass_index],
+ paginator=PageNumberPaginator(base_page=1, page=first_page, page_param="page"),
+ data_selector=data_selector,
+ page_state_hook=stage,
+ ):
+ mapped = [mapped_row for row in rows for mapped_row in row_map(row)] if row_map else rows
+ reached_watermark = (
+ stop_before is not None and bool(mapped) and all(_is_before(row, *stop_before) for row in mapped)
+ )
+ if reached_watermark and pass_index + 1 < len(passes):
+ manager.save_state(BolRetailerResumeConfig(pass_index=pass_index + 1, window_start=window_start))
+ if mapped:
+ yield mapped
+ else:
+ manager.safe_point()
+ if reached_watermark:
+ break
+
+
+def _as_utc(value: Any) -> datetime:
+ parsed = value if isinstance(value, datetime) else datetime.fromisoformat(str(value))
+ return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=UTC)
+
+
+def _is_before(row: dict[str, Any], field: str, watermark: datetime) -> bool:
+ value = row.get(field)
+ return value is not None and _as_utc(value) < watermark
+
+
+def _to_date(value: Any) -> date:
+ if isinstance(value, datetime):
+ return value.date()
+ if isinstance(value, date):
+ return value
+ return date.fromisoformat(str(value)[:10])
+
+
+def _invoice_windows(
+ client: RESTClient,
+ config: BolEndpointConfig,
+ manager: ResumableSourceManager[BolRetailerResumeConfig],
+ start: date,
+ today: date,
+) -> Iterator[list[Any]]:
+ window = start
+ while window <= today:
+ end = min(window + timedelta(days=INVOICE_WINDOW_DAYS - 1), today)
+ rows: list[Any] = []
+ for page in client.paginate(
+ config.path,
+ params={"period-start-date": window.isoformat(), "period-end-date": end.isoformat()},
+ paginator=SinglePagePaginator(),
+ data_selector=config.data_selector,
+ ):
+ rows.extend(page)
+ next_window = end + timedelta(days=1)
+ if next_window <= today:
+ manager.save_state(BolRetailerResumeConfig(window_start=next_window.isoformat()))
+ if rows:
+ yield rows
+ else:
+ manager.safe_point()
+ window = next_window
+
+
+def bol_retailer_source(
+ client_id: str,
+ client_secret: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[BolRetailerResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = BOL_ENDPOINTS[endpoint]
+ auth = _auth(client_id, client_secret)
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ response_kwargs: dict[str, Any] = {
+ "name": endpoint,
+ "primary_keys": list(config.primary_keys),
+ "partition_count": 1 if config.partition_key else None,
+ "partition_size": 1 if config.partition_key else None,
+ "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,
+ }
+
+ if config.pagination == "cursor":
+ is_incremental = should_use_incremental_field and bool(config.incremental_fields)
+ modified_since: str | None
+ if resume is not None:
+ modified_since = resume.modified_since
+ elif is_incremental and db_incremental_field_last_value is not None:
+ modified_since = format_modified_since(db_incremental_field_last_value)
+ else:
+ modified_since = None
+ params: dict[str, Any] = {"page-size": OFFERS_PAGE_SIZE}
+ if modified_since:
+ params["last-modified-date-time"] = modified_since
+
+ rest_config: RESTAPIConfig = {
+ "client": {
+ "base_url": BOL_BASE_URL,
+ "headers": {"Accept": config.accept},
+ "auth": auth,
+ "paginator": JSONResponseCursorPaginator(cursor_path="page.nextCursor", cursor_param="cursor"),
+ "request_timeout": REQUEST_TIMEOUT,
+ },
+ "resource_defaults": {},
+ "resources": [
+ {
+ "name": endpoint,
+ "table_name": endpoint,
+ "primary_key": list(config.primary_keys),
+ "write_disposition": {"disposition": "merge", "strategy": "upsert"}
+ if is_incremental
+ else "replace",
+ "endpoint": {"path": config.path, "params": params, "data_selector": config.data_selector},
+ "table_format": "delta",
+ }
+ ],
+ }
+
+ def save_cursor(state: Optional[dict[str, Any]]) -> None:
+ if state and state.get("cursor"):
+ resumable_source_manager.save_state(
+ BolRetailerResumeConfig(cursor=str(state["cursor"]), modified_since=modified_since)
+ )
+
+ resource = rest_api_resource(
+ rest_config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value,
+ resume_hook=save_cursor,
+ initial_paginator_state={"cursor": resume.cursor} if resume is not None and resume.cursor else None,
+ )
+ # bol documents no order for offers, so the watermark is taken once the run ends.
+ return SourceResponse(items=lambda: resource, sort_mode="desc", **response_kwargs)
+
+ client = RESTClient(
+ base_url=BOL_BASE_URL, headers={"Accept": config.accept}, auth=auth, request_timeout=REQUEST_TIMEOUT
+ )
+ if config.pagination == "invoice_windows":
+ today = datetime.now(UTC).date()
+ start = (
+ date.fromisoformat(resume.window_start)
+ if resume is not None and resume.window_start
+ else today - timedelta(days=INVOICE_HISTORY_DAYS)
+ )
+ return SourceResponse(
+ items=lambda: _invoice_windows(client, config, resumable_source_manager, start, today),
+ **response_kwargs,
+ )
+
+ if config.per_change_day:
+ today = datetime.now(UTC).date()
+ floor = today - timedelta(days=ORDER_HISTORY_DAYS)
+ if resume is not None and resume.window_start:
+ first_day = date.fromisoformat(resume.window_start)
+ elif should_use_incremental_field and db_incremental_field_last_value is not None:
+ first_day = max(_to_date(db_incremental_field_last_value), floor)
+ else:
+ first_day = floor
+ days = [first_day + timedelta(days=offset) for offset in range((today - first_day).days + 1)]
+ passes = [{**dict(base), "latest-change-date": day.isoformat()} for day in days for base in config.passes]
+ return SourceResponse(
+ items=lambda: _paged_passes(
+ client,
+ config.path,
+ config.data_selector,
+ passes,
+ resumable_source_manager,
+ resume,
+ window_start=first_day.isoformat(),
+ row_map=flatten_order_items,
+ ),
+ # Days are requested in order, and the next run re-reads the watermark's whole day.
+ sort_mode="asc",
+ **response_kwargs,
+ )
+
+ stop_before: tuple[str, datetime] | None = None
+ if config.newest_first and should_use_incremental_field and db_incremental_field_last_value is not None:
+ stop_before = (config.incremental_fields[0]["field"], _as_utc(db_incremental_field_last_value))
+ return SourceResponse(
+ items=lambda: _paged_passes(
+ client,
+ config.path,
+ config.data_selector,
+ [dict(params) for params in config.passes],
+ resumable_source_manager,
+ resume,
+ stop_before=stop_before,
+ ),
+ # Newest-first lists take the watermark once the run ends.
+ sort_mode="desc" if config.newest_first else "asc",
+ **response_kwargs,
+ )
+
+
+def validate_credentials(client_id: str, client_secret: str) -> tuple[bool, str | None]:
+ """Mint one access token. bol grants every Retailer API resource to the same client credentials."""
+ try:
+ # Setup waits on the probe, so it gets one attempt.
+ response = make_tracked_session(
+ redact_values=(client_secret,), capture=False, allow_redirects=False, retry=Retry(total=0)
+ ).post(
+ BOL_TOKEN_URL,
+ data={"grant_type": "client_credentials"},
+ auth=HTTPBasicAuth(client_id, client_secret),
+ headers={"Accept": "application/json"},
+ timeout=TOKEN_TIMEOUT,
+ )
+ except Exception: # noqa: BLE001 — a credential probe must never raise; any failure means "not validated"
+ return False, "Could not connect to bol. Try again in a minute."
+ if response.status_code == 200:
+ return True, None
+ if response.status_code in (400, 401):
+ return (
+ False,
+ "bol rejected the client ID or secret. Copy both again from API settings in your seller dashboard.",
+ )
+ return False, "Could not connect to bol. Try again in a minute."
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bol_retailer/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bol_retailer/canonical_descriptions.py
new file mode 100644
index 000000000000..2f6757e79162
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bol_retailer/canonical_descriptions.py
@@ -0,0 +1,77 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+_DOCS = "https://api.bol.com/retailer/public/Retailer-API/"
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "order_items": {
+ "description": "One line of an order placed on bol.com for the seller's offers.",
+ "docs_url": f"{_DOCS}v10/functional/retailer-api/orders-shipments.html",
+ "columns": {
+ "orderId": "The order the item belongs to.",
+ "orderPlacedDateTime": "When the customer placed the order.",
+ "orderItemId": "Identifier of the order item.",
+ "ean": "EAN of the ordered product.",
+ "fulfilmentMethod": "Whether the seller (FBR) or bol (FBB) ships the item.",
+ "fulfilmentStatus": "Whether the item is still open or handled.",
+ "quantity": "Units ordered.",
+ "quantityShipped": "Units shipped so far.",
+ "quantityCancelled": "Units cancelled.",
+ "cancellationRequest": "Whether the customer asked to cancel the item.",
+ "latestChangedDateTime": "When the item last changed. Used for incremental sync.",
+ },
+ },
+ "shipments": {
+ "description": "A shipment of order items. The API lists the last three months.",
+ "docs_url": f"{_DOCS}v10/functional/retailer-api/orders-shipments.html",
+ "columns": {
+ "shipmentId": "Unique identifier of the shipment.",
+ "shipmentDateTime": "When the shipment was made.",
+ "shipmentReference": "The seller's own reference for the shipment.",
+ "order": "The order the shipment belongs to.",
+ "shipmentItems": "The order items in the shipment.",
+ "transport": "Carrier and track-and-trace details.",
+ },
+ },
+ "returns": {
+ "description": "A customer return of one or more order items.",
+ "docs_url": f"{_DOCS}v10/functional/retailer-api/returns.html",
+ "columns": {
+ "returnId": "Unique identifier of the return.",
+ "registrationDateTime": "When the return was registered.",
+ "fulfilmentMethod": "Whether the seller (FBR) or bol (FBB) handles the return.",
+ "returnItems": "The returned items, each with its order, EAN, quantity and handling state.",
+ },
+ },
+ "inventory": {
+ "description": "Stock the seller keeps in bol's warehouses (fulfilment by bol), one row per product.",
+ "docs_url": f"{_DOCS}v10/functional/retailer-api/inventory-shipments-fbb.html",
+ "columns": {
+ "ean": "EAN of the product.",
+ "bsku": "bol's stock keeping unit for the product.",
+ "title": "Product title.",
+ "regularStock": "Units in sellable condition.",
+ "gradedStock": "Units in graded (second-hand) condition.",
+ },
+ },
+ "invoices": {
+ "description": "An invoice bol issued to the seller, such as the monthly sales invoice or an advertising invoice.",
+ "docs_url": f"{_DOCS}v10/functional/retailer-api/invoices.html",
+ "columns": {
+ "invoiceId": "Unique identifier of the invoice.",
+ "issueDate": "When bol issued the invoice.",
+ "invoiceType": "ALL_IN_ONE for the seller invoice or ADVERTISING_VIA_BOL for an advertising invoice.",
+ },
+ },
+ "offers": {
+ "description": "An offer the seller lists on bol.com for a product.",
+ "docs_url": f"{_DOCS}v11/functional/offer-api/offer-api.html",
+ "columns": {
+ "offerId": "Unique identifier of the offer.",
+ "ean": "EAN of the product the offer is for.",
+ "reference": "The seller's own reference for the offer.",
+ "lastModifiedDateTime": "When the offer last changed. Used for incremental sync.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bol_retailer/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bol_retailer/settings.py
new file mode 100644
index 000000000000..30a61fb2909d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bol_retailer/settings.py
@@ -0,0 +1,137 @@
+from typing import Literal
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+BOL_BASE_URL = "https://api.bol.com/retailer"
+BOL_TOKEN_URL = "https://login.bol.com/token"
+
+# Each bol resource versions on its own. Offers moved to v11; the other resources are still on v10.
+ACCEPT_V10 = "application/vnd.retailer.v10+json"
+ACCEPT_V11 = "application/vnd.retailer.v11+json"
+
+OFFERS_PAGE_SIZE = 100
+
+# The order list keeps handled orders for 48 hours. Older orders come one day at a time through
+# `latest-change-date`, which reaches three months back.
+ORDER_HISTORY_DAYS = 90
+
+# The invoice list takes a period of at most 31 days, and invoice details reach 2 years back.
+INVOICE_WINDOW_DAYS = 31
+INVOICE_HISTORY_DAYS = 2 * 365
+
+Pagination = Literal["pages", "cursor", "invoice_windows"]
+
+
+@frozen
+class BolEndpointConfig:
+ name: str
+ path: str
+ data_selector: str
+ primary_keys: tuple[str, ...]
+ pagination: Pagination = "pages"
+ accept: str = ACCEPT_V10
+ # One pass per parameter set, for list endpoints that only return one fulfilment method or one
+ # handled state per call.
+ passes: tuple[tuple[tuple[str, str], ...], ...] = ((),)
+ incremental_fields: tuple[IncrementalField, ...] = ()
+ partition_key: str | None = None
+ # Repeat the passes once per day, filtered on the day the order items last changed.
+ per_change_day: bool = False
+ # The list returns the newest rows first, so an incremental pass stops at the first page older
+ # than the watermark.
+ newest_first: bool = False
+
+
+BOL_ENDPOINTS: dict[str, BolEndpointConfig] = {
+ # One row per order item: a day filtered on `latest-change-date` returns only the items changed that
+ # day, so whole-order rows would lose the items of other days on merge.
+ "order_items": BolEndpointConfig(
+ name="order_items",
+ path="/orders",
+ data_selector="orders",
+ primary_keys=("orderId", "orderItemId"),
+ # The list defaults to open orders shipped by the retailer only.
+ passes=((("status", "ALL"), ("fulfilment-method", "ALL")),),
+ per_change_day=True,
+ incremental_fields=(
+ {
+ "label": "latestChangedDateTime",
+ "type": IncrementalFieldType.DateTime,
+ "field": "latestChangedDateTime",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ),
+ partition_key="orderPlacedDateTime",
+ ),
+ "shipments": BolEndpointConfig(
+ name="shipments",
+ path="/shipments",
+ data_selector="shipments",
+ primary_keys=("shipmentId",),
+ passes=((("fulfilment-method", "FBR"),), (("fulfilment-method", "FBB"),)),
+ # The list reaches three months back, so only merging keeps older shipments in the table.
+ incremental_fields=(
+ {
+ "label": "shipmentDateTime",
+ "type": IncrementalFieldType.DateTime,
+ "field": "shipmentDateTime",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ),
+ partition_key="shipmentDateTime",
+ newest_first=True,
+ ),
+ "returns": BolEndpointConfig(
+ name="returns",
+ path="/returns",
+ data_selector="returns",
+ primary_keys=("returnId",),
+ passes=tuple(
+ (("handled", handled), ("fulfilment-method", method))
+ for method in ("FBR", "FBB")
+ for handled in ("false", "true")
+ ),
+ partition_key="registrationDateTime",
+ ),
+ "inventory": BolEndpointConfig(
+ name="inventory",
+ path="/inventory",
+ data_selector="inventory",
+ primary_keys=("ean",),
+ ),
+ "invoices": BolEndpointConfig(
+ name="invoices",
+ path="/invoices",
+ data_selector="invoiceListItems",
+ primary_keys=("invoiceId",),
+ pagination="invoice_windows",
+ ),
+ "offers": BolEndpointConfig(
+ name="offers",
+ path="/offers",
+ data_selector="offers",
+ primary_keys=("offerId",),
+ pagination="cursor",
+ accept=ACCEPT_V11,
+ incremental_fields=(
+ {
+ "label": "lastModifiedDateTime",
+ "type": IncrementalFieldType.DateTime,
+ "field": "lastModifiedDateTime",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ),
+ ),
+}
+
+ENDPOINTS = tuple(BOL_ENDPOINTS)
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: list(config.incremental_fields) for name, config in BOL_ENDPOINTS.items()
+}
+
+# Order items re-read the watermark's whole day each run, and shipments re-read the watermark's page.
+# Appending would write those rows again.
+MERGE_ONLY = ("order_items", "shipments")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bol_retailer/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bol_retailer/source.py
index 7249c8165ef7..1683f4502415 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bol_retailer/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bol_retailer/source.py
@@ -1,27 +1,147 @@
-from typing import cast
+from typing import Optional, cast
-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.facade.codebase_detection import NOT_DETECTABLE
+from products.warehouse_sources.backend.facade.source_config import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.bol_retailer.bol_retailer import (
+ BolRetailerResumeConfig,
+ bol_retailer_source,
+ validate_credentials as validate_bol_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.bol_retailer.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ MERGE_ONLY,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import (
+ OAUTH2_PERMANENT_ERROR_MARKER,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (
+ SourceSchema,
+ build_endpoint_schemas,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.bolretailer import (
BolRetailerSourceConfig,
)
from products.warehouse_sources.backend.types import ExternalDataSourceType
+_RECONNECT = "Copy the client ID and secret again from API settings in your bol seller dashboard."
+
@SourceRegistry.register
-class BolRetailerSource(SimpleSource[BolRetailerSourceConfig]):
+class BolRetailerSource(ResumableSource[BolRetailerSourceConfig, BolRetailerResumeConfig]):
+ codebase_detection = NOT_DETECTABLE
+
+ lists_tables_without_credentials = True
+ # bol versions each resource on its own (v11 for offers, v10 for the rest), so there is no single
+ # version to pin.
+ api_docs_url = "https://api.bol.com/retailer/public/Retailer-API/v10/releasenotes.html"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.BOLRETAILER
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ OAUTH2_PERMANENT_ERROR_MARKER: f"bol rejected the client ID or secret. {_RECONNECT}",
+ "401 Client Error: Unauthorized for url: https://api.bol.com": f"bol rejected the access token. {_RECONNECT}",
+ "403 Client Error: Forbidden for url: https://api.bol.com": (
+ "bol refused access. Check that your seller account is active and has a technical contact in API settings."
+ ),
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.bol_retailer.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: BolRetailerSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, merge_only=MERGE_ONLY)
+
+ def validate_credentials(
+ self,
+ config: BolRetailerSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ return validate_bol_credentials(config.client_id, config.client_secret)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[BolRetailerResumeConfig]:
+ return ResumableSourceManager[BolRetailerResumeConfig](inputs, BolRetailerResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: BolRetailerSourceConfig,
+ resumable_source_manager: ResumableSourceManager[BolRetailerResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return bol_retailer_source(
+ client_id=config.client_id,
+ client_secret=config.client_secret,
+ 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,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=ExternalDataSourceType.BOLRETAILER,
category=DataWarehouseSourceCategory.E_COMMERCE,
- label="bol.com (bol Partner / Retailer API)",
+ keywords=["bol", "bol.com"],
+ label="bol.com Retailer",
+ caption="Sync order items, shipments, returns, offers, inventory and invoices from your bol.com seller account.",
+ docsUrl="https://posthog.com/docs/cdp/sources/bol-retailer",
iconPath="/static/services/bol_retailer.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="client_id",
+ label="Client ID",
+ caption="Create client credentials under Settings > Services > API settings in your bol seller dashboard.",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="client_secret",
+ label="Client secret",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bol_retailer/tests/test_bol_retailer.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bol_retailer/tests/test_bol_retailer.py
new file mode 100644
index 000000000000..31acd906f00d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bol_retailer/tests/test_bol_retailer.py
@@ -0,0 +1,281 @@
+from datetime import UTC, datetime
+from typing import Any
+
+import pytest
+import time_machine
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.bol_retailer.bol_retailer import (
+ BolRetailerResumeConfig,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.bol_retailer.source import BolRetailerSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import (
+ OAUTH2_PERMANENT_ERROR_MARKER,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
+ DriveResult,
+ ScriptedResponse,
+ SourceDriver,
+ always,
+ route,
+ scripted_network,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.bolretailer import (
+ BolRetailerSourceConfig,
+)
+
+TOKEN = ScriptedResponse(json={"access_token": "tok", "token_type": "Bearer", "expires_in": 299})
+EMPTY = ScriptedResponse(json={})
+
+
+def _run(endpoint: str, api_path: str, responses: list[ScriptedResponse], **inputs: Any) -> DriveResult:
+ config = BolRetailerSourceConfig(client_id="bol_id", client_secret="bol_secret")
+ script = route({"/token": [TOKEN], api_path: responses})
+ return SourceDriver(BolRetailerSource(), config).run(endpoint, script, **inputs)
+
+
+def _api(result: DriveResult) -> list[Any]:
+ return [request for request in result.requests if request.path != "/token"]
+
+
+class TestPagedLists:
+ @time_machine.travel(datetime(2026, 10, 15, 12, tzinfo=UTC), tick=False)
+ def test_order_items_read_one_change_day_at_a_time_from_the_watermark(self) -> None:
+ # The plain list drops handled orders after 48 hours, so history comes from `latest-change-date`.
+ order = {
+ "orderId": "A1",
+ "orderPlacedDateTime": "2026-10-14T09:00:00+02:00",
+ "orderItems": [
+ {"orderItemId": "1", "latestChangedDateTime": "2026-10-14T23:30:00+02:00"},
+ {"orderItemId": "2", "latestChangedDateTime": "2026-10-14T22:00:00+00:00"},
+ ],
+ }
+ result = _run(
+ "order_items",
+ "/orders",
+ [ScriptedResponse(json={"orders": [order]}), EMPTY, EMPTY],
+ incremental_field="latestChangedDateTime",
+ db_incremental_field_last_value=datetime(2026, 10, 14, 8, tzinfo=UTC),
+ )
+
+ assert result.raised is None
+ token_request = result.requests[0]
+ assert token_request.path == "/token"
+ assert token_request.headers["authorization"] == "Basic Ym9sX2lkOmJvbF9zZWNyZXQ="
+ assert token_request.body == b"grant_type=client_credentials"
+ api = _api(result)
+ assert [(r.param("latest-change-date"), r.param("page")) for r in api] == [
+ ("2026-10-14", "1"),
+ ("2026-10-14", "2"),
+ ("2026-10-15", "1"),
+ ]
+ assert {(r.param("status"), r.param("fulfilment-method")) for r in api} == {("ALL", "ALL")}
+ assert api[0].headers["accept"] == "application/vnd.retailer.v10+json"
+ assert api[0].headers["authorization"] == "Bearer tok"
+ # A day's response holds only the items changed that day, so each item is its own row.
+ assert [(row["orderId"], row["orderItemId"], row["orderPlacedDateTime"]) for row in result.rows] == [
+ ("A1", "1", "2026-10-14T09:00:00+02:00"),
+ ("A1", "2", "2026-10-14T09:00:00+02:00"),
+ ]
+ assert result.saved_states == [
+ BolRetailerResumeConfig(pass_index=0, page=2, window_start="2026-10-14"),
+ BolRetailerResumeConfig(pass_index=1, window_start="2026-10-14"),
+ ]
+
+ @time_machine.travel(datetime(2026, 10, 15, 12, tzinfo=UTC), tick=False)
+ def test_resumed_order_items_rebuild_the_days_from_the_saved_window_start(self) -> None:
+ # The watermark moved past the saved window start, which must not shift the saved pass index.
+ result = _run(
+ "order_items",
+ "/orders",
+ [EMPTY, EMPTY],
+ resume_state=BolRetailerResumeConfig(pass_index=1, page=2, window_start="2026-10-13"),
+ incremental_field="latestChangedDateTime",
+ db_incremental_field_last_value=datetime(2026, 10, 14, 8, tzinfo=UTC),
+ )
+
+ assert result.raised is None
+ assert [(r.param("latest-change-date"), r.param("page")) for r in _api(result)] == [
+ ("2026-10-14", "2"),
+ ("2026-10-15", "1"),
+ ]
+
+ @time_machine.travel(datetime(2026, 10, 15, 12, tzinfo=UTC), tick=False)
+ def test_a_first_order_items_sync_reaches_three_months_back(self) -> None:
+ result = _run("order_items", "/orders", [EMPTY] * 91)
+
+ assert result.raised is None
+ days = [r.param("latest-change-date") for r in _api(result)]
+ assert (days[0], days[-1], len(days)) == ("2026-07-17", "2026-10-15", 91)
+
+ def test_shipments_walk_one_pass_per_fulfilment_method(self) -> None:
+ result = _run(
+ "shipments",
+ "/shipments",
+ [
+ ScriptedResponse(json={"shipments": [{"shipmentId": "1"}]}),
+ EMPTY,
+ ScriptedResponse(json={"shipments": [{"shipmentId": "2"}]}),
+ EMPTY,
+ ],
+ )
+
+ assert result.raised is None
+ assert [(r.param("fulfilment-method"), r.param("page")) for r in _api(result)] == [
+ ("FBR", "1"),
+ ("FBR", "2"),
+ ("FBB", "1"),
+ ("FBB", "2"),
+ ]
+ assert [row["shipmentId"] for row in result.rows] == ["1", "2"]
+ # The empty page that ends the first pass stages the second pass, and the safe point commits it.
+ assert BolRetailerResumeConfig(pass_index=1) in result.committed_states
+
+ def test_incremental_shipments_stop_each_pass_at_the_first_page_older_than_the_watermark(self) -> None:
+ # The list returns newest shipments first and reaches three months back.
+ def shipment(shipment_id: str, day: int) -> dict[str, Any]:
+ return {"shipmentId": shipment_id, "shipmentDateTime": f"2026-10-{day:02d}T12:00:00+02:00"}
+
+ result = _run(
+ "shipments",
+ "/shipments",
+ [
+ ScriptedResponse(json={"shipments": [shipment("4", 14), shipment("3", 9)]}),
+ ScriptedResponse(json={"shipments": [shipment("2", 8), shipment("1", 2)]}),
+ ScriptedResponse(json={"shipments": [shipment("5", 1)]}),
+ ],
+ incremental_field="shipmentDateTime",
+ db_incremental_field_last_value=datetime(2026, 10, 10, tzinfo=UTC),
+ )
+
+ assert result.raised is None
+ assert [(r.param("fulfilment-method"), r.param("page")) for r in _api(result)] == [
+ ("FBR", "1"),
+ ("FBR", "2"),
+ ("FBB", "1"),
+ ]
+ assert [row["shipmentId"] for row in result.rows] == ["4", "3", "2", "1", "5"]
+ # The stop stages the next pass, so a resume does not go back to the stopped pass's next page.
+ assert result.saved_states == [
+ BolRetailerResumeConfig(page=2),
+ BolRetailerResumeConfig(page=3),
+ BolRetailerResumeConfig(pass_index=1),
+ BolRetailerResumeConfig(pass_index=1, page=2),
+ ]
+
+ def test_returns_resume_at_the_saved_pass_and_page(self) -> None:
+ result = _run(
+ "returns",
+ "/returns",
+ [EMPTY, EMPTY],
+ resume_state=BolRetailerResumeConfig(pass_index=2, page=3),
+ )
+
+ assert result.raised is None
+ assert [(r.param("handled"), r.param("fulfilment-method"), r.param("page")) for r in _api(result)] == [
+ ("false", "FBB", "3"),
+ ("true", "FBB", "1"),
+ ]
+
+
+class TestInvoices:
+ @time_machine.travel(datetime(2026, 10, 15, 12, tzinfo=UTC), tick=False)
+ def test_requests_31_day_windows_up_to_today(self) -> None:
+ result = _run(
+ "invoices",
+ "/invoices",
+ [ScriptedResponse(json={"invoiceListItems": [{"invoiceId": "INV-1"}]}), ScriptedResponse(json={})],
+ resume_state=BolRetailerResumeConfig(window_start="2026-09-05"),
+ )
+
+ assert result.raised is None
+ assert [(r.param("period-start-date"), r.param("period-end-date")) for r in _api(result)] == [
+ ("2026-09-05", "2026-10-05"),
+ ("2026-10-06", "2026-10-15"),
+ ]
+ assert [row["invoiceId"] for row in result.rows] == ["INV-1"]
+ assert result.saved_states == [BolRetailerResumeConfig(window_start="2026-10-06")]
+
+
+class TestOffers:
+ @pytest.mark.parametrize(
+ ("inputs", "expected_since"),
+ [
+ ({}, None),
+ (
+ {
+ "incremental_field": "lastModifiedDateTime",
+ "db_incremental_field_last_value": datetime(2026, 10, 1, 8, 30, tzinfo=UTC),
+ },
+ "2026-10-01T08:30:00Z",
+ ),
+ ],
+ )
+ def test_walks_the_cursor_on_v11_and_filters_on_the_watermark(
+ self, inputs: dict[str, Any], expected_since: str | None
+ ) -> None:
+ result = _run(
+ "offers",
+ "/offers",
+ [
+ ScriptedResponse(json={"offers": [{"offerId": "o1"}], "page": {"pageSize": 100, "nextCursor": "c2"}}),
+ ScriptedResponse(json={"offers": [{"offerId": "o2"}], "page": {"pageSize": 100, "nextCursor": None}}),
+ ],
+ **inputs,
+ )
+
+ assert result.raised is None
+ api = _api(result)
+ assert [r.param("cursor") for r in api] == [None, "c2"]
+ assert {r.param("last-modified-date-time") for r in api} == {expected_since}
+ assert api[0].headers["accept"] == "application/vnd.retailer.v11+json"
+ assert result.saved_states == [BolRetailerResumeConfig(cursor="c2", modified_since=expected_since)]
+
+ def test_resume_keeps_the_cursor_and_the_interrupted_filter(self) -> None:
+ result = _run(
+ "offers",
+ "/offers",
+ [ScriptedResponse(json={"offers": [], "page": {"nextCursor": None}})],
+ resume_state=BolRetailerResumeConfig(cursor="c9", modified_since="2026-09-01T00:00:00Z"),
+ incremental_field="lastModifiedDateTime",
+ db_incremental_field_last_value=datetime(2026, 10, 1, tzinfo=UTC),
+ )
+
+ assert result.raised is None
+ assert [(r.param("cursor"), r.param("last-modified-date-time")) for r in _api(result)] == [
+ ("c9", "2026-09-01T00:00:00Z")
+ ]
+
+
+class TestTokenErrors:
+ def test_rejected_client_credentials_fail_with_the_permanent_marker(self) -> None:
+ config = BolRetailerSourceConfig(client_id="bol_id", client_secret="wrong")
+ result = SourceDriver(BolRetailerSource(), config).run(
+ "inventory", always(ScriptedResponse(status=401, json={"error": "invalid_client"}))
+ )
+
+ assert result.raised is not None
+ assert OAUTH2_PERMANENT_ERROR_MARKER in str(result.raised)
+ assert "invalid_client" in str(result.raised)
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ ("response", "expected_valid", "message_fragment"),
+ [
+ (TOKEN, True, None),
+ (ScriptedResponse(status=401, json={"error": "invalid_client"}), False, "rejected the client ID"),
+ (ScriptedResponse(status=500, json={}), False, "Could not connect"),
+ (ConnectionError("boom"), False, "Could not connect"),
+ ],
+ )
+ def test_maps_the_token_probe(self, response: Any, expected_valid: bool, message_fragment: str | None) -> None:
+ with scripted_network(always(response)) as network:
+ is_valid, message = validate_credentials("bol_id", "bol_secret")
+
+ assert is_valid is expected_valid
+ if message_fragment is None:
+ assert message is None
+ else:
+ assert message is not None and message_fragment in message
+ assert {request.path for request in network.requests_log} == {"/token"}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/bolretailer.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/bolretailer.py
index be4679d44f87..69cd85e50816 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/bolretailer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/bolretailer.py
@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class BolRetailerSourceConfig(config.Config):
- pass
+ client_id: str
+ client_secret: str