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 adyen source (#73771)

Tom Owers9888423dfcaf
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 89400ec69bea..3688636bc014 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -50,6 +50,7 @@ the row lists both.
| -------------------------------- | --------------------------- | --------------------------------------------------------------- | --------------------------- |
| ably | HTTP | requests + `rest_source.RESTClient` | ✅ |
| adroll | HTTP | requests | ✅ |
+| adyen | HTTP | requests | ✅ |
| agilecrm | HTTP | requests | ✅ |
| aha | HTTP | requests | ✅ |
| aha_ideas | HTTP | requests + `rest_source.RESTClient` | ✅ |
@@ -707,7 +708,6 @@ doesn't conflict with concurrent PRs.
- adobe_analytics
- adobe_commerce
- adp_workforce_now
-- adyen
- aftership
- ahrefs
- aikido_security
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/adyen/adyen.py b/products/warehouse_sources/backend/temporal/data_imports/sources/adyen/adyen.py
new file mode 100644
index 000000000000..12b1df9bf6ba
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/adyen/adyen.py
@@ -0,0 +1,591 @@
+import re
+import csv
+import codecs
+import dataclasses
+from collections.abc import Callable, Iterable, Iterator
+from datetime import UTC, date, datetime, timedelta
+from typing import Any, Optional
+from urllib.parse import parse_qs, urlencode, urlparse
+
+import requests
+from structlog.types import FilteringBoundLogger
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.adyen.settings import (
+ ADYEN_ENDPOINTS,
+ AdyenApi,
+ AdyenEndpointConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+
+ADYEN_ENVIRONMENTS = ("test", "live")
+DEFAULT_ENVIRONMENT = "live"
+
+# Adyen serves each read API from its own host, with the environment baked into the hostname.
+# Fixed allow-list, so a customer-supplied environment can never retarget the API key.
+ADYEN_HOSTS: dict[str, dict[str, str]] = {
+ "test": {
+ "transfers": "https://balanceplatform-api-test.adyen.com/btl/v4",
+ "configuration": "https://balanceplatform-api-test.adyen.com/bcl/v2",
+ "management": "https://management-test.adyen.com/v3",
+ "reports": "https://ca-test.adyen.com",
+ },
+ "live": {
+ "transfers": "https://balanceplatform-api-live.adyen.com/btl/v4",
+ "configuration": "https://balanceplatform-api-live.adyen.com/bcl/v2",
+ "management": "https://management-live.adyen.com/v3",
+ "reports": "https://ca-live.adyen.com",
+ },
+}
+
+PAGE_SIZE = 100
+REQUEST_TIMEOUT_SECONDS = 120
+REPORT_TIMEOUT_SECONDS = 600
+# The Transfers API rejects a createdUntil more than 6 months after createdSince, so long
+# backfills are walked in windows well inside that limit.
+MAX_WINDOW_DAYS = 150
+# How far back the first (non-incremental) sync reaches when no start date is configured.
+DEFAULT_BACKFILL_DAYS = 365
+# Report batch numbers are sequential per merchant account, but a batch can be missing (no
+# settlement that period, or a report aged out), so tolerate a short run of gaps before stopping.
+MAX_CONSECUTIVE_MISSING_BATCHES = 3
+# Hard cap on report files fetched in one sync — the next run resumes at the watermark.
+MAX_BATCHES_PER_SYNC = 500
+# Report files can be large; yield them in chunks rather than one list per file.
+REPORT_CHUNK_SIZE = 5000
+
+_IDENTIFIER_RE = re.compile(r"^[A-Za-z0-9._-]{1,100}$")
+
+
+class AdyenConfigurationError(Exception):
+ """The stored config can't satisfy the requested endpoint (missing or malformed identifier)."""
+
+
+class AdyenResumeConfig:
+ """Checkpoint for whichever pagination style the running endpoint uses.
+
+ One dataclass covers every endpoint because a job only ever syncs one schema, so the
+ unused fields simply stay `None`.
+ """
+
+ # Transfers API: the window being walked plus the opaque page cursor within it.
+ window_start: str | None = None
+ cursor: str | None = None
+ # Configuration API offset pagination, and the parent index for fan-out children.
+ offset: int | None = None
+ parent_index: int | None = None
+ # Management API page pagination.
+ page_number: int | None = None
+ # Report downloads: the last batch number successfully yielded.
+ batch_number: int | None = None
+
+
+def resolve_environment(environment: Optional[str]) -> str:
+ if environment is not None and environment in ADYEN_ENVIRONMENTS:
+ return environment
+ return DEFAULT_ENVIRONMENT
+
+
+def base_url(environment: Optional[str], api: AdyenApi) -> str:
+ return ADYEN_HOSTS[resolve_environment(environment)][api]
+
+
+def _require_identifier(value: Optional[str], label: str) -> str:
+ """Return a config identifier that is safe to interpolate into a request path."""
+ cleaned = (value or "").strip()
+ if not cleaned:
+ raise AdyenConfigurationError(f"{label} is required to sync this table.")
+ if not _IDENTIFIER_RE.match(cleaned):
+ raise AdyenConfigurationError(f"{label} contains unsupported characters.")
+ return cleaned
+
+
+def _get_session(api_key: str) -> requests.Session:
+ return make_tracked_session(
+ headers={"X-API-Key": api_key, "Accept": "application/json"},
+ redact_values=(api_key,),
+ # `requests` replays custom headers (including `X-API-Key`) across a cross-host 3xx, so
+ # pin redirects off to keep the credential on the host it was issued for.
+ allow_redirects=False,
+ # Report and transfer bodies carry transaction identifiers, amounts and free-form
+ # references the name-based scrubbers can't recognise — keep them out of sample capture.
+ capture=False,
+ )
+
+
+def _format_timestamp(value: datetime) -> str:
+ dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
+ return dt.strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def _to_datetime(value: Any) -> datetime | None:
+ """Coerce a stored incremental watermark (datetime, date or ISO string) into UTC."""
+ if value is None:
+ return None
+ if isinstance(value, datetime):
+ return value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
+ if isinstance(value, date):
+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC)
+ try:
+ parsed = datetime.fromisoformat(str(value).replace("Z", "+00:00"))
+ except ValueError:
+ return None
+ return parsed.replace(tzinfo=UTC) if parsed.tzinfo is None else parsed.astimezone(UTC)
+
+
+def _to_batch_number(value: Any) -> int | None:
+ if value is None:
+ return None
+ try:
+ return int(float(str(value)))
+ except (TypeError, ValueError):
+ return None
+
+
+def _resolve_start(
+ start_date: Optional[str],
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+ now: datetime,
+) -> datetime:
+ if should_use_incremental_field:
+ watermark = _to_datetime(db_incremental_field_last_value)
+ if watermark is not None:
+ return watermark
+
+ configured = _to_datetime(start_date) if start_date else None
+ if configured is not None:
+ return configured
+
+ return now - timedelta(days=DEFAULT_BACKFILL_DAYS)
+
+
+def iter_windows(start: datetime, end: datetime) -> Iterator[tuple[datetime, datetime]]:
+ """Split [start, end] into ascending chunks the Transfers API will accept."""
+ if end <= start:
+ return
+ window_start = start
+ while window_start < end:
+ window_end = min(window_start + timedelta(days=MAX_WINDOW_DAYS), end)
+ yield window_start, window_end
+ window_start = window_end
+
+
+def next_cursor(payload: Any) -> str | None:
+ """Pull the opaque cursor out of `_links.next`.
+
+ Only the cursor is kept — the next page is rebuilt against our own host, so a tampered
+ response can't point the authenticated request at another server.
+ """
+ if not isinstance(payload, dict):
+ return None
+ links = payload.get("_links")
+ if not isinstance(links, dict):
+ return None
+ next_link = links.get("next")
+ if not isinstance(next_link, dict):
+ return None
+ href = next_link.get("href")
+ if not isinstance(href, str) or not href:
+ return None
+ values = parse_qs(urlparse(href).query).get("cursor")
+ return values[0] if values else None
+
+
+def extract_items(payload: Any, data_key: Optional[str]) -> list[dict[str, Any]]:
+ if data_key is None:
+ return payload if isinstance(payload, list) else []
+ if not isinstance(payload, dict):
+ return []
+ items = payload.get(data_key, [])
+ return [item for item in items if isinstance(item, dict)] if isinstance(items, list) else []
+
+
+def normalize_header(header: str) -> str:
+ """`Gross Debit (GC)` becomes the stable column `gross_debit_gc`."""
+ return re.sub(r"[^0-9a-zA-Z]+", "_", header).strip("_").lower()
+
+
+def parse_report_rows(
+ lines: Iterable[str], batch_number: int, logger: FilteringBoundLogger
+) -> Iterator[dict[str, Any]]:
+ # `lines` is any iterator of physical CSV lines (a live response stream or a StringIO), so a
+ # large report is parsed row-by-row without buffering the whole file.
+ reader = csv.reader(lines)
+ headers: list[str] | None = None
+ for row in reader:
+ if headers is None:
+ headers = [normalize_header(header) for header in row]
+ continue
+ if not any(cell.strip() for cell in row):
+ continue
+ # zip would silently truncate a short row and drop primary-key columns, corrupting
+ # dedupe — skip the malformed line instead so the failure is visible.
+ if len(row) != len(headers):
+ logger.warning(
+ "Adyen settlement report row length mismatch; skipping row",
+ expected=len(headers),
+ got=len(row),
+ batch_number=batch_number,
+ )
+ continue
+ parsed: dict[str, Any] = dict(zip(headers, row))
+ # The report's own `Batch Number` column is a string; the requested batch is the
+ # authoritative integer watermark, so it always wins.
+ parsed["batch_number"] = batch_number
+ yield parsed
+
+
+def _request(
+ session: requests.Session,
+ url: str,
+ logger: FilteringBoundLogger,
+ headers: Optional[dict[str, str]] = None,
+ timeout: int = REQUEST_TIMEOUT_SECONDS,
+) -> requests.Response:
+ """One GET through the tracked session, which already retries 429/5xx honoring Retry-After."""
+ response = session.get(url, headers=headers, timeout=timeout)
+ if not response.ok:
+ logger.error(f"Adyen API error: status={response.status_code}, url={url}")
+ response.raise_for_status()
+ return response
+
+
+def _build_url(host: str, path: str, params: dict[str, Any]) -> str:
+ if not params:
+ return f"{host}{path}"
+ return f"{host}{path}?{urlencode(params)}"
+
+
+def validate_credentials(
+ environment: Optional[str],
+ api_key: str,
+ balance_platform: Optional[str] = None,
+ merchant_account: Optional[str] = None,
+) -> tuple[bool, str | None]:
+ """Probe the API key with one cheap call, without touching customer data.
+
+ `GET /me` returns the calling credential's own details. A 403 means the key is genuine but
+ lacks the Management API role — legitimate for a report-only credential, so it passes. A key
+ issued in a Balance Platform Customer Area may not be known to the Management API at all, so
+ a 401 there falls back to probing the balance platform the key was issued for.
+ """
+ for value, label in ((balance_platform, "Balance platform ID"), (merchant_account, "Merchant account")):
+ if value and not _IDENTIFIER_RE.match(value.strip()):
+ return False, f"{label} contains unsupported characters."
+
+ session = _get_session(api_key)
+ try:
+ status = session.get(f"{base_url(environment, 'management')}/me", timeout=30).status_code
+ if status == 401 and balance_platform:
+ platform = balance_platform.strip()
+ status = session.get(
+ f"{base_url(environment, 'configuration')}/balancePlatforms/{platform}", timeout=30
+ ).status_code
+ except requests.exceptions.RequestException as e:
+ return False, str(e)
+
+ if status in (200, 403):
+ return True, None
+ if status == 401:
+ return False, "Adyen rejected the API key. Check the key and that it matches the selected environment."
+ return False, f"Adyen credential validation failed (status {status})."
+
+
+def _iter_cursor_pages(
+ session: requests.Session,
+ config: AdyenEndpointConfig,
+ host: str,
+ balance_platform: str,
+ start: datetime,
+ end: datetime,
+ logger: FilteringBoundLogger,
+ manager: ResumableSourceManager[AdyenResumeConfig],
+ resume: Optional[AdyenResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ resume_window = _to_datetime(resume.window_start) if resume is not None else None
+ cursor = resume.cursor if resume is not None else None
+
+ for window_start, window_end in iter_windows(start, end):
+ # Skip windows already walked to completion before the interruption.
+ if resume_window is not None and window_start < resume_window:
+ continue
+ page_cursor = cursor if resume_window is not None and window_start == resume_window else None
+ resume_window = None
+
+ while True:
+ params: dict[str, Any] = {
+ "balancePlatform": balance_platform,
+ "createdSince": _format_timestamp(window_start),
+ "createdUntil": _format_timestamp(window_end),
+ "limit": PAGE_SIZE,
+ "sortOrder": "asc",
+ }
+ if page_cursor:
+ params["cursor"] = page_cursor
+
+ payload = _request(session, _build_url(host, config.path, params), logger).json()
+ items = extract_items(payload, config.data_key)
+ if items:
+ yield items
+
+ page_cursor = next_cursor(payload)
+ if not page_cursor:
+ break
+
+ # Checkpoint after yielding, so a crash re-yields the last batch (merge dedupes on
+ # the primary key) instead of skipping it.
+ manager.save_state(
+ AdyenResumeConfig(window_start=_format_timestamp(window_start), cursor=page_cursor),
+ )
+
+
+def _iter_offset_pages(
+ session: requests.Session,
+ host: str,
+ path: str,
+ data_key: Optional[str],
+ logger: FilteringBoundLogger,
+ start_offset: int = 0,
+ on_page: Callable[[int], None] | None = None,
+) -> Iterator[list[dict[str, Any]]]:
+ offset = start_offset
+ while True:
+ payload = _request(session, _build_url(host, path, {"limit": PAGE_SIZE, "offset": offset}), logger).json()
+ items = extract_items(payload, data_key)
+ if not items:
+ return
+
+ yield items
+
+ if len(items) < PAGE_SIZE:
+ return
+
+ offset += PAGE_SIZE
+ if on_page is not None:
+ on_page(offset)
+
+
+def _iter_page_number_pages(
+ session: requests.Session,
+ host: str,
+ path: str,
+ data_key: Optional[str],
+ logger: FilteringBoundLogger,
+ manager: ResumableSourceManager[AdyenResumeConfig],
+ start_page: int = 1,
+) -> Iterator[list[dict[str, Any]]]:
+ page_number = start_page
+ while True:
+ params = {"pageSize": PAGE_SIZE, "pageNumber": page_number}
+ payload = _request(session, _build_url(host, path, params), logger).json()
+ items = extract_items(payload, data_key)
+ if not items:
+ return
+
+ yield items
+
+ pages_total = payload.get("pagesTotal") if isinstance(payload, dict) else None
+ if len(items) < PAGE_SIZE or (isinstance(pages_total, int) and page_number >= pages_total):
+ return
+
+ page_number += 1
+ manager.save_state(AdyenResumeConfig(page_number=page_number))
+
+
+def _iter_fanout_pages(
+ session: requests.Session,
+ config: AdyenEndpointConfig,
+ host: str,
+ balance_platform: str,
+ logger: FilteringBoundLogger,
+ manager: ResumableSourceManager[AdyenResumeConfig],
+ start_parent_index: int,
+) -> Iterator[list[dict[str, Any]]]:
+ parent = ADYEN_ENDPOINTS[config.parent] if config.parent else None
+ if parent is None:
+ raise AdyenConfigurationError(f"Adyen endpoint {config.name} has no parent endpoint configured.")
+
+ parent_path = parent.path.format(balance_platform=balance_platform)
+ parent_ids: list[str] = []
+ for page in _iter_offset_pages(session, host, parent_path, parent.data_key, logger):
+ parent_ids.extend(str(item["id"]) for item in page if item.get("id"))
+
+ for index, parent_id in enumerate(parent_ids):
+ if index < start_parent_index:
+ continue
+ child_path = config.path.format(parent_id=parent_id)
+ for page in _iter_offset_pages(session, host, child_path, config.data_key, logger):
+ yield page
+ manager.save_state(AdyenResumeConfig(parent_index=index + 1))
+
+
+def _iter_report_batches(
+ session: requests.Session,
+ config: AdyenEndpointConfig,
+ host: str,
+ merchant_account: str,
+ logger: FilteringBoundLogger,
+ manager: ResumableSourceManager[AdyenResumeConfig],
+ start_batch: int,
+) -> Iterator[list[dict[str, Any]]]:
+ batch_number = max(start_batch, 1)
+ last_batch = batch_number + MAX_BATCHES_PER_SYNC
+ consecutive_misses = 0
+
+ while batch_number < last_batch:
+ file_name = config.path.format(batch_number=batch_number)
+ url = f"{host}/reports/download/MerchantAccount/{merchant_account}/{file_name}"
+ # `stream=True` so a large settlement report is parsed incrementally instead of buffered
+ # whole in the worker (a report file can be very large for a high-volume merchant).
+ response = session.get(
+ url,
+ # Adyen only compresses the download when the client advertises gzip.
+ headers={"Accept": "text/csv", "Accept-Encoding": "gzip"},
+ timeout=REPORT_TIMEOUT_SECONDS,
+ stream=True,
+ )
+
+ if response.status_code == 404:
+ response.close()
+ consecutive_misses += 1
+ if consecutive_misses > MAX_CONSECUTIVE_MISSING_BATCHES:
+ logger.debug(f"Adyen: no settlement report at batch {batch_number}, stopping")
+ return
+ batch_number += 1
+ continue
+
+ if not response.ok:
+ logger.error(f"Adyen report download error: status={response.status_code}, url={url}")
+ response.close()
+ response.raise_for_status()
+
+ consecutive_misses = 0
+ chunk: list[dict[str, Any]] = []
+ try:
+ # Decode gzip on the fly and read physical lines off the socket so quoted multi-line
+ # CSV fields survive (unlike `iter_lines`, which strips the terminators csv needs).
+ response.raw.decode_content = True
+ lines = codecs.getreader("utf-8")(response.raw)
+ for row in parse_report_rows(lines, batch_number, logger):
+ chunk.append(row)
+ if len(chunk) >= REPORT_CHUNK_SIZE:
+ yield chunk
+ chunk = []
+ if chunk:
+ yield chunk
+ finally:
+ response.close()
+
+ manager.save_state(AdyenResumeConfig(batch_number=batch_number))
+ batch_number += 1
+
+
+def get_rows(
+ environment: Optional[str],
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[AdyenResumeConfig],
+ balance_platform: Optional[str] = None,
+ merchant_account: Optional[str] = None,
+ start_date: Optional[str] = None,
+ settlement_report_start_batch: Optional[int] = None,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = ADYEN_ENDPOINTS[endpoint]
+ host = base_url(environment, config.api)
+ session = _get_session(api_key)
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+
+ if config.pagination == "report_batch":
+ account = _require_identifier(merchant_account, "Merchant account")
+ watermark = _to_batch_number(db_incremental_field_last_value) if should_use_incremental_field else None
+ if resume is not None and resume.batch_number is not None:
+ start_batch = resume.batch_number + 1
+ elif watermark is not None:
+ start_batch = watermark + 1
+ else:
+ start_batch = settlement_report_start_batch or 1
+ yield from _iter_report_batches(session, config, host, account, logger, resumable_source_manager, start_batch)
+ return
+
+ if config.pagination == "cursor":
+ platform = _require_identifier(balance_platform, "Balance platform ID")
+ now = datetime.now(UTC)
+ start = _resolve_start(start_date, should_use_incremental_field, db_incremental_field_last_value, now)
+ yield from _iter_cursor_pages(
+ session, config, host, platform, start, now, logger, resumable_source_manager, resume
+ )
+ return
+
+ if config.pagination == "fanout_offset":
+ platform = _require_identifier(balance_platform, "Balance platform ID")
+ start_parent_index = resume.parent_index if resume is not None and resume.parent_index is not None else 0
+ yield from _iter_fanout_pages(
+ session, config, host, platform, logger, resumable_source_manager, start_parent_index
+ )
+ return
+
+ if config.pagination == "offset":
+ platform = _require_identifier(balance_platform, "Balance platform ID")
+ path = config.path.format(balance_platform=platform)
+ start_offset = resume.offset if resume is not None and resume.offset is not None else 0
+
+ def checkpoint(offset: int) -> None:
+ resumable_source_manager.save_state(AdyenResumeConfig(offset=offset))
+
+ yield from _iter_offset_pages(
+ session, host, path, config.data_key, logger, start_offset=start_offset, on_page=checkpoint
+ )
+ return
+
+ start_page = resume.page_number if resume is not None and resume.page_number is not None else 1
+ yield from _iter_page_number_pages(
+ session, host, config.path, config.data_key, logger, resumable_source_manager, start_page
+ )
+
+
+def adyen_source(
+ environment: Optional[str],
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[AdyenResumeConfig],
+ balance_platform: Optional[str] = None,
+ merchant_account: Optional[str] = None,
+ start_date: Optional[str] = None,
+ settlement_report_start_batch: Optional[int] = None,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> SourceResponse:
+ config = ADYEN_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ environment=environment,
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ balance_platform=balance_platform,
+ merchant_account=merchant_account,
+ start_date=start_date,
+ settlement_report_start_batch=settlement_report_start_batch,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ primary_keys=list(config.primary_key),
+ # Every paginated endpoint is walked oldest-first (`sortOrder=asc`, ascending offsets,
+ # ascending report batch numbers), so the incremental watermark only ever moves forward.
+ sort_mode="asc",
+ 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,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/adyen/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/adyen/canonical_descriptions.py
new file mode 100644
index 000000000000..a4b3a8fc0278
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/adyen/canonical_descriptions.py
@@ -0,0 +1,135 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "Transactions": {
+ "description": "A movement of funds booked against a balance account in your balance platform.",
+ "docs_url": "https://docs.adyen.com/api-explorer/transfers/4/get/transactions",
+ "columns": {
+ "id": "Unique identifier of the transaction.",
+ "accountHolder": "The account holder that the transaction belongs to.",
+ "balanceAccount": "The balance account that the funds moved in or out of.",
+ "balancePlatform": "Unique identifier of the balance platform.",
+ "amount": "The amount of the transaction, as a currency code and a value in minor units.",
+ "bookingDate": "Date the transaction was booked to the balance account.",
+ "creationDate": "Date and time the transaction was created.",
+ "description": "Description of the transaction.",
+ "paymentInstrument": "The payment instrument, such as a card, involved in the transaction.",
+ "referenceForBeneficiary": "Reference sent to the beneficiary of the transfer.",
+ "status": "Status of the transaction: pending or booked.",
+ "transfer": "The transfer that this transaction was created for.",
+ "valueDate": "Date the funds are made available on the balance account.",
+ },
+ },
+ "Transfers": {
+ "description": "An instruction to move funds, such as a payout, top-up or internal transfer.",
+ "docs_url": "https://docs.adyen.com/api-explorer/transfers/4/get/transfers",
+ "columns": {
+ "id": "Unique identifier of the transfer.",
+ "accountHolder": "The account holder that the transfer belongs to.",
+ "amount": "The amount of the transfer, as a currency code and a value in minor units.",
+ "balanceAccount": "The balance account the funds moved from or to.",
+ "balancePlatform": "Unique identifier of the balance platform.",
+ "balances": "The balances affected by the transfer, per currency.",
+ "category": "Type of transfer: bank, card, internal, issuedCard, platformPayment or topUp.",
+ "categoryData": "Extra data specific to the transfer category.",
+ "counterparty": "The other party in the transfer, such as a bank account or balance account.",
+ "createdAt": "Date and time the transfer was created.",
+ "description": "Description of the transfer.",
+ "direction": "Direction of the transfer: incoming or outgoing.",
+ "reason": "Reason the transfer has its current status.",
+ "reference": "Your reference for the transfer.",
+ "referenceForBeneficiary": "Reference sent to the beneficiary of the transfer.",
+ "status": "Status of the transfer, for example authorised, booked or failed.",
+ },
+ },
+ "AccountHolders": {
+ "description": "A legal entity you onboarded onto your balance platform, holding one or more balance accounts.",
+ "docs_url": "https://docs.adyen.com/api-explorer/balanceplatform/2/get/balancePlatforms/(id)/accountHolders",
+ "columns": {
+ "id": "Unique identifier of the account holder.",
+ "balancePlatform": "Unique identifier of the balance platform the account holder belongs to.",
+ "capabilities": "The capabilities enabled for the account holder, with their verification status.",
+ "description": "Your description of the account holder.",
+ "legalEntityId": "Unique identifier of the legal entity associated with the account holder.",
+ "primaryBalanceAccount": "Unique identifier of the account holder's primary balance account.",
+ "reference": "Your reference for the account holder.",
+ "status": "Status of the account holder: active, inactive, suspended or closed.",
+ "timeZone": "Time zone of the account holder.",
+ },
+ },
+ "BalanceAccounts": {
+ "description": "A balance account holding funds for an account holder in your balance platform.",
+ "docs_url": "https://docs.adyen.com/api-explorer/balanceplatform/2/get/accountHolders/(id)/balanceAccounts",
+ "columns": {
+ "id": "Unique identifier of the balance account.",
+ "accountHolderId": "Unique identifier of the account holder the balance account belongs to.",
+ "defaultCurrencyCode": "Three-character ISO currency code of the balance account's default currency.",
+ "description": "Your description of the balance account.",
+ "reference": "Your reference for the balance account.",
+ "status": "Status of the balance account: active, inactive, suspended or closed.",
+ "timeZone": "Time zone of the balance account.",
+ },
+ },
+ "Companies": {
+ "description": "A company account your API credential can access.",
+ "docs_url": "https://docs.adyen.com/api-explorer/Management/3/get/companies",
+ "columns": {
+ "id": "Unique identifier of the company account.",
+ "name": "Legal or trading name of the company.",
+ "description": "Your description of the company account.",
+ "reference": "Your reference for the company account.",
+ "status": "Status of the company account: Active, Inactive or Closed.",
+ "dataCenters": "Data centers the company account processes in, with their live URL prefixes.",
+ },
+ },
+ "MerchantAccounts": {
+ "description": "A merchant account your API credential can access, with its processing configuration.",
+ "docs_url": "https://docs.adyen.com/api-explorer/Management/3/get/merchants",
+ "columns": {
+ "id": "Unique identifier of the merchant account.",
+ "name": "Name of the merchant account.",
+ "companyId": "Unique identifier of the company account the merchant account belongs to.",
+ "description": "Your description of the merchant account.",
+ "reference": "Your reference for the merchant account.",
+ "status": "Status of the merchant account, for example PreActive, Active or Closed.",
+ "captureDelay": "When payments are captured: immediate, manual, or a number of days.",
+ "merchantCity": "City where the merchant account is registered.",
+ "primarySettlementCurrency": "Three-character ISO code of the currency the account settles in.",
+ "shopWebAddress": "Website of the shop linked to the merchant account.",
+ "dataCenters": "Data centers the merchant account processes in, with their live URL prefixes.",
+ "defaultShopperInteraction": "Default shopper interaction used when processing payments.",
+ "pricingPlan": "Pricing plan of the merchant account, for partner-managed accounts.",
+ },
+ },
+ "SettlementDetailReports": {
+ "description": "Transaction-level rows from Adyen's settlement details report: one line per settled payment, modification or fee.",
+ "docs_url": "https://docs.adyen.com/reporting/settlement-reconciliation/transaction-level/settlement-details-report",
+ "columns": {
+ "batch_number": "Settlement batch this row belongs to. Batches are numbered sequentially per merchant account.",
+ "company_account": "Company account the settled transaction belongs to.",
+ "merchant_account": "Merchant account the settled transaction belongs to.",
+ "psp_reference": "Adyen's unique reference for the original payment.",
+ "merchant_reference": "Your own reference for the payment.",
+ "payment_method": "Payment method used, for example visa or ideal.",
+ "creation_date": "Date and time the record was created, in the report's time zone.",
+ "timezone": "Time zone the report dates are expressed in.",
+ "type": "Type of record, for example Settled, Refunded, Chargeback or Fee.",
+ "modification_reference": "Reference of the modification (capture, refund, chargeback) this row records.",
+ "gross_currency": "Currency the gross amounts are expressed in.",
+ "gross_debit_gc": "Gross amount debited, in the gross currency.",
+ "gross_credit_gc": "Gross amount credited, in the gross currency.",
+ "exchange_rate": "Rate used to convert the gross amount into the net currency.",
+ "net_currency": "Currency the net amounts and fees are expressed in.",
+ "net_debit_nc": "Net amount debited, in the net currency.",
+ "net_credit_nc": "Net amount credited, in the net currency.",
+ "commission_nc": "Adyen's processing commission, in the net currency.",
+ "markup_nc": "Adyen's markup, in the net currency.",
+ "scheme_fees_nc": "Card scheme fees, in the net currency.",
+ "interchange_nc": "Interchange fees paid to the issuer, in the net currency.",
+ "payment_method_variant": "Specific variant of the payment method, for example mc_debit.",
+ "modification_merchant_reference": "Your reference for the modification this row records.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/adyen/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/adyen/settings.py
new file mode 100644
index 000000000000..a00b9ac83a64
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/adyen/settings.py
@@ -0,0 +1,124 @@
+from dataclasses import dataclass
+from typing import Literal
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# Adyen splits its read APIs across three hosts with independent versions, so each endpoint
+# names the API it belongs to rather than sharing one base URL.
+AdyenApi = Literal["transfers", "configuration", "management", "reports"]
+
+# `cursor` — Transfers API `_links.next` with an opaque `cursor` query param.
+# `offset` — Configuration API `offset`/`limit`.
+# `page` — Management API `pageNumber`/`pageSize`.
+# `fanout_offset` — offset pagination per parent id resolved from another endpoint.
+# `report_batch` — no pagination: walk sequential report batch numbers, one CSV file each.
+AdyenPagination = Literal["cursor", "offset", "page", "fanout_offset", "report_batch"]
+
+
+@dataclass(frozen=True)
+class AdyenEndpointConfig:
+ name: str
+ api: AdyenApi
+ path: str
+ primary_key: tuple[str, ...]
+ pagination: AdyenPagination
+ # Key the rows live under in the JSON body (unused for report endpoints).
+ data_key: str | None = None
+ # Transfers endpoints reject requests without a createdSince/createdUntil window.
+ window_filtered: bool = False
+ partition_key: str | None = None
+ requires_balance_platform: bool = False
+ requires_merchant_account: bool = False
+ # Fan-out children: the endpoint whose row ids fill the `{parent_id}` placeholder.
+ parent: str | None = None
+ description: str = ""
+
+
+ADYEN_ENDPOINTS: dict[str, AdyenEndpointConfig] = {
+ "AccountHolders": AdyenEndpointConfig(
+ name="AccountHolders",
+ api="configuration",
+ path="/balancePlatforms/{balance_platform}/accountHolders",
+ primary_key=("id",),
+ pagination="offset",
+ data_key="accountHolders",
+ requires_balance_platform=True,
+ description="Account holders in your balance platform, each representing a legal entity you onboarded.",
+ ),
+ "BalanceAccounts": AdyenEndpointConfig(
+ name="BalanceAccounts",
+ api="configuration",
+ path="/accountHolders/{parent_id}/balanceAccounts",
+ primary_key=("id",),
+ pagination="fanout_offset",
+ data_key="balanceAccounts",
+ parent="AccountHolders",
+ requires_balance_platform=True,
+ description="Balance accounts holding funds for each account holder in your balance platform.",
+ ),
+ "Companies": AdyenEndpointConfig(
+ name="Companies",
+ api="management",
+ path="/companies",
+ primary_key=("id",),
+ pagination="page",
+ data_key="data",
+ description="Company accounts your API credential can access.",
+ ),
+ "MerchantAccounts": AdyenEndpointConfig(
+ name="MerchantAccounts",
+ api="management",
+ path="/merchants",
+ primary_key=("id",),
+ pagination="page",
+ data_key="data",
+ description="Merchant accounts your API credential can access, with their processing configuration.",
+ ),
+ "SettlementDetailReports": AdyenEndpointConfig(
+ name="SettlementDetailReports",
+ api="reports",
+ path="settlement_detail_report_batch_{batch_number}.csv",
+ primary_key=("batch_number", "psp_reference", "type", "modification_reference"),
+ pagination="report_batch",
+ requires_merchant_account=True,
+ description="Transaction-level settlement lines from the settlement details report, one row per settled payment or fee.",
+ ),
+ "Transactions": AdyenEndpointConfig(
+ name="Transactions",
+ api="transfers",
+ path="/transactions",
+ primary_key=("id",),
+ pagination="cursor",
+ data_key="data",
+ window_filtered=True,
+ partition_key="creationDate",
+ requires_balance_platform=True,
+ description="Individual movements of funds booked against a balance account.",
+ ),
+ "Transfers": AdyenEndpointConfig(
+ name="Transfers",
+ api="transfers",
+ path="/transfers",
+ primary_key=("id",),
+ pagination="cursor",
+ data_key="data",
+ window_filtered=True,
+ partition_key="createdAt",
+ requires_balance_platform=True,
+ description="Transfer instructions such as payouts, top-ups and internal transfers.",
+ ),
+}
+
+ENDPOINTS = tuple(ADYEN_ENDPOINTS.keys())
+
+# Only endpoints with a real server-side filter are incremental: the Transfers API filters on
+# `createdSince`/`createdUntil`, and settlement reports are addressed by an ascending batch
+# number. The Configuration and Management endpoints expose no updated-since filter.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ "Transactions": [incremental_field("creationDate")],
+ "Transfers": [incremental_field("createdAt")],
+ "SettlementDetailReports": [incremental_field("batch_number", IncrementalFieldType.Integer)],
+}
+
+ENDPOINT_DESCRIPTIONS: dict[str, str] = {name: config.description for name, config in ADYEN_ENDPOINTS.items()}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/adyen/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/adyen/source.py
index cca7b8cfd24b..08c857ee9b98 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/adyen/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/adyen/source.py
@@ -1,30 +1,207 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+ SourceFieldSelectConfig,
+ SourceFieldSelectConfigOption,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.adyen.adyen import (
+ AdyenResumeConfig,
+ adyen_source,
+ validate_credentials as validate_adyen_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.adyen.settings import (
+ ADYEN_ENDPOINTS,
+ ENDPOINT_DESCRIPTIONS,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.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.adyen import AdyenSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
+CAPTION = """Connect your Adyen account to sync payments data into the PostHog Data warehouse.
+
+Create an API credential in your Adyen Customer Area under **Developers > API credentials**, then paste its API key below. Which tables you can sync depends on what that credential can reach:
+
+- **Transactions, transfers, account holders and balance accounts** need an Adyen for Platforms or Adyen Issuing integration. Add your balance platform ID too.
+- **Settlement detail reports** need a merchant account and the **Merchant Report Download** role. Adyen only creates these files once you turn on the settlement details report in your Customer Area.
+- **Companies and merchant accounts** come from the Management API and need an account read role.
+
+Pick the environment that matches where you created the API key — a test key won't work against live."""
+
@SourceRegistry.register
-class AdyenSource(SimpleSource[AdyenSourceConfig]):
+class AdyenSource(ResumableSource[AdyenSourceConfig, AdyenResumeConfig]):
+ # Adyen versions each of its APIs separately (Transfers v4, Configuration v2, Management v3),
+ # so there is no single version token to pin for the source as a whole.
+ api_docs_url = "https://docs.adyen.com/api-explorer/"
+
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.ADYEN
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized": "Adyen rejected the API key. Check the key, and that it matches the environment you selected.",
+ "403 Client Error: Forbidden": "Adyen denied access. Check that the API credential has the roles needed for the tables you're syncing.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.adyen.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: AdyenSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ # Adyen accounts reach either the balance platform tables or the merchant report, rarely
+ # both, so a table whose identifier is missing starts unselected instead of failing its
+ # first sync.
+ has_platform = bool((config.balance_platform or "").strip())
+ has_merchant = bool((config.merchant_account or "").strip())
+ should_sync_default = {
+ name: (has_platform or not endpoint.requires_balance_platform)
+ and (has_merchant or not endpoint.requires_merchant_account)
+ for name, endpoint in ADYEN_ENDPOINTS.items()
+ }
+
+ return build_endpoint_schemas(
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ names,
+ descriptions=ENDPOINT_DESCRIPTIONS,
+ should_sync_default=should_sync_default,
+ )
+
+ def validate_credentials(
+ self,
+ config: AdyenSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ return validate_adyen_credentials(
+ environment=config.environment,
+ api_key=config.api_key,
+ balance_platform=config.balance_platform,
+ merchant_account=config.merchant_account,
+ )
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AdyenResumeConfig]:
+ return ResumableSourceManager[AdyenResumeConfig](inputs, AdyenResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: AdyenSourceConfig,
+ resumable_source_manager: ResumableSourceManager[AdyenResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return adyen_source(
+ environment=config.environment,
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ balance_platform=config.balance_platform,
+ merchant_account=config.merchant_account,
+ start_date=config.start_date,
+ settlement_report_start_batch=config.settlement_report_start_batch,
+ 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.ADYEN,
category=DataWarehouseSourceCategory.PAYMENTS___BILLING,
label="Adyen",
+ caption=CAPTION,
+ docsUrl="https://posthog.com/docs/cdp/sources/adyen",
iconPath="/static/services/adyen.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldSelectConfig(
+ name="environment",
+ label="Environment",
+ required=True,
+ defaultValue="live",
+ options=[
+ SourceFieldSelectConfigOption(label="Live", value="live"),
+ SourceFieldSelectConfigOption(label="Test", value="test"),
+ ],
+ ),
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="balance_platform",
+ label="Balance platform ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="YOUR_BALANCE_PLATFORM",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="merchant_account",
+ label="Merchant account",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="YOUR_MERCHANT_ACCOUNT",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="start_date",
+ label="Start date",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="2024-01-01",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="settlement_report_start_batch",
+ label="First settlement batch number",
+ type=SourceFieldInputConfigType.NUMBER,
+ required=False,
+ placeholder="1",
+ secret=False,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/adyen/tests/test_adyen.py b/products/warehouse_sources/backend/temporal/data_imports/sources/adyen/tests/test_adyen.py
new file mode 100644
index 000000000000..495e87d89ec2
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/adyen/tests/test_adyen.py
@@ -0,0 +1,682 @@
+import io
+from collections.abc import Iterable
+from datetime import UTC, date, datetime, timedelta
+from typing import Any, Optional, cast
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+from unittest import mock
+
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.adyen import adyen as adyen_module
+from products.warehouse_sources.backend.temporal.data_imports.sources.adyen.adyen import (
+ MAX_CONSECUTIVE_MISSING_BATCHES,
+ MAX_WINDOW_DAYS,
+ PAGE_SIZE,
+ AdyenConfigurationError,
+ AdyenResumeConfig,
+ _iter_cursor_pages,
+ _require_identifier,
+ _to_batch_number,
+ _to_datetime,
+ adyen_source,
+ base_url,
+ extract_items,
+ get_rows,
+ iter_windows,
+ next_cursor,
+ normalize_header,
+ parse_report_rows,
+ resolve_environment,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.adyen.settings import ADYEN_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+
+class _FakeRaw:
+ """Stand-in for `response.raw`: a readable byte stream the report path streams CSV off."""
+
+ def __init__(self, data: bytes) -> None:
+ self._buffer = io.BytesIO(data)
+ self.decode_content = False
+
+ def read(self, *args: Any, **kwargs: Any) -> bytes:
+ return self._buffer.read(*args, **kwargs)
+
+
+class _FakeResponse:
+ def __init__(self, status_code: int = 200, json_data: Optional[dict[str, Any]] = None, text: str = "") -> None:
+ self.status_code = status_code
+ self._json_data = json_data if json_data is not None else {}
+ self.text = text
+ self.raw = _FakeRaw(text.encode())
+ self.closed = False
+
+ @property
+ def ok(self) -> bool:
+ return self.status_code < 400
+
+ def json(self) -> dict[str, Any]:
+ return self._json_data
+
+ def raise_for_status(self) -> None:
+ if not self.ok:
+ raise Exception(f"{self.status_code} Client Error for url")
+
+ def close(self) -> None:
+ self.closed = True
+
+
+class _FakeSession:
+ """Replays a queued list of responses and records the URLs that were requested."""
+
+ def __init__(self, responses: list[_FakeResponse]) -> None:
+ self._responses = list(responses)
+ self.requested_urls: list[str] = []
+ self.requested_headers: list[Optional[dict[str, str]]] = []
+
+ def get(
+ self,
+ url: str,
+ headers: Optional[dict[str, str]] = None,
+ timeout: Optional[int] = None,
+ stream: bool = False,
+ ) -> _FakeResponse:
+ self.requested_urls.append(url)
+ self.requested_headers.append(headers)
+ if not self._responses:
+ raise AssertionError(f"unexpected request to {url}")
+ return self._responses.pop(0)
+
+
+class _FakeManager(ResumableSourceManager[AdyenResumeConfig]):
+ """In-memory stand-in for the Redis-backed manager (no `super().__init__`)."""
+
+ def __init__(self, resume_state: Optional[AdyenResumeConfig] = None) -> None:
+ self._resume_state = resume_state
+ self.saved_states: list[AdyenResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._resume_state is not None
+
+ def load_state(self) -> Optional[AdyenResumeConfig]:
+ return self._resume_state
+
+ def save_state(self, data: AdyenResumeConfig) -> None:
+ self.saved_states.append(data)
+
+
+def _query(url: str) -> dict[str, list[str]]:
+ return parse_qs(urlparse(url).query)
+
+
+def _drain(
+ session: _FakeSession,
+ endpoint: str,
+ manager: _FakeManager,
+ **kwargs: Any,
+) -> list[dict[str, Any]]:
+ with mock.patch.object(adyen_module, "_get_session", return_value=session):
+ rows: list[dict[str, Any]] = []
+ for batch in get_rows(
+ environment="test",
+ api_key="key",
+ endpoint=endpoint,
+ logger=mock.MagicMock(),
+ resumable_source_manager=manager,
+ **kwargs,
+ ):
+ rows.extend(batch)
+ return rows
+
+
+class TestHosts:
+ @parameterized.expand(
+ [
+ ("test_transfers", "test", "transfers", "https://balanceplatform-api-test.adyen.com/btl/v4"),
+ ("live_transfers", "live", "transfers", "https://balanceplatform-api-live.adyen.com/btl/v4"),
+ ("test_configuration", "test", "configuration", "https://balanceplatform-api-test.adyen.com/bcl/v2"),
+ ("live_management", "live", "management", "https://management-live.adyen.com/v3"),
+ ("test_reports", "test", "reports", "https://ca-test.adyen.com"),
+ # An unrecognised environment can never retarget the API key at another host.
+ ("unknown_falls_back_to_live", "evil.example.com", "management", "https://management-live.adyen.com/v3"),
+ ("none_falls_back_to_live", None, "reports", "https://ca-live.adyen.com"),
+ ]
+ )
+ def test_base_url(self, _name: str, environment: Optional[str], api: Any, expected: str) -> None:
+ assert base_url(environment, api) == expected
+
+ @parameterized.expand([("test", "test", "test"), ("live", "live", "live"), ("junk", "junk", "live")])
+ def test_resolve_environment(self, _name: str, value: str, expected: str) -> None:
+ assert resolve_environment(value) == expected
+
+
+class TestRequireIdentifier:
+ def test_accepts_a_plain_identifier(self) -> None:
+ assert _require_identifier(" YOUR_BALANCE_PLATFORM ", "Balance platform ID") == "YOUR_BALANCE_PLATFORM"
+
+ @parameterized.expand(
+ [
+ ("empty", ""),
+ ("whitespace", " "),
+ ("none", None),
+ ("path_traversal", "../../secrets"),
+ ("slash", "acct/other"),
+ ("query_injection", "acct?limit=1"),
+ ]
+ )
+ def test_rejects_unusable_values(self, _name: str, value: Optional[str]) -> None:
+ with pytest.raises(AdyenConfigurationError):
+ _require_identifier(value, "Merchant account")
+
+
+class TestCoercion:
+ @parameterized.expand(
+ [
+ ("aware_datetime", datetime(2026, 3, 4, 5, 6, 7, tzinfo=UTC), datetime(2026, 3, 4, 5, 6, 7, tzinfo=UTC)),
+ ("naive_datetime", datetime(2026, 3, 4, 5, 6, 7), datetime(2026, 3, 4, 5, 6, 7, tzinfo=UTC)),
+ ("date", date(2026, 3, 4), datetime(2026, 3, 4, tzinfo=UTC)),
+ ("iso_string", "2026-03-04T05:06:07Z", datetime(2026, 3, 4, 5, 6, 7, tzinfo=UTC)),
+ ("date_string", "2026-03-04", datetime(2026, 3, 4, tzinfo=UTC)),
+ ("garbage", "not-a-date", None),
+ ("none", None, None),
+ ]
+ )
+ def test_to_datetime(self, _name: str, value: Any, expected: Optional[datetime]) -> None:
+ assert _to_datetime(value) == expected
+
+ @parameterized.expand(
+ [("int", 12, 12), ("str", "12", 12), ("float_str", "12.0", 12), ("garbage", "abc", None), ("none", None, None)]
+ )
+ def test_to_batch_number(self, _name: str, value: Any, expected: Optional[int]) -> None:
+ assert _to_batch_number(value) == expected
+
+
+class TestIterWindows:
+ def test_short_range_is_a_single_window(self) -> None:
+ start = datetime(2026, 1, 1, tzinfo=UTC)
+ end = start + timedelta(days=3)
+ assert list(iter_windows(start, end)) == [(start, end)]
+
+ def test_long_range_is_split_into_contiguous_ascending_windows(self) -> None:
+ start = datetime(2026, 1, 1, tzinfo=UTC)
+ end = start + timedelta(days=MAX_WINDOW_DAYS * 2 + 10)
+
+ windows = list(iter_windows(start, end))
+
+ assert len(windows) == 3
+ assert windows[0][0] == start
+ assert windows[-1][1] == end
+ for (_, previous_end), (next_start, _) in zip(windows, windows[1:]):
+ assert previous_end == next_start
+ for window_start, window_end in windows:
+ assert window_end - window_start <= timedelta(days=MAX_WINDOW_DAYS)
+
+ @parameterized.expand([("equal", 0), ("inverted", -5)])
+ def test_no_windows_when_end_not_after_start(self, _name: str, offset_days: int) -> None:
+ start = datetime(2026, 1, 1, tzinfo=UTC)
+ assert list(iter_windows(start, start + timedelta(days=offset_days))) == []
+
+
+class TestResponseParsing:
+ @parameterized.expand(
+ [
+ (
+ "cursor_present",
+ {"_links": {"next": {"href": "https://x/btl/v4/transfers?cursor=abc&limit=100"}}},
+ "abc",
+ ),
+ ("no_links", {"data": []}, None),
+ ("no_next", {"_links": {"prev": {"href": "https://x?cursor=old"}}}, None),
+ ("next_without_cursor", {"_links": {"next": {"href": "https://x/btl/v4/transfers?limit=100"}}}, None),
+ ("next_not_an_object", {"_links": {"next": "https://x?cursor=abc"}}, None),
+ ("not_a_dict", ["nope"], None),
+ ]
+ )
+ def test_next_cursor(self, _name: str, payload: Any, expected: Optional[str]) -> None:
+ assert next_cursor(payload) == expected
+
+ @parameterized.expand(
+ [
+ ("keyed", {"data": [{"id": "1"}]}, "data", [{"id": "1"}]),
+ ("missing_key", {"other": [{"id": "1"}]}, "data", []),
+ ("bare_list", [{"id": "1"}], None, [{"id": "1"}]),
+ ("non_dict_items_dropped", {"data": [{"id": "1"}, "junk", None]}, "data", [{"id": "1"}]),
+ ("non_list_value", {"data": {"id": "1"}}, "data", []),
+ ]
+ )
+ def test_extract_items(
+ self, _name: str, payload: Any, data_key: Optional[str], expected: list[dict[str, Any]]
+ ) -> None:
+ assert extract_items(payload, data_key) == expected
+
+
+class TestReportParsing:
+ @parameterized.expand(
+ [
+ ("simple", "Psp Reference", "psp_reference"),
+ ("parenthesised", "Gross Debit (GC)", "gross_debit_gc"),
+ ("already_snake", "batch_number", "batch_number"),
+ ("mixed_punctuation", "Modification Merchant Reference", "modification_merchant_reference"),
+ ]
+ )
+ def test_normalize_header(self, _name: str, header: str, expected: str) -> None:
+ assert normalize_header(header) == expected
+
+ def test_rows_are_normalized_and_stamped_with_the_requested_batch(self) -> None:
+ text = "Psp Reference,Type,Gross Debit (GC),Batch Number\nABC123,Settled,10.00,7\n"
+
+ rows = list(parse_report_rows(io.StringIO(text), 7, mock.MagicMock()))
+
+ assert rows == [
+ {
+ "psp_reference": "ABC123",
+ "type": "Settled",
+ "gross_debit_gc": "10.00",
+ # The requested batch is the authoritative integer watermark, so it overrides
+ # the report's own string column.
+ "batch_number": 7,
+ }
+ ]
+
+ def test_blank_and_malformed_rows_are_skipped(self) -> None:
+ logger = mock.MagicMock()
+ text = "Psp Reference,Type\nABC,Settled\n\nSHORT\nDEF,Refunded\n"
+
+ rows = list(parse_report_rows(io.StringIO(text), 1, logger))
+
+ assert [row["psp_reference"] for row in rows] == ["ABC", "DEF"]
+ assert logger.warning.call_count == 1
+
+ def test_empty_report_yields_nothing(self) -> None:
+ assert list(parse_report_rows(io.StringIO(""), 1, mock.MagicMock())) == []
+
+
+class TestValidateCredentials:
+ @parameterized.expand(
+ [
+ ("ok", 200, True),
+ # A report-only credential legitimately lacks the Management API role.
+ ("forbidden_is_still_a_real_key", 403, True),
+ ("unauthorized", 401, False),
+ ("server_error", 500, False),
+ ]
+ )
+ def test_status_mapping(self, _name: str, status_code: int, expected_valid: bool) -> None:
+ session = _FakeSession([_FakeResponse(status_code=status_code)])
+ with mock.patch.object(adyen_module, "_get_session", return_value=session):
+ is_valid, message = validate_credentials("test", "key")
+
+ assert is_valid is expected_valid
+ assert (message is None) is expected_valid
+ assert session.requested_urls == ["https://management-test.adyen.com/v3/me"]
+
+ @parameterized.expand([("reachable", 200, True), ("still_rejected", 401, False)])
+ def test_balance_platform_key_unknown_to_the_management_api_falls_back(
+ self, _name: str, fallback_status: int, expected_valid: bool
+ ) -> None:
+ # A key issued in a Balance Platform Customer Area can 401 against Management API.
+ session = _FakeSession([_FakeResponse(status_code=401), _FakeResponse(status_code=fallback_status)])
+ with mock.patch.object(adyen_module, "_get_session", return_value=session):
+ is_valid, _ = validate_credentials("test", "key", balance_platform="BP123")
+
+ assert is_valid is expected_valid
+ assert session.requested_urls[1] == "https://balanceplatform-api-test.adyen.com/bcl/v2/balancePlatforms/BP123"
+
+ def test_no_fallback_without_a_balance_platform(self) -> None:
+ session = _FakeSession([_FakeResponse(status_code=401)])
+ with mock.patch.object(adyen_module, "_get_session", return_value=session):
+ is_valid, _ = validate_credentials("test", "key")
+
+ assert is_valid is False
+ assert len(session.requested_urls) == 1
+
+ def test_malformed_identifier_fails_before_any_request(self) -> None:
+ session = _FakeSession([])
+ with mock.patch.object(adyen_module, "_get_session", return_value=session):
+ is_valid, message = validate_credentials("test", "key", merchant_account="../etc")
+
+ assert is_valid is False
+ assert message is not None
+ assert session.requested_urls == []
+
+ def test_transport_failure_is_reported_not_raised(self) -> None:
+ session = mock.MagicMock()
+ session.get.side_effect = adyen_module.requests.exceptions.ConnectionError("boom")
+ with mock.patch.object(adyen_module, "_get_session", return_value=session):
+ is_valid, message = validate_credentials("live", "key")
+
+ assert is_valid is False
+ assert message == "boom"
+
+
+class TestCursorPagination:
+ def _pages(self, session: _FakeSession, manager: _FakeManager, resume: Optional[AdyenResumeConfig] = None) -> list:
+ start = datetime(2026, 1, 1, tzinfo=UTC)
+ return list(
+ _iter_cursor_pages(
+ session=cast(Any, session),
+ config=ADYEN_ENDPOINTS["Transfers"],
+ host="https://balanceplatform-api-test.adyen.com/btl/v4",
+ balance_platform="BP123",
+ start=start,
+ end=start + timedelta(days=1),
+ logger=mock.MagicMock(),
+ manager=manager,
+ resume=resume,
+ )
+ )
+
+ def test_walks_pages_until_the_cursor_runs_out(self) -> None:
+ session = _FakeSession(
+ [
+ _FakeResponse(
+ json_data={"data": [{"id": "t1"}], "_links": {"next": {"href": "https://x?cursor=c2"}}},
+ ),
+ _FakeResponse(json_data={"data": [{"id": "t2"}]}),
+ ]
+ )
+ manager = _FakeManager()
+
+ pages = self._pages(session, manager)
+
+ assert [item["id"] for page in pages for item in page] == ["t1", "t2"]
+ assert _query(session.requested_urls[1])["cursor"] == ["c2"]
+
+ def test_first_request_carries_the_required_window_and_sort(self) -> None:
+ session = _FakeSession([_FakeResponse(json_data={"data": []})])
+
+ self._pages(session, _FakeManager())
+
+ params = _query(session.requested_urls[0])
+ assert params["balancePlatform"] == ["BP123"]
+ assert params["createdSince"] == ["2026-01-01T00:00:00Z"]
+ assert params["createdUntil"] == ["2026-01-02T00:00:00Z"]
+ assert params["sortOrder"] == ["asc"]
+ assert params["limit"] == [str(PAGE_SIZE)]
+ assert "cursor" not in params
+
+ def test_state_is_saved_after_each_yielded_page(self) -> None:
+ session = _FakeSession(
+ [
+ _FakeResponse(json_data={"data": [{"id": "t1"}], "_links": {"next": {"href": "https://x?cursor=c2"}}}),
+ _FakeResponse(json_data={"data": [{"id": "t2"}]}),
+ ]
+ )
+ manager = _FakeManager()
+
+ self._pages(session, manager)
+
+ assert [state.cursor for state in manager.saved_states] == ["c2"]
+ assert manager.saved_states[0].window_start == "2026-01-01T00:00:00Z"
+
+ def test_resume_starts_from_the_saved_cursor(self) -> None:
+ session = _FakeSession([_FakeResponse(json_data={"data": [{"id": "t9"}]})])
+ resume = AdyenResumeConfig(window_start="2026-01-01T00:00:00Z", cursor="saved-cursor")
+
+ pages = self._pages(session, _FakeManager(resume), resume=resume)
+
+ assert [item["id"] for page in pages for item in page] == ["t9"]
+ assert _query(session.requested_urls[0])["cursor"] == ["saved-cursor"]
+
+ def test_windows_before_the_saved_one_are_skipped(self) -> None:
+ session = _FakeSession([_FakeResponse(json_data={"data": [{"id": "later"}]})])
+ start = datetime(2026, 1, 1, tzinfo=UTC)
+ resume_window = start + timedelta(days=MAX_WINDOW_DAYS)
+ manager = _FakeManager()
+
+ pages = list(
+ _iter_cursor_pages(
+ session=cast(Any, session),
+ config=ADYEN_ENDPOINTS["Transactions"],
+ host="https://balanceplatform-api-test.adyen.com/btl/v4",
+ balance_platform="BP123",
+ start=start,
+ end=start + timedelta(days=MAX_WINDOW_DAYS + 5),
+ logger=mock.MagicMock(),
+ manager=manager,
+ resume=AdyenResumeConfig(window_start=resume_window.strftime("%Y-%m-%dT%H:%M:%SZ")),
+ )
+ )
+
+ # Only the second window is requested; the first was already completed.
+ assert len(session.requested_urls) == 1
+ assert _query(session.requested_urls[0])["createdSince"] == [resume_window.strftime("%Y-%m-%dT%H:%M:%SZ")]
+ assert [item["id"] for page in pages for item in page] == ["later"]
+
+ def test_missing_balance_platform_is_a_configuration_error(self) -> None:
+ with pytest.raises(AdyenConfigurationError):
+ _drain(_FakeSession([]), "Transfers", _FakeManager())
+
+
+class TestOffsetPagination:
+ def test_stops_on_a_short_page_and_checkpoints_the_offset(self) -> None:
+ session = _FakeSession(
+ [
+ _FakeResponse(json_data={"accountHolders": [{"id": f"AH{i}"} for i in range(PAGE_SIZE)]}),
+ _FakeResponse(json_data={"accountHolders": [{"id": "AH-last"}]}),
+ ]
+ )
+ manager = _FakeManager()
+
+ rows = _drain(session, "AccountHolders", manager, balance_platform="BP123")
+
+ assert len(rows) == PAGE_SIZE + 1
+ assert _query(session.requested_urls[0])["offset"] == ["0"]
+ assert _query(session.requested_urls[1])["offset"] == [str(PAGE_SIZE)]
+ assert [state.offset for state in manager.saved_states] == [PAGE_SIZE]
+
+ def test_resumes_from_the_saved_offset(self) -> None:
+ session = _FakeSession([_FakeResponse(json_data={"accountHolders": [{"id": "AH9"}]})])
+
+ rows = _drain(
+ session,
+ "AccountHolders",
+ _FakeManager(AdyenResumeConfig(offset=200)),
+ balance_platform="BP123",
+ )
+
+ assert [row["id"] for row in rows] == ["AH9"]
+ assert _query(session.requested_urls[0])["offset"] == ["200"]
+
+ def test_empty_first_page_yields_nothing(self) -> None:
+ session = _FakeSession([_FakeResponse(json_data={"accountHolders": []})])
+
+ assert _drain(session, "AccountHolders", _FakeManager(), balance_platform="BP123") == []
+
+
+class TestPageNumberPagination:
+ def test_stops_once_pages_total_is_reached(self) -> None:
+ session = _FakeSession(
+ [
+ _FakeResponse(
+ json_data={"data": [{"id": f"M{i}"} for i in range(PAGE_SIZE)], "pagesTotal": 2},
+ ),
+ _FakeResponse(
+ json_data={"data": [{"id": f"N{i}"} for i in range(PAGE_SIZE)], "pagesTotal": 2},
+ ),
+ ]
+ )
+ manager = _FakeManager()
+
+ rows = _drain(session, "MerchantAccounts", manager)
+
+ assert len(rows) == PAGE_SIZE * 2
+ assert _query(session.requested_urls[0])["pageNumber"] == ["1"]
+ assert _query(session.requested_urls[1])["pageNumber"] == ["2"]
+ assert [state.page_number for state in manager.saved_states] == [2]
+
+ def test_resumes_from_the_saved_page(self) -> None:
+ session = _FakeSession([_FakeResponse(json_data={"data": [{"id": "C1"}], "pagesTotal": 4})])
+
+ rows = _drain(session, "Companies", _FakeManager(AdyenResumeConfig(page_number=3)))
+
+ assert [row["id"] for row in rows] == ["C1"]
+ assert _query(session.requested_urls[0])["pageNumber"] == ["3"]
+
+
+class TestFanout:
+ def test_children_are_fetched_per_parent_and_checkpointed(self) -> None:
+ session = _FakeSession(
+ [
+ _FakeResponse(json_data={"accountHolders": [{"id": "AH1"}, {"id": "AH2"}]}),
+ _FakeResponse(json_data={"balanceAccounts": [{"id": "BA1", "accountHolderId": "AH1"}]}),
+ _FakeResponse(json_data={"balanceAccounts": [{"id": "BA2", "accountHolderId": "AH2"}]}),
+ ]
+ )
+ manager = _FakeManager()
+
+ rows = _drain(session, "BalanceAccounts", manager, balance_platform="BP123")
+
+ assert [row["id"] for row in rows] == ["BA1", "BA2"]
+ assert session.requested_urls[1].startswith(
+ "https://balanceplatform-api-test.adyen.com/bcl/v2/accountHolders/AH1/balanceAccounts"
+ )
+ assert [state.parent_index for state in manager.saved_states] == [1, 2]
+
+ def test_resume_skips_parents_already_walked(self) -> None:
+ session = _FakeSession(
+ [
+ _FakeResponse(json_data={"accountHolders": [{"id": "AH1"}, {"id": "AH2"}]}),
+ _FakeResponse(json_data={"balanceAccounts": [{"id": "BA2"}]}),
+ ]
+ )
+
+ rows = _drain(
+ session,
+ "BalanceAccounts",
+ _FakeManager(AdyenResumeConfig(parent_index=1)),
+ balance_platform="BP123",
+ )
+
+ assert [row["id"] for row in rows] == ["BA2"]
+ assert "AH2" in session.requested_urls[1]
+
+
+class TestReportBatches:
+ def _report(self, rows: str) -> _FakeResponse:
+ return _FakeResponse(text=f"Psp Reference,Type,Modification Reference\n{rows}")
+
+ def test_walks_ascending_batches_until_the_gap_tolerance_is_exhausted(self) -> None:
+ session = _FakeSession(
+ [
+ self._report("A,Settled,\n"),
+ _FakeResponse(status_code=404),
+ self._report("B,Fee,\n"),
+ *[_FakeResponse(status_code=404) for _ in range(MAX_CONSECUTIVE_MISSING_BATCHES + 1)],
+ ]
+ )
+ manager = _FakeManager()
+
+ rows = _drain(session, "SettlementDetailReports", manager, merchant_account="ACME")
+
+ assert [(row["psp_reference"], row["batch_number"]) for row in rows] == [("A", 1), ("B", 3)]
+ assert [state.batch_number for state in manager.saved_states] == [1, 3]
+ assert session.requested_urls[0].endswith(
+ "/reports/download/MerchantAccount/ACME/settlement_detail_report_batch_1.csv"
+ )
+
+ def test_requests_gzip_and_csv(self) -> None:
+ session = _FakeSession([self._report("A,Settled,\n"), *[_FakeResponse(status_code=404) for _ in range(4)]])
+
+ _drain(session, "SettlementDetailReports", _FakeManager(), merchant_account="ACME")
+
+ headers = session.requested_headers[0]
+ assert headers is not None
+ assert headers["Accept-Encoding"] == "gzip"
+ assert headers["Accept"] == "text/csv"
+
+ def test_incremental_watermark_starts_at_the_next_batch(self) -> None:
+ session = _FakeSession([self._report("C,Settled,\n"), *[_FakeResponse(status_code=404) for _ in range(4)]])
+
+ rows = _drain(
+ session,
+ "SettlementDetailReports",
+ _FakeManager(),
+ merchant_account="ACME",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=41,
+ )
+
+ assert rows[0]["batch_number"] == 42
+ assert session.requested_urls[0].endswith("settlement_detail_report_batch_42.csv")
+
+ def test_resume_state_wins_over_the_watermark(self) -> None:
+ session = _FakeSession([self._report("D,Settled,\n"), *[_FakeResponse(status_code=404) for _ in range(4)]])
+
+ _drain(
+ session,
+ "SettlementDetailReports",
+ _FakeManager(AdyenResumeConfig(batch_number=100)),
+ merchant_account="ACME",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=41,
+ )
+
+ assert session.requested_urls[0].endswith("settlement_detail_report_batch_101.csv")
+
+ def test_configured_start_batch_is_used_on_a_first_full_sync(self) -> None:
+ session = _FakeSession([self._report("E,Settled,\n"), *[_FakeResponse(status_code=404) for _ in range(4)]])
+
+ _drain(
+ session,
+ "SettlementDetailReports",
+ _FakeManager(),
+ merchant_account="ACME",
+ settlement_report_start_batch=500,
+ )
+
+ assert session.requested_urls[0].endswith("settlement_detail_report_batch_500.csv")
+
+ @parameterized.expand([("forbidden", 403), ("server_error", 500)])
+ def test_non_404_failures_are_raised(self, _name: str, status_code: int) -> None:
+ session = _FakeSession([_FakeResponse(status_code=status_code)])
+
+ with pytest.raises(Exception, match="Client Error|Error for url"):
+ _drain(session, "SettlementDetailReports", _FakeManager(), merchant_account="ACME")
+
+ def test_missing_merchant_account_is_a_configuration_error(self) -> None:
+ with pytest.raises(AdyenConfigurationError):
+ _drain(_FakeSession([]), "SettlementDetailReports", _FakeManager())
+
+
+class TestAdyenSourceResponse:
+ @parameterized.expand([(name,) for name in ADYEN_ENDPOINTS])
+ def test_response_matches_the_endpoint_catalog(self, endpoint: str) -> None:
+ config = ADYEN_ENDPOINTS[endpoint]
+
+ response = adyen_source(
+ environment="test",
+ api_key="key",
+ endpoint=endpoint,
+ logger=mock.MagicMock(),
+ resumable_source_manager=_FakeManager(),
+ )
+
+ assert response.name == endpoint
+ assert response.primary_keys == list(config.primary_key)
+ # Every endpoint is walked oldest-first, so the watermark only moves forward.
+ assert response.sort_mode == "asc"
+ 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 None
+
+ def test_items_are_lazy(self) -> None:
+ # Building the response must not touch the network — the pipeline calls `items()`.
+ response = adyen_source(
+ environment="test",
+ api_key="key",
+ endpoint="Transfers",
+ logger=mock.MagicMock(),
+ resumable_source_manager=_FakeManager(),
+ )
+
+ assert callable(response.items)
+ with mock.patch.object(adyen_module, "_get_session", return_value=_FakeSession([])):
+ with pytest.raises(AdyenConfigurationError):
+ list(cast("Iterable[Any]", response.items()))
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/adyen/tests/test_adyen_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/adyen/tests/test_adyen_source.py
new file mode 100644
index 000000000000..a94620244624
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/adyen/tests/test_adyen_source.py
@@ -0,0 +1,270 @@
+from typing import Any, Optional
+
+from unittest import mock
+
+from parameterized import parameterized
+
+from posthog.schema import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+ SourceFieldSelectConfig,
+)
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.adyen.adyen import AdyenResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.adyen.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.adyen.settings import (
+ ADYEN_ENDPOINTS,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.adyen.source import AdyenSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.adyen import AdyenSourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.adyen.source"
+
+
+def _make_inputs(**overrides: Any) -> SourceInputs:
+ defaults: dict[str, Any] = {
+ "schema_name": "Transfers",
+ "schema_id": "schema-1",
+ "source_id": "source-1",
+ "team_id": 123,
+ "should_use_incremental_field": False,
+ "db_incremental_field_last_value": None,
+ "db_incremental_field_earliest_value": None,
+ "incremental_field": None,
+ "incremental_field_type": None,
+ "job_id": "job-1",
+ "logger": mock.MagicMock(),
+ "reset_pipeline": False,
+ }
+ defaults.update(overrides)
+ return SourceInputs(**defaults)
+
+
+class TestAdyenSource:
+ def setup_method(self) -> None:
+ self.source = AdyenSource()
+ self.team_id = 123
+ self.config = AdyenSourceConfig(
+ api_key="adyen-key",
+ environment="live",
+ balance_platform="BP123",
+ merchant_account="ACME",
+ start_date="2026-01-01",
+ settlement_report_start_batch=None,
+ )
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.ADYEN
+
+ def test_source_config_is_released_in_alpha(self) -> None:
+ config = self.source.get_source_config
+
+ assert not config.unreleasedSource
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.category == DataWarehouseSourceCategory.PAYMENTS___BILLING
+ assert config.iconPath == "/static/services/adyen.png"
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/adyen"
+
+ def test_environment_field_is_a_fixed_choice(self) -> None:
+ environment_field = self.source.get_source_config.fields[0]
+
+ assert isinstance(environment_field, SourceFieldSelectConfig)
+ assert environment_field.name == "environment"
+ assert environment_field.required is True
+ assert environment_field.defaultValue == "live"
+ assert {option.value for option in environment_field.options} == {"live", "test"}
+
+ @parameterized.expand(
+ [
+ ("api_key", SourceFieldInputConfigType.PASSWORD, True, True),
+ ("balance_platform", SourceFieldInputConfigType.TEXT, False, False),
+ ("merchant_account", SourceFieldInputConfigType.TEXT, False, False),
+ ("start_date", SourceFieldInputConfigType.TEXT, False, False),
+ ("settlement_report_start_batch", SourceFieldInputConfigType.NUMBER, False, False),
+ ]
+ )
+ def test_input_fields(
+ self,
+ name: str,
+ expected_type: SourceFieldInputConfigType,
+ required: bool,
+ secret: bool,
+ ) -> None:
+ fields = {
+ field.name: field
+ for field in self.source.get_source_config.fields
+ if isinstance(field, SourceFieldInputConfig)
+ }
+
+ field = fields[name]
+ assert field.type == expected_type
+ assert field.required is required
+ assert field.secret is secret
+
+ @parameterized.expand(
+ [("unauthorized", "401 Client Error: Unauthorized"), ("forbidden", "403 Client Error: Forbidden")]
+ )
+ def test_non_retryable_errors(self, _name: str, expected_key: str) -> None:
+ assert expected_key in self.source.get_non_retryable_errors()
+
+ def test_get_schemas_returns_the_whole_catalog(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+ assert all(schema.description for schema in schemas)
+
+ @parameterized.expand([(name,) for name in ENDPOINTS])
+ def test_incremental_flags_track_the_endpoint_catalog(self, endpoint: str) -> None:
+ schema = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}[endpoint]
+ expected_fields = INCREMENTAL_FIELDS.get(endpoint, [])
+
+ assert schema.incremental_fields == expected_fields
+ assert schema.supports_incremental is bool(expected_fields)
+
+ def test_only_endpoints_with_a_server_side_filter_are_incremental(self) -> None:
+ incremental = {s.name for s in self.source.get_schemas(self.config, self.team_id) if s.supports_incremental}
+
+ assert incremental == {"Transactions", "Transfers", "SettlementDetailReports"}
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["Transfers"])
+
+ assert [schema.name for schema in schemas] == ["Transfers"]
+
+ def test_get_schemas_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["Nope"]) == []
+
+ def test_schemas_list_without_credentials_for_public_docs(self) -> None:
+ # The catalog is static, so the public docs endpoint can render it with a blank config.
+ assert self.source.lists_tables_without_credentials is True
+ blank = AdyenSourceConfig(api_key="")
+ assert {schema.name for schema in self.source.get_schemas(blank, self.team_id)} == set(ENDPOINTS)
+
+ @parameterized.expand(
+ [
+ ("both_identifiers", "BP123", "ACME", set(ENDPOINTS)),
+ (
+ "platform_only",
+ "BP123",
+ None,
+ {"Transactions", "Transfers", "AccountHolders", "BalanceAccounts", "Companies", "MerchantAccounts"},
+ ),
+ ("merchant_only", None, "ACME", {"SettlementDetailReports", "Companies", "MerchantAccounts"}),
+ ("neither", None, " ", {"Companies", "MerchantAccounts"}),
+ ]
+ )
+ def test_tables_needing_a_missing_identifier_start_unselected(
+ self,
+ _name: str,
+ balance_platform: Optional[str],
+ merchant_account: Optional[str],
+ expected_on: set[str],
+ ) -> None:
+ config = AdyenSourceConfig(
+ api_key="adyen-key",
+ balance_platform=balance_platform,
+ merchant_account=merchant_account,
+ )
+
+ schemas = self.source.get_schemas(config, self.team_id)
+
+ assert {schema.name for schema in schemas if schema.should_sync_default} == expected_on
+
+ def test_canonical_descriptions_cover_every_endpoint(self) -> None:
+ assert set(self.source.get_canonical_descriptions()) == set(ENDPOINTS)
+
+ @parameterized.expand([(name,) for name in ENDPOINTS])
+ def test_canonical_descriptions_document_the_primary_key(self, endpoint: str) -> None:
+ columns = CANONICAL_DESCRIPTIONS[endpoint]["columns"]
+
+ for key in ADYEN_ENDPOINTS[endpoint].primary_key:
+ assert key in columns
+
+ @parameterized.expand(
+ [
+ ("valid", (True, None), True, None),
+ ("invalid", (False, "Adyen rejected the API key."), False, "Adyen rejected the API key."),
+ ]
+ )
+ def test_validate_credentials(
+ self,
+ _name: str,
+ mock_return: tuple[bool, Optional[str]],
+ expected_valid: bool,
+ expected_message: Optional[str],
+ ) -> None:
+ with mock.patch(f"{SOURCE_MODULE}.validate_adyen_credentials", return_value=mock_return) as mock_validate:
+ is_valid, message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is expected_valid
+ assert message == expected_message
+ mock_validate.assert_called_once_with(
+ environment="live",
+ api_key="adyen-key",
+ balance_platform="BP123",
+ merchant_account="ACME",
+ )
+
+ def test_get_resumable_source_manager_bound_to_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(_make_inputs())
+
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is AdyenResumeConfig
+
+ def test_source_for_pipeline_plumbs_arguments(self) -> None:
+ inputs = _make_inputs(schema_name="Transactions")
+ manager = mock.MagicMock(spec=ResumableSourceManager)
+
+ with mock.patch(f"{SOURCE_MODULE}.adyen_source") as mock_source:
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_source.assert_called_once_with(
+ environment="live",
+ api_key="adyen-key",
+ endpoint="Transactions",
+ logger=inputs.logger,
+ resumable_source_manager=manager,
+ balance_platform="BP123",
+ merchant_account="ACME",
+ start_date="2026-01-01",
+ settlement_report_start_batch=None,
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ )
+
+ def test_source_for_pipeline_only_passes_the_watermark_when_incremental(self) -> None:
+ inputs = _make_inputs(
+ schema_name="Transfers",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2026-05-01T00:00:00Z",
+ incremental_field="createdAt",
+ )
+ manager = mock.MagicMock(spec=ResumableSourceManager)
+
+ with mock.patch(f"{SOURCE_MODULE}.adyen_source") as mock_source:
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ _, kwargs = mock_source.call_args
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2026-05-01T00:00:00Z"
+
+ def test_watermark_is_dropped_when_incremental_is_off(self) -> None:
+ inputs = _make_inputs(
+ should_use_incremental_field=False, db_incremental_field_last_value="2026-05-01T00:00:00Z"
+ )
+ manager = mock.MagicMock(spec=ResumableSourceManager)
+
+ with mock.patch(f"{SOURCE_MODULE}.adyen_source") as mock_source:
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ _, kwargs = mock_source.call_args
+ assert kwargs["db_incremental_field_last_value"] is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/adyen.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/adyen.py
index 82ebe346be6b..b4bfe3991071 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/adyen.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/adyen.py
@@ -1,9 +1,18 @@
# This file is automatically generated from `SourceRegistry.get_all_sources()`
# Do not edit manually - run `pnpm generate:source-configs` to regenerate.
+from typing import Literal
+
from products.warehouse_sources.backend.temporal.data_imports.sources.common import config
@config.config
class AdyenSourceConfig(config.Config):
- pass
+ api_key: str
+ settlement_report_start_batch: int | None = config.value(
+ converter=config.str_to_optional_int, default_factory=lambda: None
+ )
+ environment: Literal["live", "test"] = config.value(default="live")
+ balance_platform: str | None = None
+ merchant_account: str | None = None
+ start_date: str | None = None