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): add vendor central reports to amazon selling partner (#118179)

Daniel RC54e30bfc67e3
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_selling_partner/amazon_selling_partner.py b/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_selling_partner/amazon_selling_partner.py
index 2e9c3fd64e2f..51ec4f9df338 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_selling_partner/amazon_selling_partner.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_selling_partner/amazon_selling_partner.py
@@ -1,15 +1,20 @@
+import gzip
import json
+import time
import sqlite3
import tempfile
from collections.abc import Callable, Iterable, Iterator
from dataclasses import field
from datetime import UTC, datetime, timedelta
+from itertools import batched
from pathlib import Path
from typing import Any, Optional
+from urllib.parse import parse_qsl, urlsplit
import requests
import structlog
from requests import PreparedRequest
+from urllib3.util.retry import Retry
from posthog.dataclasses import frozen
@@ -19,6 +24,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.amazon_sel
INVENTORY_SUMMARIES,
INVENTORY_SUMMARIES_PATH,
LWA_TOKEN_URL,
+ MARKETPLACE_CURRENCIES,
MARKETPLACE_PARTICIPATIONS_PATH,
ORDER_ITEMS,
ORDERS,
@@ -27,6 +33,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.amazon_sel
ORDERS_PATH,
PARTITION_KEYS,
PRIMARY_KEYS,
+ REPORT_DOCUMENTS_PATH,
+ REPORTS_PATH,
REQUEST_TIME_MARGIN_SECONDS,
SP_API_HOSTS,
SP_API_MAX_RETRY_ATTEMPTS,
@@ -34,9 +42,15 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.amazon_sel
TRANSACTIONS,
TRANSACTIONS_PATH,
TRANSACTIONS_WINDOW_DAYS,
+ VENDOR_REPORTS,
+ VENDOR_SALES,
+ VendorReport,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import parse_datetime_value
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.interruptible_wait import (
+ interruptible_wait,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
RESTAPIConfig,
rest_api_resource,
@@ -56,13 +70,35 @@ LWA_REJECTED_MESSAGE = (
"Check the client ID, client secret and refresh token, then try again."
)
ACCESS_DENIED_MESSAGE = (
- "Amazon accepted the login but refused the Selling Partner API call. "
- "Check that the app is authorized for this seller and has the roles the tables need."
+ "Amazon accepted the login but refused the Selling Partner API calls. "
+ "Check that the region matches the account, that the account authorized the app, "
+ "and that the app has the roles the tables need."
)
UNAVAILABLE_MESSAGE = "Couldn't reach Amazon to check the credentials. Try again in a few minutes."
+MISSING_MARKETPLACES_MESSAGE = "Vendor reports need marketplace IDs. Add them in the source settings."
+SELLER_ONLY_MESSAGE = "This table needs a seller account with the role listed in the source description."
+VENDOR_ONLY_MESSAGE = "This table needs a vendor account with the Brand Analytics role."
REQUEST_TIMEOUT = (10.0, 30.0)
+# The table picker waits on the probes inside one setup request, so they share a short budget.
+PROBE_TIMEOUT = (5.0, 10.0)
+PROBE_BUDGET_SECONDS = 30.0
INVENTORY_ROWS_PER_BATCH = 2000
+REPORT_POLL_INTERVAL_SECONDS = 30
+# A report still pending after this long fails the attempt; the next attempt polls the same report.
+REPORT_POLL_BUDGET_SECONDS = 60 * 60
+# createReport allows one call a minute after a burst of 15, and Amazon sends no Retry-After.
+REPORT_CREATE_ATTEMPTS = 5
+REPORT_CREATE_BACKOFF_SECONDS = 60
+REPORT_DOWNLOAD_TIMEOUT = (10.0, 300.0)
+# A FATAL report for a window that ended this recently may only mean Amazon has not published it yet.
+REPORT_PUBLISH_GRACE = timedelta(days=7)
+REPORT_FATAL_ATTEMPTS = 3
+REPORT_DOWNLOAD_CHUNK_BYTES = 1024 * 1024
+REPORT_ROWS_PER_BATCH = 2000
+# The document sits on presigned Amazon storage. Pinning the host keeps a tampered `url` from
+# sending the download anywhere else.
+REPORT_URL_HOST_SUFFIXES = (".amazonaws.com", ".amazon.com")
ResumeHook = Callable[[Optional[dict[str, Any]]], None]
@@ -74,11 +110,13 @@ class AmazonSellingPartnerResumeConfig:
window_start: str | None = None
window_end: str | None = None
transaction_status: str | None = None
- # Marketplaces whose inventory walk finished. Inventory page tokens expire in 30 seconds, so a
- # marketplace restarts from its first page.
+ # Marketplaces whose walk finished.
completed_marketplaces: list[str] = field(default_factory=list)
marketplace_id: str | None = None
last_seller_sku: str | None = None
+ # A vendor report being handed on, so a resume polls it and skips its rows already handed on.
+ report_id: str | None = None
+ rows_done: int = 0
class LwaAuth(OAuth2Auth):
@@ -370,9 +408,14 @@ def _transactions_resource(
return Resource(pages, name=TRANSACTIONS, hints=_wrapper_hints(TRANSACTIONS, should_use_incremental_field))
-def list_marketplace_ids(region: str, auth: LwaAuth) -> list[str]:
- session = make_tracked_session(redact_values=auth.secret_values())
- response = session.get(f"{_base_url(region)}{MARKETPLACE_PARTICIPATIONS_PATH}", auth=auth, timeout=REQUEST_TIMEOUT)
+def list_marketplace_ids(
+ region: str,
+ auth: LwaAuth,
+ session: requests.Session | None = None,
+ timeout: tuple[float, float] = REQUEST_TIMEOUT,
+) -> list[str]:
+ session = session or make_tracked_session(redact_values=auth.secret_values())
+ response = session.get(f"{_base_url(region)}{MARKETPLACE_PARTICIPATIONS_PATH}", auth=auth, timeout=timeout)
response.raise_for_status()
return [
entry["marketplace"]["id"]
@@ -483,6 +526,302 @@ def _inventory_rows(
completed = done_state.completed_marketplaces
+class VendorReportError(Exception):
+ """Amazon finished a report with FATAL status. The retry requests a new report for the same window."""
+
+
+class VendorReportPendingError(Exception):
+ """A report is still processing after the polling budget. The next attempt polls it again."""
+
+
+@frozen
+class ReportWindow:
+ data_start_time: str
+ data_end_time: str
+
+
+def presigned_secret_values(url: str) -> tuple[str, ...]:
+ """The signing material in a presigned document URL, which the shared scrubber does not mask by name."""
+ return tuple(
+ value for name, value in parse_qsl(urlsplit(url).query) if name.lower().startswith("x-amz-") and len(value) >= 8
+ )
+
+
+def report_windows(
+ report: VendorReport, start: datetime | None, now: datetime, *, resumed: bool = False
+) -> list[ReportWindow]:
+ """The date ranges to request, oldest first, from `start` (or the oldest Amazon keeps) to the newest it publishes.
+
+ A resumed `start` belongs to a report that already exists, so it is kept even when the lookback
+ floor moved past it since the report was created.
+ """
+ if report.window is None or report.lookback is None:
+ return []
+ if report.hourly:
+ newest = (now - report.availability_delay).replace(minute=0, second=0, microsecond=0)
+ oldest = now.replace(minute=0, second=0, microsecond=0) - report.lookback
+ if start is not None:
+ start = start.replace(minute=0, second=0, microsecond=0)
+ cursor = (start if resumed else max(start, oldest)) if start else oldest
+ windows = []
+ while cursor < newest:
+ end = min(cursor + report.window, newest)
+ windows.append(ReportWindow(data_start_time=to_iso8601(cursor), data_end_time=to_iso8601(end)))
+ cursor = end
+ return windows
+
+ last_day = (now - report.availability_delay).date()
+ oldest_day = now.date() - report.lookback
+ day = (start.date() if resumed else max(start.date(), oldest_day)) if start else oldest_day
+ windows = []
+ while day <= last_day:
+ end_day = min(day + report.window - timedelta(days=1), last_day)
+ windows.append(
+ ReportWindow(
+ data_start_time=f"{day.isoformat()}T00:00:00Z", data_end_time=f"{end_day.isoformat()}T23:59:59Z"
+ )
+ )
+ day = end_day + timedelta(days=1)
+ return windows
+
+
+class ReportsClient:
+ def __init__(self, region: str, auth: LwaAuth) -> None:
+ self._base_url = _base_url(region)
+ self._auth = auth
+ # Report and document bodies carry presigned download URLs, so they stay out of sample capture.
+ self._session = make_tracked_session(redact_values=auth.secret_values(), capture=False)
+
+ def create_report(self, body: dict[str, Any], safe_point: Callable[[], None]) -> str:
+ for attempt in range(REPORT_CREATE_ATTEMPTS):
+ response = self._session.post(
+ f"{self._base_url}{REPORTS_PATH}", json=body, auth=self._auth, timeout=REQUEST_TIMEOUT
+ )
+ if response.status_code == 429 and attempt + 1 < REPORT_CREATE_ATTEMPTS:
+ interruptible_wait(REPORT_CREATE_BACKOFF_SECONDS, safe_point=safe_point)
+ continue
+ response.raise_for_status()
+ return str(response.json()["reportId"])
+ raise AssertionError("unreachable")
+
+ def get_report(self, report_id: str) -> dict[str, Any]:
+ response = self._session.get(
+ f"{self._base_url}{REPORTS_PATH}/{report_id}", auth=self._auth, timeout=REQUEST_TIMEOUT
+ )
+ response.raise_for_status()
+ return response.json()
+
+ def get_document(self, document_id: str) -> dict[str, Any]:
+ """Read a report document. Rows come back as JSON, unzipped when Amazon compressed them."""
+ response = self._session.get(
+ f"{self._base_url}{REPORT_DOCUMENTS_PATH}/{document_id}", auth=self._auth, timeout=REQUEST_TIMEOUT
+ )
+ response.raise_for_status()
+ document = response.json()
+ url = str(document["url"])
+ host = (urlsplit(url).hostname or "").lower()
+ if not host.endswith(REPORT_URL_HOST_SUFFIXES):
+ raise ValueError(f"Amazon report document URL points outside Amazon: host={host}")
+ # The presigned URL carries its own signature, so the download sends no LWA token.
+ download = make_tracked_session(redact_values=presigned_secret_values(url), capture=False)
+ # The stock error messages quote the whole URL, signature included, into the job's error and logs.
+ # The download goes to a temporary file in chunks, so the compressed copy never sits in memory.
+ with tempfile.TemporaryFile() as spool:
+ try:
+ with download.get(url, timeout=REPORT_DOWNLOAD_TIMEOUT, stream=True) as content_response:
+ if not content_response.ok:
+ raise requests.HTTPError(
+ f"Amazon report document download returned status={content_response.status_code}",
+ response=content_response,
+ )
+ for chunk in content_response.iter_content(chunk_size=REPORT_DOWNLOAD_CHUNK_BYTES):
+ spool.write(chunk)
+ except requests.HTTPError:
+ raise
+ except requests.RequestException as e:
+ raise requests.ConnectionError(f"Amazon report document download failed: {type(e).__name__}") from None
+ spool.seek(0)
+ if document.get("compressionAlgorithm") == "GZIP":
+ with gzip.GzipFile(fileobj=spool) as unzipped:
+ return json.load(unzipped)
+ return json.load(spool)
+
+
+def await_report_document(
+ client: ReportsClient, report: VendorReport, report_id: str, safe_point: Callable[[], None]
+) -> dict[str, Any] | None:
+ """Poll until the report is done. None means Amazon cancelled it because there was no data."""
+ waited = 0
+ while True:
+ status = client.get_report(report_id)
+ safe_point()
+ processing_status = status.get("processingStatus")
+ if processing_status == "DONE":
+ return client.get_document(str(status["reportDocumentId"]))
+ if processing_status == "CANCELLED":
+ return None
+ if processing_status == "FATAL":
+ detail = ""
+ if status.get("reportDocumentId"):
+ detail = str(client.get_document(str(status["reportDocumentId"])).get("errorDetails") or "")
+ raise VendorReportError(f"Amazon could not generate the {report.report_type} report: {detail}".strip())
+ if waited >= REPORT_POLL_BUDGET_SECONDS:
+ raise VendorReportPendingError(
+ f"Amazon {report.report_type} report {report_id} is still {processing_status} after {waited} seconds"
+ )
+ interruptible_wait(REPORT_POLL_INTERVAL_SECONDS, safe_point=safe_point)
+ waited += REPORT_POLL_INTERVAL_SECONDS
+
+
+def _may_be_unpublished(report: VendorReport, data_end_time: str, now: datetime) -> bool:
+ """Whether a FATAL report for this window can mean Amazon has not published the data yet."""
+ end = parse_datetime_value(data_end_time)
+ return end is None or end >= now - report.availability_delay - REPORT_PUBLISH_GRACE
+
+
+def _after(report: VendorReport, data_end_time: str) -> datetime | None:
+ """Where the window after one ending at `data_end_time` starts."""
+ end = parse_datetime_value(data_end_time)
+ if end is None or report.hourly:
+ return end
+ return datetime.combine(end.date() + timedelta(days=1), datetime.min.time(), tzinfo=UTC)
+
+
+def _report_options(report: VendorReport, marketplace_id: str) -> dict[str, str]:
+ if not report.needs_currency:
+ return dict(report.options)
+ currency = MARKETPLACE_CURRENCIES.get(marketplace_id)
+ if currency is None:
+ raise ValueError(f"Unknown Amazon marketplace ID for real-time sales: {marketplace_id}")
+ return {**report.options, "currencyCode": currency}
+
+
+def _vendor_report_rows(
+ *,
+ region: str,
+ auth: LwaAuth,
+ marketplace_ids: list[str],
+ endpoint: str,
+ resumable_source_manager: ResumableSourceManager[AmazonSellingPartnerResumeConfig],
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> Iterator[list[dict[str, Any]]]:
+ if not marketplace_ids:
+ raise ValueError(MISSING_MARKETPLACES_MESSAGE)
+ report = VENDOR_REPORTS[endpoint]
+ client = ReportsClient(region, auth)
+ manager = resumable_source_manager
+ resume = manager.load_state() if manager.can_resume() else None
+ completed = list(resume.completed_marketplaces) if resume is not None else []
+ watermark = parse_datetime_value(db_incremental_field_last_value) if should_use_incremental_field else None
+ now = datetime.now(UTC)
+
+ for marketplace_id in marketplace_ids:
+ if marketplace_id in completed:
+ continue
+ pending = resume if resume is not None and resume.marketplace_id == marketplace_id else None
+ windows: list[ReportWindow | None]
+ if not report.window:
+ windows = [None]
+ elif pending is not None and pending.report_id and pending.window_start and pending.window_end:
+ # The saved report covers the range it was created with. The next window starts right
+ # after it, even when a partial window would come out longer today.
+ saved = ReportWindow(data_start_time=pending.window_start, data_end_time=pending.window_end)
+ windows = [saved, *report_windows(report, _after(report, pending.window_end), now, resumed=True)]
+ else:
+ resumed = pending is not None and pending.window_start is not None
+ start = (
+ parse_datetime_value(pending.window_start)
+ if pending is not None and pending.window_start
+ else watermark
+ )
+ windows = list(report_windows(report, start, now, resumed=resumed))
+
+ for index, window in enumerate(windows):
+ window_start = window.data_start_time if window is not None else None
+ window_end = window.data_end_time if window is not None else None
+ resuming = pending is not None and pending.window_start == window_start
+ report_id = pending.report_id if pending is not None and resuming else None
+ rows_done = pending.rows_done if pending is not None and resuming and report_id else 0
+ pending = None
+ following = windows[index + 1] if index + 1 < len(windows) else None
+ next_state = (
+ AmazonSellingPartnerResumeConfig(
+ completed_marketplaces=completed,
+ marketplace_id=marketplace_id,
+ window_start=following.data_start_time,
+ )
+ if following is not None
+ else AmazonSellingPartnerResumeConfig(completed_marketplaces=[*completed, marketplace_id])
+ )
+ recent = window_end is None or _may_be_unpublished(report, window_end, now)
+ document: dict[str, Any] | None = None
+ for attempt in range(1, REPORT_FATAL_ATTEMPTS + 1):
+ if report_id is None:
+ body: dict[str, Any] = {"reportType": report.report_type, "marketplaceIds": [marketplace_id]}
+ options = _report_options(report, marketplace_id)
+ if options:
+ body["reportOptions"] = options
+ if window is not None:
+ body["dataStartTime"] = window.data_start_time
+ body["dataEndTime"] = window.data_end_time
+ report_id = client.create_report(body, manager.safe_point)
+ rows_done = 0
+ # Staged, not committed: the pipeline commits it at a safe point once earlier rows are
+ # written, so an attempt that resumes polls this report instead of creating another.
+ manager.save_state(
+ AmazonSellingPartnerResumeConfig(
+ completed_marketplaces=completed,
+ marketplace_id=marketplace_id,
+ window_start=window_start,
+ window_end=window_end,
+ report_id=report_id,
+ )
+ )
+ try:
+ document = await_report_document(client, report, report_id, manager.safe_point)
+ break
+ except VendorReportError:
+ # A failed report stays failed, so a retry asks for a new one for the same window.
+ report_id = None
+ # FATAL can be a passing processing error, so an old window gets more reports in
+ # this run. A recent one may only be unpublished, so it waits for the next sync.
+ if not recent and attempt < REPORT_FATAL_ATTEMPTS:
+ continue
+ # The resume point stays on this window, so no later window moves the watermark past it.
+ manager.save_state(
+ AmazonSellingPartnerResumeConfig(
+ completed_marketplaces=completed,
+ marketplace_id=marketplace_id,
+ window_start=window_start,
+ )
+ )
+ manager.safe_point()
+ raise
+ all_rows = (document or {}).get(report.rows_key) or []
+ if rows_done >= len(all_rows):
+ manager.save_state(next_state)
+ manager.safe_point()
+ continue
+ for batch in batched(all_rows[rows_done:], REPORT_ROWS_PER_BATCH, strict=False):
+ rows_done += len(batch)
+ # A resumed full refresh would append handed-on rows again, so the offset moves with each batch.
+ manager.save_state(
+ next_state
+ if rows_done >= len(all_rows)
+ else AmazonSellingPartnerResumeConfig(
+ completed_marketplaces=completed,
+ marketplace_id=marketplace_id,
+ window_start=window_start,
+ window_end=window_end,
+ report_id=report_id,
+ rows_done=rows_done,
+ )
+ )
+ yield [{"marketplaceId": marketplace_id, **row} for row in batch]
+ completed = [*completed, marketplace_id]
+
+
def amazon_selling_partner_source(
*,
region: str,
@@ -513,6 +852,16 @@ def amazon_selling_partner_source(
items = lambda: _inventory_rows(
region=region, auth=auth, marketplace_ids=marketplace_ids, resumable_source_manager=resumable_source_manager
)
+ elif endpoint in VENDOR_REPORTS:
+ items = lambda: _vendor_report_rows(
+ region=region,
+ auth=auth,
+ marketplace_ids=marketplace_ids,
+ endpoint=endpoint,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ )
else:
resource: Resource
if endpoint in (ORDERS, ORDER_ITEMS):
@@ -542,14 +891,23 @@ def amazon_selling_partner_source(
def validate_credentials(
- region: str, client_id: str, client_secret: str, refresh_token: str
+ region: str, client_id: str, client_secret: str, refresh_token: str, marketplace_ids: list[str]
) -> tuple[bool, str | None]:
auth = LwaAuth(client_id, client_secret, refresh_token)
session = make_tracked_session(redact_values=auth.secret_values(), capture=False)
+ base_url = _base_url(region)
try:
- response = session.get(
- f"{_base_url(region)}{MARKETPLACE_PARTICIPATIONS_PATH}", auth=auth, timeout=REQUEST_TIMEOUT
- )
+ response = session.get(f"{base_url}{MARKETPLACE_PARTICIPATIONS_PATH}", auth=auth, timeout=REQUEST_TIMEOUT)
+ if response.status_code == 403:
+ # Vendor accounts always get 403 from the Sellers API, so ask the Reports API instead.
+ response = session.get(
+ f"{base_url}{REPORTS_PATH}",
+ params={"reportTypes": VENDOR_REPORTS[VENDOR_SALES].report_type, "pageSize": "1"},
+ auth=auth,
+ timeout=REQUEST_TIMEOUT,
+ )
+ if response.status_code == 200 and not marketplace_ids:
+ return False, MISSING_MARKETPLACES_MESSAGE
except OAuth2AuthRequestError as e:
return False, LWA_REJECTED_MESSAGE if e.is_permanent else UNAVAILABLE_MESSAGE
except requests.RequestException:
@@ -559,3 +917,92 @@ def validate_credentials(
if response.status_code in (401, 403):
return False, ACCESS_DENIED_MESSAGE
return False, UNAVAILABLE_MESSAGE
+
+
+def _probe(session: requests.Session, auth: LwaAuth, url: str, params: dict[str, Any]) -> bool | None:
+ """Whether Amazon allows the call. None when the answer says nothing about access."""
+ try:
+ response = session.get(url, params=params, auth=auth, timeout=PROBE_TIMEOUT)
+ except (OAuth2AuthRequestError, requests.RequestException):
+ return None
+ if response.status_code in (401, 403):
+ return False
+ return True if response.ok else None
+
+
+def probe_endpoint_permissions(
+ region: str,
+ client_id: str,
+ client_secret: str,
+ refresh_token: str,
+ marketplace_ids: list[str],
+ endpoints: list[str],
+) -> dict[str, str | None]:
+ auth = LwaAuth(client_id, client_secret, refresh_token)
+ session = make_tracked_session(redact_values=auth.secret_values(), capture=False, retry=Retry(total=0))
+ base_url = _base_url(region)
+ recent = to_iso8601(datetime.now(UTC) - timedelta(days=1))
+ deadline = time.monotonic() + PROBE_BUDGET_SECONDS
+
+ def probe_inventory() -> bool | None:
+ marketplace_id = marketplace_ids[0] if marketplace_ids else None
+ if marketplace_id is None:
+ try:
+ discovered = list_marketplace_ids(region, auth, session=session, timeout=PROBE_TIMEOUT)
+ except requests.HTTPError as e:
+ # Only an explicit rejection means the account is not a seller. Other failures stay unknown.
+ status = e.response.status_code if e.response is not None else None
+ return False if status in (401, 403) else None
+ except (OAuth2AuthRequestError, requests.RequestException):
+ return None
+ if not discovered:
+ return None
+ marketplace_id = discovered[0]
+ return _probe(
+ session,
+ auth,
+ f"{base_url}{INVENTORY_SUMMARIES_PATH}",
+ {"granularityType": "Marketplace", "granularityId": marketplace_id, "marketplaceIds": marketplace_id},
+ )
+
+ def probe(path: str, params: dict[str, Any]) -> Callable[[], bool | None]:
+ return lambda: _probe(session, auth, f"{base_url}{path}", params)
+
+ probes: dict[str, tuple[Callable[[], bool | None], str]] = {
+ ORDERS: (
+ probe(
+ ORDERS_PATH,
+ {
+ "maxResultsPerPage": 1,
+ "lastUpdatedAfter": recent,
+ "marketplaceIds": ",".join(marketplace_ids) or None,
+ },
+ ),
+ SELLER_ONLY_MESSAGE,
+ ),
+ TRANSACTIONS: (probe(TRANSACTIONS_PATH, {"postedAfter": recent}), SELLER_ONLY_MESSAGE),
+ INVENTORY_SUMMARIES: (probe_inventory, SELLER_ONLY_MESSAGE),
+ VENDOR_SALES: (
+ probe(REPORTS_PATH, {"reportTypes": VENDOR_REPORTS[VENDOR_SALES].report_type, "pageSize": 1}),
+ VENDOR_ONLY_MESSAGE,
+ ),
+ }
+ # One call answers for every table that needs the same role.
+ probe_for = {ORDER_ITEMS: ORDERS, **dict.fromkeys(VENDOR_REPORTS, VENDOR_SALES)}
+ answers: dict[str, bool | None] = {}
+ permissions: dict[str, str | None] = {}
+ for endpoint in endpoints:
+ probe_name = probe_for.get(endpoint, endpoint)
+ if probe_name not in probes:
+ permissions[endpoint] = None
+ continue
+ run_probe, message = probes[probe_name]
+ if probe_name not in answers:
+ answers[probe_name] = run_probe() if time.monotonic() < deadline else None
+ if answers[probe_name] is False:
+ permissions[endpoint] = message
+ elif endpoint in VENDOR_REPORTS and not marketplace_ids:
+ permissions[endpoint] = MISSING_MARKETPLACES_MESSAGE
+ else:
+ permissions[endpoint] = None
+ return permissions
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_selling_partner/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_selling_partner/canonical_descriptions.py
index 371d1ba285a0..954f796893d2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_selling_partner/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_selling_partner/canonical_descriptions.py
@@ -75,4 +75,83 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"stores": "Seller-enrolled stores that apply to the SKU.",
},
},
+ "vendor_sales": {
+ "description": "Daily retail sales per ASIN for a vendor, from the Vendor Sales report (manufacturing view, retail program).",
+ "docs_url": "https://developer-docs.amazon.com/sp-api/docs/report-type-values-analytics",
+ "columns": {
+ "marketplaceId": "Marketplace the report covers.",
+ "startDate": "First day of the period the row aggregates.",
+ "endDate": "Last day of the period the row aggregates.",
+ "asin": "Amazon Standard Identification Number of the item.",
+ "customerReturns": "Units returned by customers.",
+ "orderedRevenue": "Ordered product sales in the period, adjusted for returns.",
+ "orderedUnits": "Units ordered by Amazon customers.",
+ "shippedCogs": "Cost of goods sold for shipped units, adjusted for returns.",
+ "shippedRevenue": "Revenue from units shipped in the period, adjusted for returns.",
+ "shippedUnits": "Units shipped to Amazon customers.",
+ },
+ },
+ "vendor_inventory": {
+ "description": "Daily inventory and operational health per ASIN for a vendor, from the Vendor Inventory report.",
+ "docs_url": "https://developer-docs.amazon.com/sp-api/docs/report-type-values-analytics",
+ "columns": {
+ "marketplaceId": "Marketplace the report covers.",
+ "startDate": "First day of the period the row aggregates.",
+ "endDate": "Last day of the period the row aggregates.",
+ "asin": "Amazon Standard Identification Number of the item.",
+ "vendorConfirmationRate": "Units the vendor confirmed, divided by the units Amazon asked for.",
+ "netReceivedInventoryCost": "Cost of inventory Amazon received, minus the cost of inventory returned to the vendor.",
+ "netReceivedInventoryUnits": "Units received from the vendor, minus units returned to the vendor.",
+ "openPurchaseOrderUnits": "Units in confirmed purchase orders that Amazon has not received yet.",
+ "averageVendorLeadTimeDays": "Average days between a purchase order unit's submission and its receipt.",
+ "sellThroughRate": "Units shipped less returns, divided by the units on hand at the start plus units received.",
+ "unfilledCustomerOrderedUnits": "Units ordered or pre-ordered that have not shipped yet.",
+ "sellableOnHandInventoryCost": "Cost of sellable inventory in fulfillment centers on the last day of the period.",
+ "sellableOnHandInventoryUnits": "Sellable units in fulfillment centers on the last day of the period.",
+ "unsellableOnHandInventoryCost": "Cost of unsellable inventory in fulfillment centers on the last day of the period.",
+ "unsellableOnHandInventoryUnits": "Unsellable units in fulfillment centers on the last day of the period.",
+ "aged90PlusDaysSellableInventoryCost": "Cost of sellable inventory at least 90 days old on the last day of the period.",
+ "aged90PlusDaysSellableInventoryUnits": "Sellable units at least 90 days old on the last day of the period.",
+ "unhealthyInventoryCost": "Cost of excess inventory on the last day of the period, based on forecast demand.",
+ "unhealthyInventoryUnits": "Excess units on the last day of the period, based on forecast demand.",
+ },
+ },
+ "vendor_net_pure_product_margin": {
+ "description": "Daily net pure product margin per ASIN, a measure of Amazon's profitability on the vendor's items.",
+ "docs_url": "https://developer-docs.amazon.com/sp-api/docs/report-type-values-analytics",
+ "columns": {
+ "marketplaceId": "Marketplace the report covers.",
+ "startDate": "First day of the period the row aggregates.",
+ "endDate": "Last day of the period the row aggregates.",
+ "asin": "Amazon Standard Identification Number of the item.",
+ "netPureProductMargin": "Product revenue minus product cost and vendor funding, divided by product revenue.",
+ },
+ },
+ "vendor_forecasts": {
+ "description": "The latest weekly customer demand forecast per ASIN, from the Vendor Forecasting report (retail program).",
+ "docs_url": "https://developer-docs.amazon.com/sp-api/docs/report-type-values-analytics",
+ "columns": {
+ "marketplaceId": "Marketplace the report covers.",
+ "forecastGenerationDate": "Date Amazon generated the forecast.",
+ "asin": "Amazon Standard Identification Number of the item.",
+ "startDate": "First day of the forecast period.",
+ "endDate": "Last day of the forecast period.",
+ "meanForecastUnits": "Average units Amazon forecasts to sell in the period.",
+ "p70ForecastUnits": "Units with a 70% probability that demand does not exceed them.",
+ "p80ForecastUnits": "Units with an 80% probability that demand does not exceed them.",
+ "p90ForecastUnits": "Units with a 90% probability that demand does not exceed them.",
+ },
+ },
+ "vendor_real_time_sales": {
+ "description": "Hourly ordered units and revenue per ASIN, from the Vendor Real-Time Sales report.",
+ "docs_url": "https://developer-docs.amazon.com/sp-api/docs/report-type-values-analytics",
+ "columns": {
+ "marketplaceId": "Marketplace the report covers.",
+ "startTime": "Start of the hour, in UTC.",
+ "endTime": "End of the hour, in UTC.",
+ "asin": "Amazon Standard Identification Number of the item.",
+ "orderedUnits": "Units ordered in the hour. Negative when cancellations exceed orders.",
+ "orderedRevenue": "Ordered product sales in the hour, adjusted for cancellations.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_selling_partner/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_selling_partner/settings.py
index 354d430dd063..69f967f19b44 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_selling_partner/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_selling_partner/settings.py
@@ -1,5 +1,9 @@
+from datetime import timedelta
+
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
-from products.warehouse_sources.backend.types import IncrementalField
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
SP_API_HOSTS = {
"na": "https://sellingpartnerapi-na.amazon.com",
@@ -12,6 +16,8 @@ ORDERS_PATH = "/orders/2026-01-01/orders"
TRANSACTIONS_PATH = "/finances/2024-06-19/transactions"
INVENTORY_SUMMARIES_PATH = "/fba/inventory/v1/summaries"
MARKETPLACE_PARTICIPATIONS_PATH = "/sellers/v1/marketplaceParticipations"
+REPORTS_PATH = "/reports/2021-06-30/reports"
+REPORT_DOCUMENTS_PATH = "/reports/2021-06-30/documents"
ORDERS_PAGE_SIZE = 100
# BUYER and RECIPIENT are left out: they carry PII and need restricted roles on the app.
@@ -37,20 +43,127 @@ ORDERS = "orders"
ORDER_ITEMS = "order_items"
TRANSACTIONS = "transactions"
INVENTORY_SUMMARIES = "inventory_summaries"
+VENDOR_SALES = "vendor_sales"
+VENDOR_INVENTORY = "vendor_inventory"
+VENDOR_NET_PURE_PRODUCT_MARGIN = "vendor_net_pure_product_margin"
+VENDOR_FORECASTS = "vendor_forecasts"
+VENDOR_REAL_TIME_SALES = "vendor_real_time_sales"
+
+
+@frozen
+class VendorReport:
+ report_type: str
+ # The key of the row list in the report document.
+ rows_key: str
+ options: dict[str, str]
+ # None for a report that takes no date range, such as the latest forecast.
+ window: timedelta | None = None
+ lookback: timedelta | None = None
+ # Amazon publishes a period's data some time after the period closes.
+ availability_delay: timedelta = timedelta(0)
+ hourly: bool = False
+ needs_currency: bool = False
+
+
+_RETAIL_OPTIONS = {"reportPeriod": "DAY", "distributorView": "MANUFACTURING", "sellingProgram": "RETAIL"}
+# Daily retail analytics: 1,460 days back, final 72 hours after the day closes. Amazon allows 15 days
+# per request, but 7 keeps one document of a large catalog small enough to parse in memory.
+_DAILY_WINDOW = timedelta(days=7)
+_DAILY_LOOKBACK = timedelta(days=1459)
+_DAILY_DELAY = timedelta(days=4)
+
+VENDOR_REPORTS: dict[str, VendorReport] = {
+ VENDOR_SALES: VendorReport(
+ report_type="GET_VENDOR_SALES_REPORT",
+ rows_key="salesByAsin",
+ options=_RETAIL_OPTIONS,
+ window=_DAILY_WINDOW,
+ lookback=_DAILY_LOOKBACK,
+ availability_delay=_DAILY_DELAY,
+ ),
+ VENDOR_INVENTORY: VendorReport(
+ report_type="GET_VENDOR_INVENTORY_REPORT",
+ rows_key="inventoryByAsin",
+ options=_RETAIL_OPTIONS,
+ window=_DAILY_WINDOW,
+ lookback=_DAILY_LOOKBACK,
+ availability_delay=_DAILY_DELAY,
+ ),
+ VENDOR_NET_PURE_PRODUCT_MARGIN: VendorReport(
+ report_type="GET_VENDOR_NET_PURE_PRODUCT_MARGIN_REPORT",
+ rows_key="netPureProductMarginByAsin",
+ options={"reportPeriod": "DAY"},
+ window=_DAILY_WINDOW,
+ lookback=_DAILY_LOOKBACK,
+ availability_delay=_DAILY_DELAY,
+ ),
+ VENDOR_FORECASTS: VendorReport(
+ report_type="GET_VENDOR_FORECASTING_REPORT", rows_key="forecastByAsin", options={"sellingProgram": "RETAIL"}
+ ),
+ # Hourly, 30 days back, requestable five minutes after the hour closes. Amazon allows 14 days per
+ # request, but one day keeps a document small enough to parse in memory for a large catalog.
+ VENDOR_REAL_TIME_SALES: VendorReport(
+ report_type="GET_VENDOR_REAL_TIME_SALES_REPORT",
+ rows_key="reportData",
+ options={},
+ window=timedelta(days=1),
+ lookback=timedelta(days=29),
+ availability_delay=timedelta(minutes=5),
+ hourly=True,
+ needs_currency=True,
+ ),
+}
+
+# Real-time sales reports ask for the currency of the marketplace they cover.
+MARKETPLACE_CURRENCIES: dict[str, str] = {
+ "A2EUQ1WTGCTBG2": "CAD",
+ "ATVPDKIKX0DER": "USD",
+ "A1AM78C64UM0Y8": "MXN",
+ "A2Q3Y263D00KWC": "BRL",
+ "A28R8C7NBKEWEA": "EUR",
+ "A1RKKUPIHCS9HS": "EUR",
+ "A1F83G8C2ARO7P": "GBP",
+ "A13V1IB3VIYZZH": "EUR",
+ "AMEN7PMS3EDWL": "EUR",
+ "A1805IZSGTT6HS": "EUR",
+ "A1PA6795UKMFR9": "EUR",
+ "APJ6JRA9NG5V4": "EUR",
+ "A2NODRKZP88ZB9": "SEK",
+ "AE08WJ6YKNBMC": "ZAR",
+ "A1C3SOZRARQ6R3": "PLN",
+ "ARBP9OOSHTCHU": "EGP",
+ "A33AVAJ2PDY3EV": "TRY",
+ "A17E79C6D8DWNP": "SAR",
+ "A2VIGQ35RCS4UG": "AED",
+ "A21TJRUUN4KGV": "INR",
+ "A19VAU5U5O7RUS": "SGD",
+ "A39IBJ37TRP1C6": "AUD",
+ "A1VC38T7YXB528": "JPY",
+}
-ENDPOINTS = (ORDERS, ORDER_ITEMS, TRANSACTIONS, INVENTORY_SUMMARIES)
+SELLER_ENDPOINTS = (ORDERS, ORDER_ITEMS, TRANSACTIONS, INVENTORY_SUMMARIES)
+ENDPOINTS = (*SELLER_ENDPOINTS, *VENDOR_REPORTS)
PRIMARY_KEYS: dict[str, list[str]] = {
ORDERS: ["orderId"],
ORDER_ITEMS: ["orderId", "orderItemId"],
TRANSACTIONS: ["transactionId"],
INVENTORY_SUMMARIES: ["marketplaceId", "sellerSku"],
+ VENDOR_SALES: ["marketplaceId", "asin", "startDate"],
+ VENDOR_INVENTORY: ["marketplaceId", "asin", "startDate"],
+ VENDOR_NET_PURE_PRODUCT_MARGIN: ["marketplaceId", "asin", "startDate"],
+ VENDOR_FORECASTS: ["marketplaceId", "asin", "startDate"],
+ VENDOR_REAL_TIME_SALES: ["marketplaceId", "asin", "startTime"],
}
PARTITION_KEYS: dict[str, str] = {
ORDERS: "createdTime",
ORDER_ITEMS: "createdTime",
TRANSACTIONS: "postedDate",
+ VENDOR_SALES: "startDate",
+ VENDOR_INVENTORY: "startDate",
+ VENDOR_NET_PURE_PRODUCT_MARGIN: "startDate",
+ VENDOR_REAL_TIME_SALES: "startTime",
}
@@ -58,6 +171,10 @@ INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
ORDERS: [incremental_field("lastUpdatedTime")],
ORDER_ITEMS: [incremental_field("lastUpdatedTime")],
TRANSACTIONS: [incremental_field("postedDate")],
+ VENDOR_SALES: [incremental_field("startDate", IncrementalFieldType.Date)],
+ VENDOR_INVENTORY: [incremental_field("startDate", IncrementalFieldType.Date)],
+ VENDOR_NET_PURE_PRODUCT_MARGIN: [incremental_field("startDate", IncrementalFieldType.Date)],
+ VENDOR_REAL_TIME_SALES: [incremental_field("startTime")],
}
DEFAULT_INCREMENTAL_LOOKBACK_SECONDS: dict[str, int] = {TRANSACTIONS: TRANSACTIONS_LOOKBACK_SECONDS}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_selling_partner/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_selling_partner/source.py
index 377799a9ce54..d289917a83d3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_selling_partner/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_selling_partner/source.py
@@ -11,9 +11,11 @@ from products.warehouse_sources.backend.facade.source_config import (
SourceFieldSelectConfigOption,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.amazon_selling_partner.amazon_selling_partner import (
+ MISSING_MARKETPLACES_MESSAGE,
AmazonSellingPartnerResumeConfig,
amazon_selling_partner_source,
parse_marketplace_ids,
+ probe_endpoint_permissions,
validate_credentials as validate_amazon_selling_partner_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.amazon_selling_partner.settings import (
@@ -67,7 +69,9 @@ class AmazonSellingPartnerSource(ResumableSource[AmazonSellingPartnerSourceConfi
"HTTP 400 from the OAuth2 token endpoint": "Amazon rejected the refresh token. Re-authorize the app for this seller and update the refresh token.",
"HTTP 401 from the OAuth2 token endpoint": "Amazon rejected the Login with Amazon client ID or client secret. Check them in the Amazon developer console and update the source.",
"401 Client Error: Unauthorized for url: https://sellingpartnerapi": "Amazon rejected the access token. Re-authorize the app for this seller and update the refresh token.",
- "403 Client Error: Forbidden for url: https://sellingpartnerapi": "Amazon refused access to this table. Check that the app has the role the table needs and that the seller authorized it.",
+ "403 Client Error: Forbidden for url: https://sellingpartnerapi": "Amazon refused access to this table. Check that the app has the role the table needs and that the account authorized it.",
+ MISSING_MARKETPLACES_MESSAGE: MISSING_MARKETPLACES_MESSAGE,
+ "Unknown Amazon marketplace ID for real-time sales": "A marketplace ID in the source settings is not one Amazon lists. Check the IDs and update the source.",
OAUTH2_PERMANENT_ERROR_MARKER: "Amazon rejected the Login with Amazon credentials. Check the client ID, client secret and refresh token, then update the source.",
}
@@ -102,7 +106,27 @@ class AmazonSellingPartnerSource(ResumableSource[AmazonSellingPartnerSourceConfi
api_version: str | None = None,
) -> tuple[bool, str | None]:
return validate_amazon_selling_partner_credentials(
- config.region, config.client_id, config.client_secret, config.refresh_token
+ config.region,
+ config.client_id,
+ config.client_secret,
+ config.refresh_token,
+ parse_marketplace_ids(config.marketplace_ids),
+ )
+
+ def get_endpoint_permissions(
+ self,
+ config: AmazonSellingPartnerSourceConfig,
+ team_id: int,
+ endpoints: list[str],
+ api_version: str | None = None,
+ ) -> dict[str, str | None]:
+ return probe_endpoint_permissions(
+ config.region,
+ config.client_id,
+ config.client_secret,
+ config.refresh_token,
+ parse_marketplace_ids(config.marketplace_ids),
+ endpoints,
)
def get_resumable_source_manager(
@@ -138,11 +162,13 @@ class AmazonSellingPartnerSource(ResumableSource[AmazonSellingPartnerSourceConfi
name=ExternalDataSourceType.AMAZONSELLINGPARTNER,
category=DataWarehouseSourceCategory.E_COMMERCE,
label="Amazon Selling Partner",
- keywords=["sp-api", "seller central", "amazon seller", "fba"],
+ keywords=["sp-api", "seller central", "vendor central", "amazon seller", "amazon vendor", "fba"],
caption=(
- "Syncs orders, order items, financial transactions and FBA inventory from your Amazon seller account. "
+ "Seller accounts sync orders, order items, financial transactions and FBA inventory. "
"The app needs the Inventory and Order Tracking, Finance and Accounting and Amazon Fulfillment roles. "
- "Orders and order items read the same Amazon endpoint, so syncing both takes twice as long."
+ "Orders and order items read the same Amazon endpoint, so syncing both takes twice as long. "
+ "Vendor accounts sync daily sales, inventory, net pure product margin, forecasts and hourly sales "
+ "reports, which need the Brand Analytics role and your marketplace IDs."
),
iconPath="/static/services/amazon_selling_partner.png",
docsUrl="https://posthog.com/docs/cdp/sources/amazon-selling-partner",
@@ -188,7 +214,7 @@ class AmazonSellingPartnerSource(ResumableSource[AmazonSellingPartnerSourceConfi
SourceFieldInputConfig(
name="marketplace_ids",
label="Marketplace IDs",
- caption="Comma-separated. Applies to orders, order items and inventory, while transactions always cover every marketplace. Leave blank to use every marketplace the seller sells in.",
+ caption="Comma-separated. Required for vendor reports. For sellers it applies to orders, order items and inventory, while transactions always cover every marketplace. Sellers can leave it blank to use every marketplace they sell in.",
type=SourceFieldInputConfigType.TEXT,
required=False,
placeholder="ATVPDKIKX0DER, A1F83G8C2ARO7P",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_selling_partner/tests/test_amazon_selling_partner.py b/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_selling_partner/tests/test_amazon_selling_partner.py
index d8f254d30e9e..c6a4ac95410e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_selling_partner/tests/test_amazon_selling_partner.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/amazon_selling_partner/tests/test_amazon_selling_partner.py
@@ -1,6 +1,8 @@
+import gzip
import json
+import time
from collections.abc import Iterator
-from datetime import UTC, datetime, timedelta
+from datetime import UTC, date, datetime, timedelta
from typing import Any
from urllib.parse import parse_qs
@@ -12,8 +14,15 @@ import requests
from products.warehouse_sources.backend.temporal.data_imports.sources.amazon_selling_partner.amazon_selling_partner import (
ACCESS_DENIED_MESSAGE,
LWA_REJECTED_MESSAGE,
+ MISSING_MARKETPLACES_MESSAGE,
+ SELLER_ONLY_MESSAGE,
UNAVAILABLE_MESSAGE,
+ VENDOR_ONLY_MESSAGE,
AmazonSellingPartnerResumeConfig,
+ VendorReportError,
+ parse_marketplace_ids,
+ probe_endpoint_permissions,
+ report_windows,
to_iso8601,
transaction_windows,
validate_credentials,
@@ -21,6 +30,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.amazon_sel
from products.warehouse_sources.backend.temporal.data_imports.sources.amazon_selling_partner.settings import (
EARLIEST_START,
ORDERS_INCLUDED_DATA,
+ REPORT_DOCUMENTS_PATH as DOCUMENTS_PATH,
+ REPORTS_PATH,
+ VENDOR_REPORTS,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.amazon_selling_partner.source import (
AmazonSellingPartnerSource,
@@ -508,30 +520,55 @@ class TestErrors:
class TestValidateCredentials:
@pytest.mark.parametrize(
- ("token_answer", "probe_answer", "expected"),
+ ("token_answer", "sellers_answer", "reports_answer", "marketplace_ids", "expected"),
[
- (LWA_INVALID_GRANT, None, (False, LWA_REJECTED_MESSAGE)),
- (ScriptedResponse(status=503, json={}), None, (False, UNAVAILABLE_MESSAGE)),
- (TOKEN, ScriptedResponse(json={"payload": []}), (True, None)),
- (TOKEN, SP_API_FORBIDDEN, (False, ACCESS_DENIED_MESSAGE)),
+ (LWA_INVALID_GRANT, None, None, ["A"], (False, LWA_REJECTED_MESSAGE)),
+ (ScriptedResponse(status=503, json={}), None, None, ["A"], (False, UNAVAILABLE_MESSAGE)),
+ (TOKEN, ScriptedResponse(json={"payload": []}), None, [], (True, None)),
+ # Vendor accounts get 403 from the Sellers API, so the Reports API decides.
+ (TOKEN, SP_API_FORBIDDEN, ScriptedResponse(json={"reports": []}), ["A"], (True, None)),
+ (
+ TOKEN,
+ SP_API_FORBIDDEN,
+ ScriptedResponse(json={"reports": []}),
+ [],
+ (False, MISSING_MARKETPLACES_MESSAGE),
+ ),
+ # Wrong region or an app with no roles: both APIs refuse, so creation fails.
+ (TOKEN, SP_API_FORBIDDEN, SP_API_FORBIDDEN, ["A"], (False, ACCESS_DENIED_MESSAGE)),
+ (
+ TOKEN,
+ ScriptedResponse(status=401, json={"errors": [{"code": "Unauthorized"}]}),
+ None,
+ ["A"],
+ (False, ACCESS_DENIED_MESSAGE),
+ ),
],
)
def test_maps_the_vendor_answers(
- self, token_answer: ScriptedResponse, probe_answer: ScriptedResponse | None, expected: tuple[bool, str | None]
+ self,
+ token_answer: ScriptedResponse,
+ sellers_answer: ScriptedResponse | None,
+ reports_answer: ScriptedResponse | None,
+ marketplace_ids: list[str],
+ expected: tuple[bool, str | None],
) -> None:
+ answers = {TOKEN_PATH: token_answer, PARTICIPATIONS_PATH: sellers_answer, REPORTS_PATH: reports_answer}
+
def respond(request: RecordedRequest) -> ScriptedResponse:
- if request.path == TOKEN_PATH:
- return token_answer
- assert probe_answer is not None
- return probe_answer
+ answer = answers[request.path]
+ assert answer is not None, request.path
+ return answer
- with scripted_network(respond) as network:
- assert validate_credentials("na", "client", "secret", "Atzr|refresh") == expected
- assert network.requests_log[-1].path == (TOKEN_PATH if probe_answer is None else PARTICIPATIONS_PATH)
+ with scripted_network(respond):
+ assert validate_credentials("na", "client", "secret", "Atzr|refresh", marketplace_ids) == expected
def test_a_network_failure_is_reported_as_unavailable(self) -> None:
with scripted_network(always(requests.ConnectionError("boom"))):
- assert validate_credentials("na", "client", "secret", "Atzr|refresh") == (False, UNAVAILABLE_MESSAGE)
+ assert validate_credentials("na", "client", "secret", "Atzr|refresh", ["A"]) == (
+ False,
+ UNAVAILABLE_MESSAGE,
+ )
@pytest.mark.parametrize(
@@ -557,3 +594,441 @@ def test_transaction_windows_are_contiguous_and_end_before_the_request_margin()
assert windows[0].posted_after == start
assert windows[-1].posted_before == NOW - timedelta(seconds=180)
assert transaction_windows(NOW - timedelta(seconds=60), NOW) == []
+
+
+DOCUMENT_URL = "https://tortuga-prod-na.s3-external-1.amazonaws.com/doc.json?X-Amz-Signature=0123456789abcdef"
+
+
+def _gzip_json(body: dict[str, Any]) -> bytes:
+ return gzip.compress(json.dumps(body).encode())
+
+
+class _ReportsVendor:
+ """A scripted Reports API: each created report runs through the given statuses, then serves its rows."""
+
+ def __init__(self, statuses: list[str], documents: list[dict[str, Any]]) -> None:
+ self.statuses = statuses
+ self.documents = documents
+ self.created: list[dict[str, Any]] = []
+ self.polls: dict[str, int] = {}
+
+ def __call__(self, request: RecordedRequest) -> ScriptedResponse:
+ if request.path == TOKEN_PATH:
+ return TOKEN
+ if request.method == "POST" and request.path == REPORTS_PATH:
+ self.created.append(request.json())
+ return ScriptedResponse(status=202, json={"reportId": f"r{len(self.created)}"})
+ if request.path.startswith(f"{REPORTS_PATH}/"):
+ report_id = request.path.rsplit("/", 1)[1]
+ poll = self.polls.get(report_id, 0)
+ self.polls[report_id] = poll + 1
+ status = self.statuses[min(poll, len(self.statuses) - 1)]
+ body: dict[str, Any] = {"reportId": report_id, "processingStatus": status}
+ if status in ("DONE", "FATAL"):
+ body["reportDocumentId"] = f"doc-{report_id}"
+ return ScriptedResponse(json=body)
+ if request.path.startswith(f"{DOCUMENTS_PATH}/"):
+ return ScriptedResponse(
+ json={"reportDocumentId": "doc", "url": DOCUMENT_URL, "compressionAlgorithm": "GZIP"}
+ )
+ if request.path == "/doc.json":
+ index = sum(1 for poll_count in self.polls.values() if poll_count) - 1
+ return ScriptedResponse(body=_gzip_json(self.documents[min(index, len(self.documents) - 1)]))
+ raise AssertionError(f"unexpected request {request.method} {request.url}")
+
+
+class TestVendorReports:
+ @pytest.fixture(autouse=True)
+ def frozen_clock(self) -> Iterator[None]:
+ with time_machine.travel(NOW, tick=False):
+ yield
+
+ def test_daily_report_walks_windows_from_the_watermark_and_tags_rows(self) -> None:
+ vendor = _ReportsVendor(
+ ["IN_QUEUE", "IN_PROGRESS", "DONE"],
+ [
+ {"salesByAsin": [{"asin": "B01", "startDate": "2026-09-28", "shippedUnits": 3}]},
+ {"salesByAsin": [{"asin": "B02", "startDate": "2026-10-05", "shippedUnits": 1}]},
+ ],
+ )
+
+ result = _driver("ATVPDKIKX0DER").run(
+ "vendor_sales", vendor, incremental_field="startDate", db_incremental_field_last_value=date(2026, 9, 28)
+ )
+
+ assert result.raised is None
+ assert vendor.created == [
+ {
+ "reportType": "GET_VENDOR_SALES_REPORT",
+ "marketplaceIds": ["ATVPDKIKX0DER"],
+ "reportOptions": {
+ "reportPeriod": "DAY",
+ "distributorView": "MANUFACTURING",
+ "sellingProgram": "RETAIL",
+ },
+ "dataStartTime": "2026-09-28T00:00:00Z",
+ "dataEndTime": "2026-10-04T23:59:59Z",
+ },
+ {
+ "reportType": "GET_VENDOR_SALES_REPORT",
+ "marketplaceIds": ["ATVPDKIKX0DER"],
+ "reportOptions": {
+ "reportPeriod": "DAY",
+ "distributorView": "MANUFACTURING",
+ "sellingProgram": "RETAIL",
+ },
+ "dataStartTime": "2026-10-05T00:00:00Z",
+ "dataEndTime": "2026-10-11T23:59:59Z",
+ },
+ ]
+ assert result.rows == [
+ {"marketplaceId": "ATVPDKIKX0DER", "asin": "B01", "startDate": "2026-09-28", "shippedUnits": 3},
+ {"marketplaceId": "ATVPDKIKX0DER", "asin": "B02", "startDate": "2026-10-05", "shippedUnits": 1},
+ ]
+ download = next(request for request in result.requests if request.path == "/doc.json")
+ assert "x-amz-access-token" not in download.headers
+ assert result.committed_states[:2] == [
+ AmazonSellingPartnerResumeConfig(
+ marketplace_id="ATVPDKIKX0DER",
+ window_start="2026-09-28T00:00:00Z",
+ window_end="2026-10-04T23:59:59Z",
+ report_id="r1",
+ ),
+ AmazonSellingPartnerResumeConfig(marketplace_id="ATVPDKIKX0DER", window_start="2026-10-05T00:00:00Z"),
+ ]
+ assert result.final_state == AmazonSellingPartnerResumeConfig(completed_marketplaces=["ATVPDKIKX0DER"])
+
+ def test_resume_polls_the_saved_report_instead_of_creating_one(self) -> None:
+ vendor = _ReportsVendor(["DONE"], [{"inventoryByAsin": [{"asin": "B03", "startDate": "2026-10-05"}]}])
+
+ result = _driver("ATVPDKIKX0DER").run(
+ "vendor_inventory",
+ vendor,
+ resume_state=AmazonSellingPartnerResumeConfig(
+ marketplace_id="ATVPDKIKX0DER", window_start="2026-10-05T00:00:00Z", report_id="r9"
+ ),
+ )
+
+ assert result.raised is None
+ assert vendor.created == []
+ assert vendor.polls == {"r9": 1}
+ assert [row["asin"] for row in result.rows] == ["B03"]
+
+ def test_resume_skips_rows_of_the_report_already_handed_on(self) -> None:
+ rows = [{"asin": f"B{index:05}", "startDate": "2026-10-01"} for index in range(4500)]
+ vendor = _ReportsVendor(["DONE"], [{"forecastByAsin": rows}])
+
+ result = _driver("ATVPDKIKX0DER").run(
+ "vendor_forecasts",
+ vendor,
+ resume_state=AmazonSellingPartnerResumeConfig(
+ marketplace_id="ATVPDKIKX0DER", report_id="r7", rows_done=2000
+ ),
+ )
+
+ assert result.raised is None
+ assert vendor.created == []
+ assert [row["asin"] for row in result.rows] == [row["asin"] for row in rows[2000:]]
+ assert result.saved_states[0] == AmazonSellingPartnerResumeConfig(
+ marketplace_id="ATVPDKIKX0DER", report_id="r7", rows_done=4000
+ )
+
+ def test_resume_polls_a_saved_report_older_than_the_moving_lookback_floor(self) -> None:
+ vendor = _ReportsVendor(["CANCELLED"], [])
+
+ result = _driver("ATVPDKIKX0DER").run(
+ "vendor_real_time_sales",
+ vendor,
+ resume_state=AmazonSellingPartnerResumeConfig(
+ marketplace_id="ATVPDKIKX0DER", window_start="2026-09-16T11:00:00Z", report_id="r5"
+ ),
+ )
+
+ assert result.raised is None
+ assert "r5" in vendor.polls
+ assert vendor.created[0]["dataStartTime"] == "2026-09-17T11:00:00Z"
+
+ def test_resume_starts_the_next_window_where_the_saved_report_ended(self) -> None:
+ vendor = _ReportsVendor(["CANCELLED"], [])
+
+ result = _driver("ATVPDKIKX0DER").run(
+ "vendor_real_time_sales",
+ vendor,
+ resume_state=AmazonSellingPartnerResumeConfig(
+ marketplace_id="ATVPDKIKX0DER",
+ window_start="2026-10-15T08:00:00Z",
+ window_end="2026-10-15T09:00:00Z",
+ report_id="r6",
+ ),
+ )
+
+ assert result.raised is None
+ assert "r6" in vendor.polls
+ assert [(body["dataStartTime"], body["dataEndTime"]) for body in vendor.created] == [
+ ("2026-10-15T09:00:00Z", "2026-10-15T11:00:00Z")
+ ]
+
+ def test_forecasts_request_one_report_per_marketplace_without_a_date_range(self) -> None:
+ vendor = _ReportsVendor(["CANCELLED"], [])
+
+ result = _driver("ATVPDKIKX0DER,A2EUQ1WTGCTBG2").run("vendor_forecasts", vendor)
+
+ assert result.raised is None
+ assert vendor.created == [
+ {
+ "reportType": "GET_VENDOR_FORECASTING_REPORT",
+ "marketplaceIds": [marketplace],
+ "reportOptions": {"sellingProgram": "RETAIL"},
+ }
+ for marketplace in ("ATVPDKIKX0DER", "A2EUQ1WTGCTBG2")
+ ]
+ assert result.rows == []
+ assert result.final_state == AmazonSellingPartnerResumeConfig(
+ completed_marketplaces=["ATVPDKIKX0DER", "A2EUQ1WTGCTBG2"]
+ )
+
+ def test_real_time_sales_sends_the_marketplace_currency(self) -> None:
+ vendor = _ReportsVendor(["CANCELLED"], [])
+
+ result = _driver("A1F83G8C2ARO7P").run(
+ "vendor_real_time_sales",
+ vendor,
+ incremental_field="startTime",
+ db_incremental_field_last_value=datetime(2026, 10, 14, 9, 30, tzinfo=UTC),
+ )
+
+ assert result.raised is None
+ assert vendor.created == [
+ {
+ "reportType": "GET_VENDOR_REAL_TIME_SALES_REPORT",
+ "marketplaceIds": ["A1F83G8C2ARO7P"],
+ "reportOptions": {"currencyCode": "GBP"},
+ "dataStartTime": start,
+ "dataEndTime": end,
+ }
+ for start, end in [
+ ("2026-10-14T09:00:00Z", "2026-10-15T09:00:00Z"),
+ ("2026-10-15T09:00:00Z", "2026-10-15T11:00:00Z"),
+ ]
+ ]
+
+ def test_a_fatal_report_raises_with_amazons_error_details(self) -> None:
+ def respond(request: RecordedRequest) -> ScriptedResponse:
+ if request.path == "/doc.json":
+ return ScriptedResponse(body=_gzip_json({"errorDetails": "Report date range is not available yet."}))
+ return vendor(request)
+
+ vendor = _ReportsVendor(["FATAL"], [])
+
+ result = _driver("ATVPDKIKX0DER").run("vendor_forecasts", respond)
+
+ assert isinstance(result.raised, VendorReportError)
+ assert str(result.raised) == (
+ "Amazon could not generate the GET_VENDOR_FORECASTING_REPORT report: Report date range is not available yet."
+ )
+ # The failed report is dropped, so the retry creates a new one instead of polling it again.
+ assert result.final_state == AmazonSellingPartnerResumeConfig(marketplace_id="ATVPDKIKX0DER")
+
+ def test_a_failed_download_keeps_the_presigned_url_out_of_the_error(self) -> None:
+ vendor = _ReportsVendor(["DONE"], [])
+
+ def respond(request: RecordedRequest) -> ScriptedResponse:
+ if request.path == "/doc.json":
+ return ScriptedResponse(status=403, body=b"<Error><Code>AccessDenied</Code></Error>")
+ return vendor(request)
+
+ result = _driver("ATVPDKIKX0DER").run("vendor_forecasts", respond)
+
+ assert isinstance(result.raised, requests.HTTPError)
+ assert str(result.raised) == "Amazon report document download returned status=403"
+
+ def test_create_report_waits_out_a_rate_limit(self) -> None:
+ vendor = _ReportsVendor(["CANCELLED"], [])
+ throttled = [ScriptedResponse(status=429, json={"errors": [{"code": "QuotaExceeded"}]})]
+
+ def respond(request: RecordedRequest) -> ScriptedResponse:
+ if request.method == "POST" and request.path == REPORTS_PATH and throttled:
+ return throttled.pop()
+ return vendor(request)
+
+ result = _driver("ATVPDKIKX0DER").run("vendor_forecasts", respond)
+
+ assert result.raised is None
+ assert [request.method for request in result.requests if request.path == REPORTS_PATH] == ["POST", "POST"]
+
+ @pytest.mark.parametrize(
+ ("fatal_reports", "expected_starts", "expected_rows", "raises"),
+ [
+ (
+ {"r1"},
+ ["2026-09-21T00:00:00Z", "2026-09-21T00:00:00Z", "2026-09-28T00:00:00Z", "2026-10-05T00:00:00Z"],
+ 3,
+ False,
+ ),
+ ({"r1", "r2", "r3"}, ["2026-09-21T00:00:00Z"] * 3, 0, True),
+ ],
+ )
+ def test_a_fatal_old_window_is_retried_and_never_passed(
+ self, fatal_reports: set[str], expected_starts: list[str], expected_rows: int, raises: bool
+ ) -> None:
+ vendor = _ReportsVendor(["DONE"], [{"salesByAsin": [{"asin": "B07", "startDate": "2026-10-05"}]}])
+
+ def respond(request: RecordedRequest) -> ScriptedResponse:
+ report_id = request.path.rsplit("/", 1)[1]
+ if request.path.startswith(f"{REPORTS_PATH}/") and report_id in fatal_reports:
+ return ScriptedResponse(json={"reportId": report_id, "processingStatus": "FATAL"})
+ return vendor(request)
+
+ result = _driver("ATVPDKIKX0DER").run(
+ "vendor_sales", respond, incremental_field="startDate", db_incremental_field_last_value=date(2026, 9, 21)
+ )
+
+ assert [body["dataStartTime"] for body in vendor.created] == expected_starts
+ assert [row["asin"] for row in result.rows] == ["B07"] * expected_rows
+ if raises:
+ assert isinstance(result.raised, VendorReportError)
+ assert result.final_state == AmazonSellingPartnerResumeConfig(
+ marketplace_id="ATVPDKIKX0DER", window_start="2026-09-21T00:00:00Z"
+ )
+ else:
+ assert result.raised is None
+
+ def test_a_document_url_outside_amazon_is_refused(self) -> None:
+ vendor = _ReportsVendor(["DONE"], [])
+
+ def respond(request: RecordedRequest) -> ScriptedResponse:
+ if request.path.startswith(f"{DOCUMENTS_PATH}/"):
+ return ScriptedResponse(json={"reportDocumentId": "doc", "url": "https://evil.example.com/doc.json"})
+ return vendor(request)
+
+ result = _driver("ATVPDKIKX0DER").run("vendor_forecasts", respond)
+
+ assert isinstance(result.raised, ValueError)
+ assert all(request.origin != "https://evil.example.com" for request in result.requests)
+
+ def test_vendor_tables_need_marketplace_ids(self) -> None:
+ result = _driver().run("vendor_sales", [])
+
+ assert isinstance(result.raised, ValueError)
+ assert str(result.raised) == MISSING_MARKETPLACES_MESSAGE
+ assert result.requests == []
+
+
+ ("endpoint", "start", "resumed", "expected"),
+ [
+ # A full refresh of a daily report starts at the oldest day Amazon keeps and stops four days back.
+ ("vendor_sales", None, False, ("2022-10-17T00:00:00Z", "2022-10-23T23:59:59Z", 208, "2026-10-11T23:59:59Z")),
+ # An hourly report stops at the last hour that closed five minutes before now.
+ (
+ "vendor_real_time_sales",
+ None,
+ False,
+ ("2026-09-16T12:00:00Z", "2026-09-17T12:00:00Z", 29, "2026-10-15T11:00:00Z"),
+ ),
+ ("vendor_sales", datetime(2026, 10, 12, tzinfo=UTC), False, None),
+ # A resumed report keeps its start after the lookback floor moved past it.
+ (
+ "vendor_real_time_sales",
+ datetime(2026, 9, 16, 11, tzinfo=UTC),
+ True,
+ ("2026-09-16T11:00:00Z", "2026-09-17T11:00:00Z", 29, "2026-10-15T11:00:00Z"),
+ ),
+ ],
+)
+def test_report_windows(
+ endpoint: str, start: datetime | None, resumed: bool, expected: tuple[str, str, int, str] | None
+) -> None:
+ windows = report_windows(VENDOR_REPORTS[endpoint], start, NOW, resumed=resumed)
+
+ if expected is None:
+ assert windows == []
+ return
+ first_start, first_end, count, last_end = expected
+ assert (windows[0].data_start_time, windows[0].data_end_time, len(windows), windows[-1].data_end_time) == (
+ first_start,
+ first_end,
+ count,
+ last_end,
+ )
+
+
+PARTICIPATING_IN_A = ScriptedResponse(
+ json={"payload": [{"marketplace": {"id": "A"}, "participation": {"isParticipating": True}}]}
+)
+
+
+ ("forbidden_paths", "marketplace_ids", "expected", "probed_paths"),
+ [
+ (
+ {REPORTS_PATH},
+ "A",
+ {"orders": None, "inventory_summaries": None, "vendor_sales": VENDOR_ONLY_MESSAGE},
+ [ORDERS_PATH, SUMMARIES_PATH, REPORTS_PATH],
+ ),
+ (
+ {ORDERS_PATH, SUMMARIES_PATH},
+ "A",
+ {"orders": SELLER_ONLY_MESSAGE, "inventory_summaries": SELLER_ONLY_MESSAGE, "vendor_sales": None},
+ [ORDERS_PATH, SUMMARIES_PATH, REPORTS_PATH],
+ ),
+ (
+ set(),
+ None,
+ {"orders": None, "inventory_summaries": None, "vendor_sales": MISSING_MARKETPLACES_MESSAGE},
+ [ORDERS_PATH, PARTICIPATIONS_PATH, SUMMARIES_PATH, REPORTS_PATH],
+ ),
+ (
+ {PARTICIPATIONS_PATH},
+ None,
+ {"orders": None, "inventory_summaries": SELLER_ONLY_MESSAGE, "vendor_sales": MISSING_MARKETPLACES_MESSAGE},
+ [ORDERS_PATH, PARTICIPATIONS_PATH, REPORTS_PATH],
+ ),
+ ],
+)
+def test_probe_endpoint_permissions(
+ forbidden_paths: set[str], marketplace_ids: str | None, expected: dict[str, str | None], probed_paths: list[str]
+) -> None:
+ def respond(request: RecordedRequest) -> ScriptedResponse:
+ if request.path == TOKEN_PATH:
+ return TOKEN
+ if request.path in forbidden_paths:
+ return SP_API_FORBIDDEN
+ return PARTICIPATING_IN_A if request.path == PARTICIPATIONS_PATH else ScriptedResponse(json={})
+
+ with scripted_network(respond) as network:
+ permissions = probe_endpoint_permissions(
+ "na", "client", "secret", "Atzr|refresh", parse_marketplace_ids(marketplace_ids), list(expected)
+ )
+
+ assert permissions == expected
+ assert [request.path for request in network.requests_log if request.path != TOKEN_PATH] == probed_paths
+
+
+def test_probes_past_the_setup_budget_leave_access_unknown() -> None:
+ def respond(request: RecordedRequest) -> ScriptedResponse:
+ if request.path == TOKEN_PATH:
+ return TOKEN
+ time.sleep(40)
+ return SP_API_FORBIDDEN
+
+ with scripted_network(respond) as network:
+ permissions = probe_endpoint_permissions(
+ "na", "client", "secret", "Atzr|refresh", ["A"], ["orders", "transactions", "vendor_sales"]
+ )
+
+ assert permissions == {"orders": SELLER_ONLY_MESSAGE, "transactions": None, "vendor_sales": None}
+ assert [request.path for request in network.requests_log if request.path != TOKEN_PATH] == [ORDERS_PATH]
+
+
+def test_a_transient_marketplace_discovery_failure_leaves_inventory_access_unknown() -> None:
+ def respond(request: RecordedRequest) -> ScriptedResponse:
+ if request.path == TOKEN_PATH:
+ return TOKEN
+ return ScriptedResponse(status=400, json={"errors": [{"code": "InvalidInput"}]})
+
+ with scripted_network(respond):
+ permissions = probe_endpoint_permissions("na", "client", "secret", "Atzr|refresh", [], ["inventory_summaries"])
+
+ assert permissions == {"inventory_summaries": None}