: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add 4 missing tables to the Paystack source (#124783)
Tom Owers45536c0e123c
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txtindex 52d1158a6500..af11107a3d90 100644--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt@@ -846,8 +846,6 @@1 products/warehouse_sources/backend/temporal/data_imports/sources/partnerstack/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/payfit/payfit.py1 products/warehouse_sources/backend/temporal/data_imports/sources/payfit/settings.py-1 products/warehouse_sources/backend/temporal/data_imports/sources/paystack/paystack.py-1 products/warehouse_sources/backend/temporal/data_imports/sources/paystack/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/pendo/pendo.py1 products/warehouse_sources/backend/temporal/data_imports/sources/pendo/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/perigon/perigon.pydiff --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.mdindex 9fade89394a6..2019eff02c3e 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@@ -9239,14 +9239,14 @@ Today (13): `Customers`, `Disputes`, `PaymentPages`, `PaymentRequests`, `Plans`,Diffed against: <https://raw.githubusercontent.com/PaystackOSS/openapi/main/dist/paystack.yaml>-- [ ] `/settlement/{id}/transactions` — maps settlements we already sync to the transactions we already sync - the payout reconciliation join (high)-- [ ] `/balance/ledger` — ledger entries behind every balance movement, the money-movement fact table (high)-- [ ] `/split (transaction splits)` — lookup resolving split codes carried on transactions and subaccounts we already sync (high)+- [x] `/settlement/{id}/transactions` — maps settlements we already sync to the transactions we already sync - the payout reconciliation join (high)+- [x] `/balance/ledger` — ledger entries behind every balance movement, the money-movement fact table (high)+- [x] `/split (transaction splits)` — lookup resolving split codes carried on transactions and subaccounts we already sync (high)- [ ] `/bank` — bank lookup resolving the bank codes on transfer recipients we already sync (medium)- [ ] `/transaction/timeline/{id}` — per-transaction event/state history for funnel and failure analysis (medium)- [ ] `/bulkcharge and /bulkcharge/{code}/charges` — batch charge runs plus their member charges (medium)- [ ] `/dedicated_account (dedicated virtual accounts)` — virtual NUBANs assigned to customers, needed to attribute bank-transfer inflows (medium)-- [ ] `/directdebit/mandate-authorizations` — direct debit mandates underpinning recurring collections (medium)+- [x] `/directdebit/mandate-authorizations` — direct debit mandates underpinning recurring collections (medium)- [ ] `/order and /order/{id}` — commerce orders with line items sitting above transactions (medium)- [ ] `/storefront and /storefront/{id}/order` — storefront dimension for the orders above (low)- [ ] `/transaction/totals and /paymentrequest/totals` — vendor-computed volume aggregates useful as a cross-check (low)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/paystack/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/paystack/canonical_descriptions.pyindex f937092268e7..1186a7d516c3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/paystack/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/paystack/canonical_descriptions.py@@ -177,4 +177,62 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"createdAt": "Time the payment page was created, as an ISO 8601 timestamp.",},},+ "TransactionSplits": {+ "description": "Transaction splits that share each payment between your main account and one or more subaccounts.",+ "docs_url": "https://paystack.com/docs/api/split/",+ "columns": {+ "id": "Unique integer identifier for the split.",+ "split_code": "Paystack split code (format SPL_xxxxxxxx) that transactions reference.",+ "name": "Name of the split.",+ "type": "How shares are expressed — 'percentage' or 'flat'.",+ "currency": "Currency of the split.",+ "active": "Whether the split can currently be used on transactions.",+ "bearer_type": "Who bears the Paystack charges — e.g. 'account', 'subaccount', 'all-proportional' or 'all'.",+ "bearer_subaccount": "Subaccount that bears the charges when bearer_type is 'subaccount'.",+ "subaccounts": "Subaccounts in the split with their share of each transaction.",+ "total_subaccounts": "Number of subaccounts in the split.",+ "createdAt": "Time the split was created, as an ISO 8601 timestamp.",+ },+ },+ "BalanceLedger": {+ "description": "Ledger entries for every movement on your Paystack balance.",+ "docs_url": "https://paystack.com/docs/api/transfer-control/#balance-ledger",+ "columns": {+ "id": "Unique integer identifier for the ledger entry.",+ "balance": "Balance after this entry, in the smallest currency unit.",+ "difference": "Amount this entry changed the balance by, in the smallest currency unit.",+ "currency": "Currency of the balance.",+ "reason": "Human-readable reason for the balance movement.",+ "model_responsible": "Type of the Paystack object that caused the movement (e.g. Transaction, Transfer).",+ "model_row": "Id of the Paystack object that caused the movement.",+ "createdAt": "Time the ledger entry was created, as an ISO 8601 timestamp.",+ },+ },+ "SettlementTransactions": {+ "description": "Transactions paid out in each settlement, one row per settlement and transaction.",+ "docs_url": "https://paystack.com/docs/api/settlement/#transactions",+ "columns": {+ "settlement_id": "Id of the settlement the transaction was paid out in.",+ "id": "Unique integer identifier for the transaction.",+ "reference": "Unique transaction reference you or Paystack assigned.",+ "amount": "Amount of the transaction in the smallest currency unit (e.g. kobo for NGN).",+ "currency": "Currency the transaction was carried out in.",+ "status": "Transaction outcome — typically 'success'.",+ },+ },+ "DirectDebitMandateAuthorizations": {+ "description": "Direct debit mandates customers authorized so you can charge their bank account.",+ "docs_url": "https://paystack.com/docs/api/direct-debit/",+ "columns": {+ "id": "Unique integer identifier for the mandate authorization.",+ "status": "Status of the authorization — 'pending', 'active' or 'revoked'.",+ "mandate_id": "Id of the direct debit mandate.",+ "authorization_id": "Id of the reusable authorization created for the mandate.",+ "authorization_code": "Authorization code (format AUTH_xxxxxxxx) used to charge the customer.",+ "account_number": "Bank account number the mandate debits.",+ "bank_code": "Code of the bank that holds the account.",+ "customer": "The customer who authorized the mandate.",+ "authorized_at": "Time the customer authorized the mandate, as an ISO 8601 timestamp.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/paystack/paystack.py b/products/warehouse_sources/backend/temporal/data_imports/sources/paystack/paystack.pyindex dcc3c871ed66..59c456147b6a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/paystack/paystack.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/paystack/paystack.py@@ -8,20 +8,38 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.httfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (RESTAPIConfig,rest_api_resource,+ rest_api_resources,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ rename_parent_fields,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ BasePaginator,+ JSONResponseCursorPaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ Endpoint,+ EndpointResource,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import BasePaginator-from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import EndpointResourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager-from products.warehouse_sources.backend.temporal.data_imports.sources.paystack.settings import PAYSTACK_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.paystack.settings import (+ PAYSTACK_ENDPOINTS,+ PaystackEndpointConfig,+)PAYSTACK_BASE_URL = "https://api.paystack.co"# Paystack caps list pages at 100 records (default 50).PAGE_SIZE = 100[email protected](frozen=True)class PaystackResumeConfig:- next_page: int+ next_page: Optional[int] = None+ next_cursor: Optional[str] = None+ # Fan-out tables checkpoint the shape the dependent resource emits: which parents finished+ # and where the current one stopped.+ fanout_state: Optional[dict[str, Any]] = Noneclass PaystackPaginator(BasePaginator):@@ -34,14 +52,15 @@ class PaystackPaginator(BasePaginator):recommended termination signal for offset pagination."""- def __init__(self, page: int = 1) -> None:+ def __init__(self, page: int = 1, page_size_param: str = "perPage") -> None:super().__init__()self._page = page+ self._page_size_param = page_size_paramdef init_request(self, request: Request) -> None:if request.params is None:request.params = {}- request.params["perPage"] = PAGE_SIZE+ request.params[self._page_size_param] = PAGE_SIZErequest.params["page"] = self._pagedef update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:@@ -82,20 +101,54 @@ class PaystackPaginator(BasePaginator):self._has_next_page = True+def _build_paginator(config: PaystackEndpointConfig) -> BasePaginator:+ if config.cursor_paginated:+ return JSONResponseCursorPaginator(cursor_path="meta.next", cursor_param="cursor")+ return PaystackPaginator(page_size_param=config.page_size_param)++def get_resource(name: str) -> EndpointResource:config = PAYSTACK_ENDPOINTS[name]- return {+ endpoint: Endpoint = {+ "data_selector": "data",+ "path": config.path,+ "paginator": _build_paginator(config),+ }+ resource: EndpointResource = {"name": name,"table_name": name.lower(),# Full refresh: Paystack offers no verified server-side updated-at filter, so we replace# the table each sync rather than risk a corrupt incremental watermark."write_disposition": "replace",- "endpoint": {- "data_selector": "data",- "path": config.path,- },+ "endpoint": endpoint,"table_format": "delta",}+ if config.fanout is not None:+ endpoint["params"] = {+ config.fanout.resolve_param: {+ "type": "resolve",+ "resource": config.fanout.parent_name,+ "field": config.fanout.resolve_field,+ }+ }+ resource["include_from_parent"] = config.fanout.include_from_parent+ return resource+++def _to_paginator_state(config: PaystackEndpointConfig, resume: PaystackResumeConfig) -> Optional[dict[str, Any]]:+ if config.fanout is not None:+ return resume.fanout_state+ if config.cursor_paginated:+ return {"cursor": resume.next_cursor} if resume.next_cursor else None+ return {"next_page": resume.next_page} if resume.next_page else None+++def _to_resume_config(config: PaystackEndpointConfig, state: dict[str, Any]) -> Optional[PaystackResumeConfig]:+ if config.fanout is not None:+ return PaystackResumeConfig(fanout_state=state)+ if config.cursor_paginated:+ return PaystackResumeConfig(next_cursor=str(state["cursor"])) if state.get("cursor") else None+ return PaystackResumeConfig(next_page=int(state["next_page"])) if state.get("next_page") else Nonedef paystack_source(@@ -104,7 +157,12 @@ def paystack_source(team_id: int,job_id: str,resumable_source_manager: ResumableSourceManager[PaystackResumeConfig],-):+) -> Resource:+ endpoint_config = PAYSTACK_ENDPOINTS[endpoint]+ resources: list[str | EndpointResource] = [get_resource(endpoint)]+ if endpoint_config.fanout is not None:+ resources.insert(0, get_resource(endpoint_config.fanout.parent_name))+config: RESTAPIConfig = {"client": {"base_url": PAYSTACK_BASE_URL,@@ -112,34 +170,50 @@ def paystack_source("type": "bearer","token": secret_api_key,},- "paginator": PaystackPaginator(),},"resource_defaults": {"write_disposition": "replace",},- "resources": [get_resource(endpoint)],+ "resources": resources,}initial_paginator_state: Optional[dict[str, Any]] = Noneif resumable_source_manager.can_resume():resume_config = resumable_source_manager.load_state()if resume_config is not None:- initial_paginator_state = {"next_page": resume_config.next_page}+ initial_paginator_state = _to_paginator_state(endpoint_config, resume_config)def save_checkpoint(state: Optional[dict[str, Any]]) -> None:# Persist only when there's a next page to resume to; the Redis TTL handles cleanup.- if state and state.get("next_page"):- resumable_source_manager.save_state(PaystackResumeConfig(next_page=int(state["next_page"])))-- return rest_api_resource(- config,- team_id,- job_id,- # Full refresh — no incremental cursor.- None,- resume_hook=save_checkpoint,- initial_paginator_state=initial_paginator_state,+ resume_config = _to_resume_config(endpoint_config, state) if state else None+ if resume_config is not None:+ resumable_source_manager.save_state(resume_config)++ if endpoint_config.fanout is None:+ return rest_api_resource(+ config,+ team_id,+ job_id,+ # Full refresh — no incremental cursor.+ None,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )++ fanout = endpoint_config.fanout+ child = next(+ r+ for r in rest_api_resources(+ config,+ team_id,+ job_id,+ None,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )+ if r.name == endpoint)+ return child.add_map(rename_parent_fields(fanout.parent_name, fanout.parent_field_renames))def validate_credentials(secret_api_key: str) -> bool:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/paystack/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/paystack/settings.pyindex 9722890112ca..20a7e47c0d16 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/paystack/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/paystack/settings.py@@ -1,12 +1,23 @@-from dataclasses import dataclass+from dataclasses import dataclass, field+from typing import Optional+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ DependentEndpointConfig,+)-@dataclass++@dataclass(frozen=True)class PaystackEndpointConfig:# API path relative to https://api.paystack.co (e.g. "/transaction").path: str# Paystack list resources expose a globally-unique integer `id`, unique across the account.- primary_key: str = "id"+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Most list endpoints take `perPage`; a few newer ones document `per_page` instead.+ page_size_param: str = "perPage"+ # Paged by an opaque `meta.next` cursor instead of `page` / `perPage`.+ cursor_paginated: bool = False+ # Set for resources only listed per parent row; the parent is re-listed each sync.+ fanout: Optional[DependentEndpointConfig] = None# Paystack list endpoints. Each returns a `{"status", "message", "data": [...], "meta": {...}}`@@ -32,6 +43,25 @@ PAYSTACK_ENDPOINTS: dict[str, PaystackEndpointConfig] = {"Disputes": PaystackEndpointConfig(path="/dispute"),"Subaccounts": PaystackEndpointConfig(path="/subaccount"),"PaymentPages": PaystackEndpointConfig(path="/page"),+ "TransactionSplits": PaystackEndpointConfig(path="/split", page_size_param="per_page"),+ "BalanceLedger": PaystackEndpointConfig(path="/balance/ledger"),+ "SettlementTransactions": PaystackEndpointConfig(+ path="/settlement/{settlement_id}/transactions",+ # A transaction id is unique on its own, but the key is scoped to the settlement so the+ # table stays unique even if Paystack ever lists one transaction under two settlements.+ primary_keys=["settlement_id", "id"],+ fanout=DependentEndpointConfig(+ parent_name="Settlements",+ resolve_param="settlement_id",+ resolve_field="id",+ include_from_parent=["id"],+ parent_field_renames={"id": "settlement_id"},+ ),+ ),+ # The page size is left at Paystack's default because the endpoint documents no maximum.+ "DirectDebitMandateAuthorizations": PaystackEndpointConfig(+ path="/directdebit/mandate-authorizations", cursor_paginated=True+ ),}ENDPOINTS = tuple(PAYSTACK_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/paystack/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/paystack/source.pyindex 0cb34d6da6e4..86095547321c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/paystack/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/paystack/source.py@@ -146,6 +146,6 @@ You can find your secret key (it starts with `sk_live_` or `sk_test_`) under **Sreturn SourceResponse(name=resource.name,items=lambda: resource,- primary_keys=[PAYSTACK_ENDPOINTS[inputs.schema_name].primary_key],+ primary_keys=PAYSTACK_ENDPOINTS[inputs.schema_name].primary_keys,column_hints=resource.column_hints,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/paystack/tests/test_paystack.py b/products/warehouse_sources/backend/temporal/data_imports/sources/paystack/tests/test_paystack.pyindex 500a24229ccb..6c0cb576932c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/paystack/tests/test_paystack.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/paystack/tests/test_paystack.py@@ -1,6 +1,8 @@import jsonfrom typing import Any+import pytest+from requests import Responsefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (@@ -32,6 +34,11 @@ def _response(body: dict[str, Any], status_code: int = 200) -> Response:return resp+_MID_SETTLEMENT_STATE = PaystackResumeConfig(+ fanout_state={"completed": [], "current": "/settlement/11/transactions", "child_state": {"next_page": 2}}+)++class TestPaystackPaginator:def test_update_state_stops_on_empty_page_without_meta(self) -> None:# No usable meta: fall back to Paystack's documented "stop when a page is empty" signal.@@ -62,17 +69,23 @@ class TestPaystackSourceResumeBehavior:def _driver() -> SourceDriver:return SourceDriver(PaystackSource(), PaystackSourceConfig(secret_api_key="sk_test_x"))- def test_fresh_run_saves_next_page_after_each_non_terminal_page(self) -> None:+ @pytest.mark.parametrize(+ "schema_name, page_size_param",+ [("Transactions", "perPage"), ("TransactionSplits", "per_page")],+ )+ def test_fresh_run_saves_next_page_after_each_non_terminal_page(+ self, schema_name: str, page_size_param: str+ ) -> None:responses = [ScriptedResponse(json={"data": [{"id": 1}], "meta": _meta(page=1, page_count=3)}),ScriptedResponse(json={"data": [{"id": 2}], "meta": _meta(page=2, page_count=3)}),ScriptedResponse(json={"data": [{"id": 3}], "meta": _meta(page=3, page_count=3)}),]- result = self._driver().run("Transactions", responses)+ result = self._driver().run(schema_name, responses)assert result.raised is Noneassert result.params("page") == ["1", "2", "3"]- assert result.params("perPage") == ["100", "100", "100"]+ assert result.params(page_size_param) == ["100", "100", "100"]assert result.rows == [{"id": 1}, {"id": 2}, {"id": 3}]assert result.saved_states == [PaystackResumeConfig(next_page=2), PaystackResumeConfig(next_page=3)]@@ -95,3 +108,67 @@ class TestPaystackSourceResumeBehavior:assert result.raised is Noneassert result.params("page") == ["1"]assert result.rows == [{"id": 1}]++ def test_mandate_authorizations_follow_meta_next_cursor(self) -> None:+ responses = [+ ScriptedResponse(json={"data": [{"id": 1}], "meta": {"per_page": 50, "next": "c2", "count": 1}}),+ ScriptedResponse(json={"data": [{"id": 2}], "meta": {"per_page": 50, "next": None, "count": 1}}),+ ]+ result = self._driver().run("DirectDebitMandateAuthorizations", responses)++ assert result.raised is None+ assert result.paths == ["/directdebit/mandate-authorizations"] * 2+ assert result.params("cursor") == [None, "c2"]+ assert result.params("page") == [None, None]+ assert result.rows == [{"id": 1}, {"id": 2}]+ assert result.saved_states == [PaystackResumeConfig(next_cursor="c2")]++ def test_mandate_authorizations_resume_from_saved_cursor(self) -> None:+ result = self._driver().run(+ "DirectDebitMandateAuthorizations",+ [ScriptedResponse(json={"data": [{"id": 2}], "meta": {"per_page": 50, "next": None, "count": 1}})],+ resume_state=PaystackResumeConfig(next_cursor="c2"),+ )++ assert result.raised is None+ assert result.params("cursor") == ["c2"]+ assert result.rows == [{"id": 2}]++ def test_settlement_transactions_fan_out_per_settlement(self) -> None:+ responses = [+ ScriptedResponse(json={"data": [{"id": 11}, {"id": 12}], "meta": _meta(page=1, page_count=1)}),+ ScriptedResponse(json={"data": [{"id": 1}], "meta": _meta(page=1, page_count=2)}),+ ScriptedResponse(json={"data": [{"id": 2}], "meta": _meta(page=2, page_count=2)}),+ ScriptedResponse(json={"data": [{"id": 3}], "meta": _meta(page=1, page_count=1)}),+ ]+ result = self._driver().run("SettlementTransactions", responses)++ assert result.raised is None+ assert result.paths == [+ "/settlement",+ "/settlement/11/transactions",+ "/settlement/11/transactions",+ "/settlement/12/transactions",+ ]+ assert result.params("page") == ["1", "1", "2", "1"]+ assert result.rows == [+ {"id": 1, "settlement_id": 11},+ {"id": 2, "settlement_id": 11},+ {"id": 3, "settlement_id": 12},+ ]+ assert result.response is not None+ assert result.response.primary_keys == ["settlement_id", "id"]+ assert result.saved_states[0] == _MID_SETTLEMENT_STATE++ def test_settlement_transactions_resume_mid_settlement(self) -> None:+ responses = [+ ScriptedResponse(json={"data": [{"id": 11}, {"id": 12}], "meta": _meta(page=1, page_count=1)}),+ ScriptedResponse(json={"data": [{"id": 2}], "meta": _meta(page=2, page_count=2)}),+ ScriptedResponse(json={"data": [{"id": 3}], "meta": _meta(page=1, page_count=1)}),+ ]+ result = self._driver().run("SettlementTransactions", responses, resume_state=_MID_SETTLEMENT_STATE)++ assert result.raised is None+ assert result.paths == ["/settlement", "/settlement/11/transactions", "/settlement/12/transactions"]+ assert result.params("page") == ["1", "2", "1"]+ assert result.rows == [{"id": 2, "settlement_id": 11}, {"id": 3, "settlement_id": 12}]