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): add 2 missing tables to the Xsolla source (#126738)

Tom Owers3881da681ca9
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index a0f5bc677230..c55d93e5297e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -13450,8 +13450,8 @@ Diffed against: <https://developers.xsolla.com/_bundle/api/catalog/index.json?do
- [x] `Get list of virtual items (GET /v2/project/{project_id}/admin/items/virtual_items)` — join purchases to product names, SKUs, prices, and catalog attributes for product revenue analysis (medium)
- [x] `Get list of virtual currencies (GET /v2/project/{project_id}/admin/items/virtual_currency)` — describe currencies sold within games and compare currency pricing and sales across projects (medium)
- [x] `Get list of bundles (GET /v2/project/{project_id}/admin/items/bundle)` — analyze bundle contents and prices alongside purchases and promotion results (medium)
-- [ ] `Get payouts breakdown in currency (GET /merchant/v2/merchants/{merchant_id}/reports/transactions/summary/transfer)` — compare currency totals for payments, commissions, taxes, and amounts due for payout (medium)
-- [ ] `Get rewards (GET /merchant/v2/merchants/{merchant_id}/promotions/{promotion_id}/rewards)` — explain promotion results using item bonuses, discounts, and subscription trial rewards (medium)
+- [x] `Get payouts breakdown in currency (GET /merchant/v2/merchants/{merchant_id}/reports/transactions/summary/transfer)` — compare currency totals for payments, commissions, taxes, and amounts due for payout (medium)
+- [x] `Get rewards (GET /merchant/v2/merchants/{merchant_id}/promotions/{promotion_id}/rewards)` — explain promotion results using item bonuses, discounts, and subscription trial rewards (medium)
Note: Diffed the Catalog specification and the Pay Station and Subscriptions specifications against the nine static tables. Additional specifications: https://developers.xsolla.com/_bundle/api/pay-station/index.json?download and https://developers.xsolla.com/_bundle/api/subscriptions/index.json?download. Catalog collections use store.xsolla.com and project IDs; rewards require reads for each promotion. Excluded repeated transaction searches, user subscription subsets, authentication, uploads, and promotion periods already represented by promotion dates.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/xsolla/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/xsolla/canonical_descriptions.py
index 87e3bbe1e460..5f3d6ec97f2d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/xsolla/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/xsolla/canonical_descriptions.py
@@ -117,6 +117,26 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"read_only": "Whether the promotion is read-only.",
},
},
+ "promotion_rewards": {
+ "description": "Rewards of each promotion: purchase discounts, package bonuses, item rewards, and subscription trials.",
+ "docs_url": "https://developers.xsolla.com/api/subscriptions/operation/get-rewards/",
+ "columns": {
+ "promotion_id": "ID of the promotion that the rewards belong to.",
+ "purchase": "Reward for the whole purchase: the discount percentage.",
+ "package": "Reward for a virtual currency package: a bonus percentage or a bonus amount of the currency.",
+ "item": "Rewards for specific virtual items: item discounts and extra items given as a bonus.",
+ "subscription": "Reward for a subscription: the trial period in days.",
+ },
+ },
+ "payouts_breakdown": {
+ "description": "Payment, commission, tax, and payout totals for each currency, one row for each calendar month.",
+ "docs_url": "https://developers.xsolla.com/api/pay-station/operation/get-payouts-breakdown/",
+ "columns": {
+ "period_start": "First day of the calendar month that the totals cover.",
+ "period_end": "Last day of the calendar month that the totals cover. The current month ends on the sync date.",
+ "IsoCurrency": "ISO 4217 currency code of the totals.",
+ },
+ },
"projects": {
"description": "Projects in the merchant's Publisher Account.",
"docs_url": PAY_STATION_DOCS,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/xsolla/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/xsolla/settings.py
index 832ba21dafcf..bf4b9337d8cd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/xsolla/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/xsolla/settings.py
@@ -26,18 +26,27 @@ RESPONSE_ACTIONS: list[ResponseAction] = [
{"status_code": 403, "action": "raise", "message": AUTH_ERROR},
]
# A project in the merchant project list can have no store, so the Store API does not know it.
-STORE_RESPONSE_ACTIONS: list[ResponseAction] = [*RESPONSE_ACTIONS, {"status_code": 404, "action": "ignore"}]
+# A promotion can also be deleted between the read of the promotion list and the read of its rewards.
+NOT_FOUND_IGNORED_RESPONSE_ACTIONS: list[ResponseAction] = [
+ *RESPONSE_ACTIONS,
+ {"status_code": 404, "action": "ignore"},
+]
@frozen
class XsollaEndpoint:
path: str
primary_keys: tuple[str, ...] = ("id",)
- # Project endpoints are read once per project that the merchant owns.
- scope: Literal["merchant", "project"] = "merchant"
+ # Project and promotion endpoints are read once per project or promotion of the merchant.
+ scope: Literal["merchant", "project", "promotion"] = "merchant"
paginated: bool = True
# Endpoints that need datetime_from/datetime_to are read in windows of this many days.
window_days: int | None = None
+ # Reads one calendar month for each request, and stamps the month on each row as period_start/period_end.
+ monthly_windows: bool = False
+ # False for endpoints that return one object instead of a list.
+ list_response: bool = True
+ ignore_not_found: bool = False
# Nested values copied to the row root, so that they can be primary keys or incremental fields.
lifted_fields: tuple[tuple[str, str, str], ...] = ()
partition_key: str | None = None
@@ -91,10 +100,24 @@ ENDPOINTS: dict[str, XsollaEndpoint] = {
path="merchants/{merchant_id}/promotions",
paginated=False,
),
+ "promotion_rewards": XsollaEndpoint(
+ path="merchants/{merchant_id}/promotions/{promotion_id}/rewards",
+ primary_keys=("promotion_id",),
+ scope="promotion",
+ paginated=False,
+ list_response=False,
+ ignore_not_found=True,
+ ),
"projects": XsollaEndpoint(
path="merchants/{merchant_id}/projects",
paginated=False,
),
+ "payouts_breakdown": XsollaEndpoint(
+ path="merchants/{merchant_id}/reports/transactions/summary/transfer",
+ primary_keys=("period_start", "IsoCurrency"),
+ paginated=False,
+ monthly_windows=True,
+ ),
"transaction_registry": XsollaEndpoint(
path="merchants/{merchant_id}/reports/transactions/registry.json",
base_url=REGISTRY_BASE_URL,
@@ -107,6 +130,7 @@ ENDPOINTS: dict[str, XsollaEndpoint] = {
scope="project",
base_url=STORE_BASE_URL,
store=True,
+ ignore_not_found=True,
),
"virtual_currencies": XsollaEndpoint(
path="project/{project_id}/admin/items/virtual_currency",
@@ -114,6 +138,7 @@ ENDPOINTS: dict[str, XsollaEndpoint] = {
scope="project",
base_url=STORE_BASE_URL,
store=True,
+ ignore_not_found=True,
),
"bundles": XsollaEndpoint(
path="project/{project_id}/admin/items/bundle",
@@ -121,6 +146,7 @@ ENDPOINTS: dict[str, XsollaEndpoint] = {
scope="project",
base_url=STORE_BASE_URL,
store=True,
+ ignore_not_found=True,
),
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/xsolla/tests/test_xsolla.py b/products/warehouse_sources/backend/temporal/data_imports/sources/xsolla/tests/test_xsolla.py
index 0ce10fa37f6f..28795944367c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/xsolla/tests/test_xsolla.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/xsolla/tests/test_xsolla.py
@@ -121,6 +121,77 @@ def test_project_tables_read_each_project_and_resume_after_finished_projects(dri
assert result.saved_states[-1] == XsollaResumeConfig(project_id=31)
+def test_promotion_rewards_read_each_promotion_skip_deleted_ones_and_resume(driver: SourceDriver) -> None:
+ result = driver.run(
+ "promotion_rewards",
+ route(
+ {
+ "/merchants/123/promotions": [ScriptedResponse(json=[{"id": 40}, {"id": 10}, {"id": 30}, {"id": 20}])],
+ "/merchants/123/promotions/20/rewards": [
+ ScriptedResponse(json={"id": 20, "purchase": {"discount_percent": 15}})
+ ],
+ "/merchants/123/promotions/30/rewards": [
+ ScriptedResponse(status=404, json={"http_status_code": 404, "message": "Promotion not found"})
+ ],
+ "/merchants/123/promotions/40/rewards": [ScriptedResponse(json={"subscription": {"trial_days": 7}})],
+ }
+ ),
+ resume_state=XsollaResumeConfig(promotion_id=20),
+ )
+
+ assert result.raised is None
+ assert [(row["promotion_id"], row.get("purchase"), row.get("subscription")) for row in result.rows] == [
+ (20, {"discount_percent": 15}, None),
+ (40, None, {"trial_days": 7}),
+ ]
+ assert not any("/promotions/10/" in url for url in result.urls)
+ assert result.saved_states[-1] == XsollaResumeConfig(promotion_id=41)
+
+
+ "now,resume_state,expected_periods",
+ [
+ (
+ "2010-03-15T12:00:00Z",
+ None,
+ [("2010-01-01", "2010-01-31"), ("2010-02-01", "2010-02-28"), ("2010-03-01", "2010-03-15")],
+ ),
+ (
+ "2012-03-01T12:00:00Z",
+ XsollaResumeConfig(window_start="2011-12-01"),
+ [
+ ("2011-12-01", "2011-12-31"),
+ ("2012-01-01", "2012-01-31"),
+ ("2012-02-01", "2012-02-29"),
+ ("2012-03-01", "2012-03-01"),
+ ],
+ ),
+ ],
+)
+def test_payouts_breakdown_reads_calendar_months_and_stamps_the_period(
+ driver: SourceDriver,
+ now: str,
+ resume_state: XsollaResumeConfig | None,
+ expected_periods: list[tuple[str, str]],
+) -> None:
+ def breakdown(request: RecordedRequest) -> ScriptedResponse:
+ return ScriptedResponse(
+ json=[
+ {"IsoCurrency": "USD", "PaymentsAmount": 10.5, "SumPayoutSum": 9.1},
+ {"IsoCurrency": "EUR", "PaymentsAmount": 4.0, "SumPayoutSum": 3.2},
+ ]
+ )
+
+ with time_machine.travel(now, tick=False):
+ result = driver.run("payouts_breakdown", breakdown, resume_state=resume_state)
+
+ assert result.raised is None
+ assert [(r.param("datetime_from"), r.param("datetime_to")) for r in result.requests] == expected_periods
+ assert [(row["period_start"], row["period_end"], row["IsoCurrency"]) for row in result.rows] == [
+ (start, end, currency) for start, end in expected_periods for currency in ("USD", "EUR")
+ ]
+
+
@pytest.mark.parametrize(
"table,path",
[
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/xsolla/xsolla.py b/products/warehouse_sources/backend/temporal/data_imports/sources/xsolla/xsolla.py
index 8686c17b608b..04d908d39251 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/xsolla/xsolla.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/xsolla/xsolla.py
@@ -18,10 +18,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.xsolla.set
AUTH_ERROR,
ENDPOINTS,
HISTORY_START,
+ NOT_FOUND_IGNORED_RESPONSE_ACTIONS,
PAGE_SIZE,
RESPONSE_ACTIONS,
STORE_PAGE_SIZE,
- STORE_RESPONSE_ACTIONS,
TRANSACTIONS_LOOKBACK_DAYS,
XsollaEndpoint,
)
@@ -34,6 +34,7 @@ class XsollaResumeConfig:
window_start: str | None = None
project_id: int | None = None
offset: int = 0
+ promotion_id: int | None = None
def parse_merchant_id(merchant_id: str) -> str:
@@ -90,9 +91,11 @@ def _rest_config(
"endpoint": {
"path": path,
"params": params,
- "response_actions": STORE_RESPONSE_ACTIONS if endpoint.store else RESPONSE_ACTIONS,
+ "response_actions": NOT_FOUND_IGNORED_RESPONSE_ACTIONS
+ if endpoint.ignore_not_found
+ else RESPONSE_ACTIONS,
# The projects list shape is not documented, so only the documented list endpoints fail loud.
- "data_selector_required": name != "projects",
+ "data_selector_required": endpoint.list_response and name != "projects",
**({"data_selector": "items"} if endpoint.store else {}),
},
"table_format": "delta",
@@ -102,16 +105,17 @@ def _rest_config(
}
-def _row_mapper(endpoint: XsollaEndpoint, project_id: int | None) -> Callable[[dict[str, Any]], dict[str, Any]] | None:
- if not endpoint.lifted_fields and project_id is None:
+def _row_mapper(
+ endpoint: XsollaEndpoint, extra_fields: dict[str, Any]
+) -> Callable[[dict[str, Any]], dict[str, Any]] | None:
+ if not endpoint.lifted_fields and not extra_fields:
return None
def map_row(row: dict[str, Any]) -> dict[str, Any]:
for target, parent, child in endpoint.lifted_fields:
nested = row.get(parent)
row[target] = nested.get(child) if isinstance(nested, dict) else None
- if project_id is not None:
- row["project_id"] = project_id
+ row.update(extra_fields)
return row
return map_row
@@ -143,15 +147,29 @@ def _window_params(name: str, window_start: date, window_end: date) -> dict[str,
return params
-def list_project_ids(
- config: XsollaSourceConfig, merchant_id: str, team_id: int, job_id: str, api_version: str
+def _window_end(endpoint: XsollaEndpoint, window_start: date, today: date) -> date:
+ if endpoint.monthly_windows:
+ next_month = (window_start.replace(day=1) + timedelta(days=32)).replace(day=1)
+ return min(next_month - timedelta(days=1), today)
+ assert endpoint.window_days is not None
+ return min(window_start + timedelta(days=endpoint.window_days - 1), today)
+
+
+def _parent_state(scope: str, parent_id: int, offset: int = 0) -> XsollaResumeConfig:
+ if scope == "promotion":
+ return XsollaResumeConfig(promotion_id=parent_id, offset=offset)
+ return XsollaResumeConfig(project_id=parent_id, offset=offset)
+
+
+def list_parent_ids(
+ config: XsollaSourceConfig, merchant_id: str, parent: str, team_id: int, job_id: str, api_version: str
) -> list[int]:
- endpoint = ENDPOINTS["projects"]
+ endpoint = ENDPOINTS[parent]
resource = rest_api_resource(
_rest_config(
config,
merchant_id,
- "projects",
+ parent,
endpoint,
endpoint.path.format(merchant_id=merchant_id),
{},
@@ -162,7 +180,7 @@ def list_project_ids(
job_id,
None,
)
- return sorted({int(project["id"]) for page in resource for project in page if project.get("id") is not None})
+ return sorted({int(row["id"]) for page in resource for row in page if row.get("id") is not None})
def xsolla_source(
@@ -186,7 +204,11 @@ def xsolla_source(
start = max(start, watermark - timedelta(days=TRANSACTIONS_LOOKBACK_DAYS))
def read(
- path: str, params: dict[str, Any], project_id: int | None, offset: int, save: Callable[[int | None], None]
+ path: str,
+ params: dict[str, Any],
+ extra_fields: dict[str, Any],
+ offset: int,
+ save: Callable[[int | None], None],
) -> Iterator[list[dict[str, Any]]]:
def resume_hook(paginator_state: dict[str, Any] | None) -> None:
save(int(paginator_state["offset"]) if paginator_state else None)
@@ -201,7 +223,7 @@ def xsolla_source(
path,
params,
api_version,
- _row_mapper(endpoint, project_id),
+ _row_mapper(endpoint, extra_fields),
),
team_id,
job_id,
@@ -211,7 +233,6 @@ def xsolla_source(
)
def windowed_items(state: XsollaResumeConfig) -> Iterator[list[dict[str, Any]]]:
- assert endpoint.window_days is not None
path = endpoint.path.format(merchant_id=merchant_id)
today = datetime.now(UTC).date()
window_start = date.fromisoformat(state.window_start) if state.window_start else start
@@ -220,7 +241,7 @@ def xsolla_source(
seen: set[tuple[Any, ...]] = set()
while window_start <= today:
- window_end = min(window_start + timedelta(days=endpoint.window_days - 1), today)
+ window_end = _window_end(endpoint, window_start, today)
next_start = window_end + timedelta(days=1)
def save(next_offset: int | None, current: date = window_start, following: date = next_start) -> None:
@@ -229,7 +250,12 @@ def xsolla_source(
else:
manager.save_state(XsollaResumeConfig(window_start=current.isoformat(), offset=next_offset))
- for page in read(path, _window_params(endpoint_name, window_start, window_end), None, offset, save):
+ period = (
+ {"period_start": window_start.isoformat(), "period_end": window_end.isoformat()}
+ if endpoint.monthly_windows
+ else {}
+ )
+ for page in read(path, _window_params(endpoint_name, window_start, window_end), period, offset, save):
if endpoint.paginated:
yield page
continue
@@ -245,32 +271,36 @@ def xsolla_source(
window_start = next_start
offset = 0
- def project_items(state: XsollaResumeConfig) -> Iterator[list[dict[str, Any]]]:
- for project_id in list_project_ids(config, merchant_id, team_id, job_id, api_version):
- if state.project_id is not None and project_id < state.project_id:
+ def parent_items(state: XsollaResumeConfig) -> Iterator[list[dict[str, Any]]]:
+ parent_key = f"{endpoint.scope}_id"
+ resume_id = state.promotion_id if endpoint.scope == "promotion" else state.project_id
+ parent_ids = list_parent_ids(config, merchant_id, f"{endpoint.scope}s", team_id, job_id, api_version)
+ for parent_id in parent_ids:
+ if resume_id is not None and parent_id < resume_id:
continue
- offset = state.offset if project_id == state.project_id else 0
+ offset = state.offset if parent_id == resume_id else 0
- def save(next_offset: int | None, current: int = project_id) -> None:
+ def save(next_offset: int | None, current: int = parent_id) -> None:
if next_offset is None:
- # Project IDs are read in ascending order, so the next run starts after this project.
- manager.save_state(XsollaResumeConfig(project_id=current + 1))
+ # Parent IDs are read in ascending order, so the next run starts after this parent.
+ manager.save_state(_parent_state(endpoint.scope, current + 1))
else:
- manager.save_state(XsollaResumeConfig(project_id=current, offset=next_offset))
+ manager.save_state(_parent_state(endpoint.scope, current, next_offset))
- yield from read(endpoint.path.format(project_id=project_id), {}, project_id, offset, save)
+ path = endpoint.path.format(merchant_id=merchant_id, **{parent_key: parent_id})
+ yield from read(path, {}, {parent_key: parent_id}, offset, save)
def items() -> Iterator[list[dict[str, Any]]]:
state = (manager.load_state() if manager.can_resume() else None) or XsollaResumeConfig()
- if endpoint.scope == "project":
- yield from project_items(state)
- elif endpoint.window_days is not None:
+ if endpoint.scope != "merchant":
+ yield from parent_items(state)
+ elif endpoint.window_days is not None or endpoint.monthly_windows:
yield from windowed_items(state)
else:
yield from read(
endpoint.path.format(merchant_id=merchant_id),
{},
- None,
+ {},
state.offset,
lambda next_offset: (
manager.save_state(XsollaResumeConfig(offset=next_offset)) if next_offset is not None else None