: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 Opn Payments import source (#84425)
Tom Owers008d7c8a6c46
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/opnpayments.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/opnpayments.pyindex 6423a787319d..2ccd0d56ade5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/opnpayments.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/opnpayments.py@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass OpnPaymentsSourceConfig(config.Config):- pass+ secret_key: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/opn_payments/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/opn_payments/canonical_descriptions.pynew file mode 100644index 000000000000..86a0cf1782af--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/opn_payments/canonical_descriptions.py@@ -0,0 +1,141 @@+"""Canonical, documentation-sourced descriptions for Opn Payments (Omise) endpoints and columns.++Sourced from the official Omise API reference (https://docs.omise.co/). Keyed by the resource names+in `settings.py` `ENDPOINTS`, which match the `ExternalDataSchema.name` of a synced table. Columns+absent here fall back to LLM enrichment.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Fields shared by every Omise object; merged into each entry so we don't repeat them.+_COMMON_COLUMNS = {+ "object": "String identifying the object's Omise type (e.g. 'charge', 'customer').",+ "id": "Unique identifier for the object.",+ "livemode": "Whether the object was created with a live (as opposed to test) secret key.",+ "location": "API path used to retrieve the object.",+ "created_at": "UTC datetime the object was created, in ISO 8601 format.",+ "metadata": "Custom key-value data attached to the object.",+}+++def _columns(**overrides: str) -> dict[str, str]:+ return {**_COMMON_COLUMNS, **overrides}+++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "Charges": {+ "description": "A single attempt to charge a customer's card or other payment source.",+ "docs_url": "https://docs.omise.co/charges-api",+ "columns": _columns(+ amount="Amount charged, in the smallest unit of the currency (e.g. satang for THB).",+ currency="Three-letter ISO 4217 currency code of the charge.",+ status="Status of the charge: successful, failed, pending, expired, or reversed.",+ paid="Whether the charge has been successfully paid.",+ paid_at="UTC datetime the charge was paid, in ISO 8601 format.",+ captured="Whether the charge has been captured.",+ capturable="Whether the charge can currently be captured.",+ authorized="Whether the charge has been authorized.",+ reversed="Whether the charge has been reversed.",+ refunded_amount="Total amount refunded on this charge, in the smallest currency unit.",+ refundable="Whether the charge can still be refunded.",+ disputable="Whether the charge can be disputed.",+ customer="ID of the customer the charge belongs to, if any.",+ card="Card object used for the charge, if any.",+ description="Free-form description of the charge.",+ failure_code="Machine-readable reason the charge failed, if it did.",+ failure_message="Human-readable reason the charge failed, if it did.",+ fee="Omise's fee for the charge, in the smallest currency unit.",+ net="Net amount received after fees, in the smallest currency unit.",+ expired="Whether the charge has expired.",+ expires_at="UTC datetime the charge expires, in ISO 8601 format.",+ return_uri="URL the customer is redirected back to after an off-site payment flow.",+ ),+ },+ "Customers": {+ "description": "A customer record that can store cards and be charged repeatedly.",+ "docs_url": "https://docs.omise.co/customers-api",+ "columns": _columns(+ email="Customer's email address.",+ description="Free-form description of the customer.",+ default_card="ID of the customer's default card.",+ cards="List of cards stored for the customer.",+ deleted="Whether the customer record has been deleted.",+ ),+ },+ "Disputes": {+ "description": "A chargeback dispute raised against one of your charges.",+ "docs_url": "https://docs.omise.co/disputes-api",+ "columns": _columns(+ amount="Disputed amount, in the smallest currency unit.",+ currency="Three-letter ISO 4217 currency code of the dispute.",+ status="Status of the dispute: open, pending, won, or lost.",+ reason_code="Machine-readable reason code for the dispute.",+ reason_message="Human-readable reason for the dispute.",+ charge="ID of the charge being disputed.",+ closed_at="UTC datetime the dispute was closed, in ISO 8601 format, if closed.",+ ),+ },+ "Events": {+ "description": "A record of a change in your Opn Payments account (e.g. charge.create).",+ "docs_url": "https://docs.omise.co/events-api",+ "columns": _columns(+ key="Type of the event, e.g. 'charge.create' or 'refund.create'.",+ data="Snapshot of the object affected by the event.",+ ),+ },+ "Recipients": {+ "description": "A bank account recipient that transfers can be sent to.",+ "docs_url": "https://docs.omise.co/recipients-api",+ "columns": _columns(+ name="Recipient's name.",+ email="Recipient's email address.",+ type="Type of recipient: individual or corporation.",+ active="Whether the recipient can currently receive transfers.",+ verified="Whether the recipient's bank account has been verified.",+ verified_at="UTC datetime the recipient was verified, in ISO 8601 format, if verified.",+ bank_account="Bank account details for the recipient.",+ failure_code="Reason the recipient failed verification, if it did.",+ ),+ },+ "Refunds": {+ "description": "A refund of all or part of a charge back to the original payment source.",+ "docs_url": "https://docs.omise.co/refunds-api",+ "columns": _columns(+ amount="Amount refunded, in the smallest currency unit.",+ currency="Three-letter ISO 4217 currency code of the refund.",+ charge="ID of the charge being refunded.",+ status="Status of the refund: closed, pending, or failed.",+ voided="Whether the refund has been voided.",+ ),+ },+ "Transactions": {+ "description": "A ledger entry recording money moving in or out of your Opn Payments balance.",+ "docs_url": "https://docs.omise.co/transactions-api",+ "columns": _columns(+ amount="Amount of the transaction, in the smallest currency unit.",+ currency="Three-letter ISO 4217 currency code of the transaction.",+ direction="Direction of the money movement: credit or debit.",+ key="Type of the underlying event that produced the transaction.",+ origin="ID of the object (charge, transfer, etc.) that produced the transaction.",+ transferable_at="UTC datetime the transaction amount becomes transferable, in ISO 8601 format.",+ ),+ },+ "Transfers": {+ "description": "A transfer of your Opn Payments balance to a bank account.",+ "docs_url": "https://docs.omise.co/transfers-api",+ "columns": _columns(+ amount="Amount transferred, in the smallest currency unit.",+ currency="Three-letter ISO 4217 currency code of the transfer.",+ fee="Omise's fee for the transfer, in the smallest currency unit.",+ net="Net amount transferred after fees, in the smallest currency unit.",+ paid="Whether the transfer has been paid out.",+ paid_at="UTC datetime the transfer was paid, in ISO 8601 format, if paid.",+ sent="Whether the transfer has been sent to the bank.",+ sent_at="UTC datetime the transfer was sent, in ISO 8601 format, if sent.",+ recipient="ID of the recipient the transfer was sent to, if any.",+ failure_code="Reason the transfer failed, if it did.",+ ),+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/opn_payments/opn_payments.py b/products/warehouse_sources/backend/temporal/data_imports/sources/opn_payments/opn_payments.pynew file mode 100644index 000000000000..b031778b831f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/opn_payments/opn_payments.py@@ -0,0 +1,146 @@+from datetime import UTC, date, datetime+from typing import Any, Optional, cast++from requests.auth import HTTPBasicAuth++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ OffsetPaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import EndpointResource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.opn_payments.settings import (+ BASE_URL,+ OPN_PAYMENTS_ENDPOINTS,+ PAGE_SIZE,+ PARTITION_KEY,+)+++@frozen+class OpnPaymentsResumeConfig:+ offset: int+++def _to_iso8601(value: Any) -> Any:+ """Format a stored watermark as the UTC ISO 8601 string Opn Payments' `from` filter takes."""+ if isinstance(value, datetime):+ dt = value if value.tzinfo else value.replace(tzinfo=UTC)+ return dt.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+ if isinstance(value, date):+ return datetime(value.year, value.month, value.day, tzinfo=UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+ return value+++def validate_credentials(secret_key: str, api_version: str) -> tuple[bool, str | None]:+ """Probe the cheapest authenticated endpoint Opn Payments offers: the single account object."""+ ok, status = validate_via_probe(+ lambda: make_tracked_session(headers={"Omise-Version": api_version}, redact_values=(secret_key,)),+ f"{BASE_URL}/account",+ auth=HTTPBasicAuth(secret_key, ""),+ )+ if ok:+ return True, None+ if status == 401:+ return False, "Your Opn Payments secret key is invalid. Check the key and try again."+ if status is None:+ return False, "Could not reach the Opn Payments API."+ return False, f"Opn Payments API returned status {status}."+++def opn_payments_source(+ secret_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[OpnPaymentsResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ api_version: str = "2019-05-29",+) -> SourceResponse:+ endpoint_config = OPN_PAYMENTS_ENDPOINTS[endpoint]++ params: dict[str, Any] = {+ "limit": PAGE_SIZE,+ # Omise defaults list endpoints to chronological order already; pin it explicitly so+ # `SourceResponse.sort_mode="asc"` below always matches the order rows actually arrive in.+ "order": "chronological",+ }+ if should_use_incremental_field:+ params["from"] = {+ "type": "incremental",+ "cursor_path": "created_at",+ "initial_value": "1970-01-01T00:00:00Z",+ "convert": _to_iso8601,+ }++ rest_config: RESTAPIConfig = {+ "client": {+ "base_url": BASE_URL,+ "headers": {"Omise-Version": api_version},+ "auth": {"type": "http_basic", "username": secret_key, "password": ""},+ # `total` (the paginator's default `total_path`) bounds pagination to the+ # (possibly `from`-filtered) matching record count, so a merchant's whole history+ # is never re-walked once the incremental watermark has advanced.+ "paginator": OffsetPaginator(limit=PAGE_SIZE),+ },+ "resources": [+ cast(+ EndpointResource,+ {+ "name": endpoint,+ "table_name": endpoint_config.table_name,+ "write_disposition": {"disposition": "merge", "strategy": "upsert"}+ if should_use_incremental_field+ else "replace",+ "table_format": "delta",+ "endpoint": {+ "path": endpoint_config.path,+ "params": params,+ "data_selector": "data",+ },+ },+ )+ ],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume = resumable_source_manager.load_state()+ if resume is not None:+ initial_paginator_state = {"offset": resume.offset}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Persist only while a next page remains; saved AFTER a page is yielded so a crash+ # re-yields (merge dedupes on `id`) rather than skipping a page.+ if state and state.get("offset") is not None:+ resumable_source_manager.save_state(OpnPaymentsResumeConfig(offset=int(state["offset"])))++ resource = rest_api_resource(+ rest_config,+ team_id,+ job_id,+ db_incremental_field_last_value if should_use_incremental_field else None,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )++ return SourceResponse(+ name=endpoint,+ items=lambda: resource,+ primary_keys=["id"],+ sort_mode="asc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime",+ partition_format="month",+ partition_keys=[PARTITION_KEY],+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/opn_payments/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/opn_payments/settings.pynew file mode 100644index 000000000000..f80a8f1a9fd6--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/opn_payments/settings.py@@ -0,0 +1,48 @@+from dataclasses import dataclass++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++BASE_URL = "https://api.omise.co"++# Documented default and maximum page size for every list endpoint.+PAGE_SIZE = 100++# Latest Omise-Version header value (see https://docs.omise.co/api-versioning).+API_VERSION = "2019-05-29"+++@dataclass(frozen=True)+class OpnPaymentsEndpointConfig:+ path: str+ table_name: str+++# Every top-level list endpoint shares the same offset/limit/from/to pagination and documents+# `created_at` as the row-creation timestamp, which never changes afterwards — it doubles as the+# incremental cursor and the partition key for all of them.+OPN_PAYMENTS_ENDPOINTS: dict[str, OpnPaymentsEndpointConfig] = {+ "Charges": OpnPaymentsEndpointConfig(path="/charges", table_name="charges"),+ "Customers": OpnPaymentsEndpointConfig(path="/customers", table_name="customers"),+ "Disputes": OpnPaymentsEndpointConfig(path="/disputes", table_name="disputes"),+ "Events": OpnPaymentsEndpointConfig(path="/events", table_name="events"),+ "Recipients": OpnPaymentsEndpointConfig(path="/recipients", table_name="recipients"),+ "Refunds": OpnPaymentsEndpointConfig(path="/refunds", table_name="refunds"),+ "Transactions": OpnPaymentsEndpointConfig(path="/transactions", table_name="transactions"),+ "Transfers": OpnPaymentsEndpointConfig(path="/transfers", table_name="transfers"),+}++ENDPOINTS = tuple(OPN_PAYMENTS_ENDPOINTS.keys())++PARTITION_KEY = "created_at"+++def _created_at_field() -> IncrementalField:+ return {+ "label": "created_at",+ "type": IncrementalFieldType.DateTime,+ "field": "created_at",+ "field_type": IncrementalFieldType.DateTime,+ }+++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: [_created_at_field()] for name in ENDPOINTS}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/opn_payments/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/opn_payments/source.pyindex 7ff52f005b62..28c27fd2d472 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/opn_payments/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/opn_payments/source.py@@ -1,32 +1,129 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.opnpayments import (OpnPaymentsSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.opn_payments.opn_payments import (+ OpnPaymentsResumeConfig,+ opn_payments_source,+ validate_credentials as validate_opn_payments_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.opn_payments.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class OpnPaymentsSource(SimpleSource[OpnPaymentsSourceConfig]):+class OpnPaymentsSource(ResumableSource[OpnPaymentsSourceConfig, OpnPaymentsResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ supported_versions = ("2019-05-29",)+ default_version = "2019-05-29"+ api_docs_url = "https://docs.omise.co/api-versioning"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.OPNPAYMENTS+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Your Opn Payments secret key is invalid. Check the key and try again.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.opn_payments.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: OpnPaymentsSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)++ def validate_credentials(+ self,+ config: OpnPaymentsSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_opn_payments_credentials(config.secret_key, self.resolve_api_version(api_version))++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[OpnPaymentsResumeConfig]:+ return ResumableSourceManager[OpnPaymentsResumeConfig](inputs, OpnPaymentsResumeConfig)++ def source_for_pipeline(+ self,+ config: OpnPaymentsSourceConfig,+ resumable_source_manager: ResumableSourceManager[OpnPaymentsResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return opn_payments_source(+ secret_key=config.secret_key,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,+ api_version=self.resolve_api_version(inputs.api_version),+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.OPN_PAYMENTS,category=DataWarehouseSourceCategory.PAYMENTS___BILLING,label="Opn Payments (formerly Omise)",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="Enter your Opn Payments (Omise) secret key to sync charges, customers, transfers, "+ "and more into the PostHog Data warehouse. Find your secret key in the Opn Payments "+ "dashboard under **Keys**.",+ docsUrl="https://posthog.com/docs/cdp/sources/opn-payments",iconPath="/static/services/opn_payments.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ keywords=["omise", "thailand"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="secret_key",+ label="Secret key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="skey_test_...",+ secret=True,+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/opn_payments/tests/test_opn_payments.py b/products/warehouse_sources/backend/temporal/data_imports/sources/opn_payments/tests/test_opn_payments.pynew file mode 100644index 000000000000..1fe286445e31--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/opn_payments/tests/test_opn_payments.py@@ -0,0 +1,300 @@+import json+from datetime import UTC, date, datetime+from typing import Any++import pytest+from unittest import mock++from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.opn_payments.opn_payments import (+ OpnPaymentsResumeConfig,+ _to_iso8601,+ opn_payments_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.opn_payments.settings import (+ ENDPOINTS,+ OPN_PAYMENTS_ENDPOINTS,+ PARTITION_KEY,+)++# The credential probe builds its own session via make_tracked_session imported into the+# opn_payments module.+SESSION_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.opn_payments.opn_payments.make_tracked_session"+)+# `opn_payments_source` leaves `client_config["session"]` unset, so `RESTClient` builds its own+# tracked session via the `make_tracked_session` imported into the rest_client module.+REST_CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+++def _response(body: dict[str, Any], status_code: int = 200) -> Response:+ resp = Response()+ resp.status_code = status_code+ resp._content = json.dumps(body).encode()+ return resp+++def _envelope(data: list[dict[str, Any]], offset: int, total: int, limit: int = 100) -> dict[str, Any]:+ return {"object": "list", "data": data, "offset": offset, "limit": limit, "total": total}+++def _page(size: int, start_id: int = 0) -> list[dict[str, Any]]:+ return [{"id": f"chrg_{start_id + i}"} for i in range(size)]+++def _make_manager(resume_state: OpnPaymentsResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:+ """Wire a mock session and capture each request's params AT PREPARE TIME.++ ``request.params`` is a single dict mutated in place across pages, so inspecting it after+ the run shows only the final state — snapshot a copy when each request is prepared instead.+ """+ session.headers = {}+ param_snapshots: list[dict[str, Any]] = []++ def _prepare(request: Any) -> mock.MagicMock:+ param_snapshots.append(dict(request.params or {}))+ return mock.MagicMock()++ session.prepare_request.side_effect = _prepare+ session.send.side_effect = responses+ return param_snapshots+++def _source(endpoint: str, manager: mock.MagicMock | None = None, **kwargs: Any):+ return opn_payments_source(+ "skey_test_123",+ endpoint,+ team_id=1,+ job_id="job",+ resumable_source_manager=manager or _make_manager(),+ **kwargs,+ )+++def _rows(source_response) -> list[dict[str, Any]]:+ return [row for page in source_response.items() for row in page]+++class TestToIso8601:+ @pytest.mark.parametrize(+ "value, expected",+ [+ (datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14Z"),+ (datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14Z"),+ (date(2026, 3, 4), "2026-03-04T00:00:00Z"),+ ("1970-01-01T00:00:00Z", "1970-01-01T00:00:00Z"),+ ],+ )+ def test_format(self, value, expected):+ assert _to_iso8601(value) == expected+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ "status_code, expected_valid, expected_message",+ [+ (200, True, None),+ (401, False, "Your Opn Payments secret key is invalid. Check the key and try again."),+ (500, False, "Opn Payments API returned status 500."),+ ],+ )+ @mock.patch(SESSION_PATCH)+ def test_status_mapping(self, mock_session, status_code, expected_valid, expected_message):+ mock_session.return_value.get.return_value = _response({}, status_code=status_code)++ valid, message = validate_credentials("skey_test_123", "2019-05-29")++ assert valid is expected_valid+ assert message == expected_message++ @mock.patch(SESSION_PATCH)+ def test_probes_account_endpoint_with_basic_auth_and_version_header(self, mock_session):+ mock_session.return_value.get.return_value = _response({}, status_code=200)++ validate_credentials("skey_test_123", "2019-05-29")++ get_call = mock_session.return_value.get.call_args+ assert get_call.args[0] == "https://api.omise.co/account"+ assert get_call.kwargs["auth"].username == "skey_test_123"+ assert get_call.kwargs["auth"].password == ""+ assert mock_session.call_args.kwargs["headers"]["Omise-Version"] == "2019-05-29"+ assert "skey_test_123" in mock_session.call_args.kwargs["redact_values"]++ @mock.patch(SESSION_PATCH)+ def test_swallows_request_exceptions(self, mock_session):+ mock_session.return_value.get.side_effect = ConnectionError("boom")++ valid, message = validate_credentials("skey_test_123", "2019-05-29")++ assert valid is False+ assert message == "Could not reach the Opn Payments API."+++class TestOpnPaymentsSourcePagination:+ @mock.patch(REST_CLIENT_SESSION_PATCH)+ def test_walks_full_pages_by_offset_until_a_short_page(self, MockSession):+ session = MockSession.return_value+ params = _wire(+ session,+ [+ _response(_envelope(_page(100), offset=0, total=150)),+ _response(_envelope(_page(50, start_id=100), offset=100, total=150)),+ ],+ )++ rows = _rows(_source("Charges"))++ assert len(rows) == 150+ assert params[0]["offset"] == 0+ assert params[0]["limit"] == 100+ assert params[1]["offset"] == 100++ @mock.patch(REST_CLIENT_SESSION_PATCH)+ def test_stops_at_total_even_when_last_page_is_full(self, MockSession):+ # A full (100-item) page whose offset+limit already reaches `total` must not fetch a+ # further (empty) page just to discover the end — the total-based check catches it first.+ session = MockSession.return_value+ _wire(session, [_response(_envelope(_page(100), offset=0, total=100))])++ rows = _rows(_source("Charges"))++ assert len(rows) == 100+ assert session.send.call_count == 1++ @mock.patch(REST_CLIENT_SESSION_PATCH)+ def test_stops_on_short_page_even_without_total(self, MockSession):+ session = MockSession.return_value+ _wire(session, [_response({"object": "list", "data": [{"id": "a"}]})])++ rows = _rows(_source("Customers"))++ assert [row["id"] for row in rows] == ["a"]+ # A single (short) page with no `total` field still ends pagination — no second request.+ assert session.send.call_count == 1++ @mock.patch(REST_CLIENT_SESSION_PATCH)+ def test_empty_first_page_yields_nothing(self, MockSession):+ session = MockSession.return_value+ _wire(session, [_response(_envelope([], offset=0, total=0))])++ manager = _make_manager()+ batches = list(_source("Refunds", manager).items())++ assert batches == []+ manager.save_state.assert_not_called()++ @mock.patch(REST_CLIENT_SESSION_PATCH)+ def test_always_sends_chronological_order(self, MockSession):+ session = MockSession.return_value+ params = _wire(session, [_response(_envelope([], offset=0, total=0))])++ _rows(_source("Transfers"))++ assert params[0]["order"] == "chronological"++ @mock.patch(REST_CLIENT_SESSION_PATCH)+ def test_omise_version_header_sent(self, MockSession):+ session = MockSession.return_value+ _wire(session, [_response(_envelope([], offset=0, total=0))])++ list(_source("Transfers", api_version="2017-11-02").items())++ # The version header is applied onto the session after it's built, not passed to+ # make_tracked_session itself — see RESTClient.__init__'s `session.headers.update(...)`.+ assert session.headers["Omise-Version"] == "2017-11-02"+++class TestOpnPaymentsSourceIncremental:+ @mock.patch(REST_CLIENT_SESSION_PATCH)+ def test_incremental_sends_converted_from_filter(self, MockSession):+ session = MockSession.return_value+ params = _wire(session, [_response(_envelope([{"id": "chrg_1"}], offset=0, total=1))])++ _rows(+ _source(+ "Charges",+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),+ )+ )++ assert params[0]["from"] == "2026-01-01T00:00:00Z"++ @mock.patch(REST_CLIENT_SESSION_PATCH)+ def test_full_refresh_never_sends_from_filter(self, MockSession):+ session = MockSession.return_value+ params = _wire(session, [_response(_envelope([{"id": "chrg_1"}], offset=0, total=1))])++ _rows(+ _source(+ "Charges",+ should_use_incremental_field=False,+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),+ )+ )++ assert "from" not in params[0]++ @mock.patch(REST_CLIENT_SESSION_PATCH)+ def test_incremental_defaults_to_epoch_on_first_sync(self, MockSession):+ session = MockSession.return_value+ params = _wire(session, [_response(_envelope([], offset=0, total=0))])++ _rows(_source("Charges", should_use_incremental_field=True, db_incremental_field_last_value=None))++ assert params[0]["from"] == "1970-01-01T00:00:00Z"+++class TestOpnPaymentsSourceResume:+ @mock.patch(REST_CLIENT_SESSION_PATCH)+ def test_saves_offset_after_each_yielded_page(self, MockSession):+ session = MockSession.return_value+ _wire(+ session,+ [+ _response(_envelope(_page(100), offset=0, total=250)),+ _response(_envelope(_page(100, start_id=100), offset=100, total=250)),+ _response(_envelope(_page(50, start_id=200), offset=200, total=250)),+ ],+ )++ manager = _make_manager()+ _rows(_source("Charges", manager))++ saved = [call.args[0].offset for call in manager.save_state.call_args_list]+ # Checkpoints point at the next unfetched offset; the terminal page saves nothing further.+ assert saved == [100, 200]++ @mock.patch(REST_CLIENT_SESSION_PATCH)+ def test_resumes_from_saved_offset(self, MockSession):+ session = MockSession.return_value+ params = _wire(session, [_response(_envelope([{"id": "9"}], offset=200, total=201))])++ _rows(_source("Charges", _make_manager(OpnPaymentsResumeConfig(offset=200))))++ assert params[0]["offset"] == 200+++class TestOpnPaymentsSourceResponse:+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_response_metadata_per_endpoint(self, endpoint):+ response = _source(endpoint)++ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ assert response.sort_mode == "asc"+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [PARTITION_KEY]++ @pytest.mark.parametrize("endpoint, config", list(OPN_PAYMENTS_ENDPOINTS.items()))+ def test_endpoints_use_documented_paths(self, endpoint, config):+ assert config.path == f"/{config.table_name}"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/opn_payments/tests/test_opn_payments_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/opn_payments/tests/test_opn_payments_source.pynew file mode 100644index 000000000000..8dd605c508af--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/opn_payments/tests/test_opn_payments_source.py@@ -0,0 +1,165 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.opnpayments import (+ OpnPaymentsSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.opn_payments.opn_payments import (+ OpnPaymentsResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.opn_payments.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.opn_payments.source import OpnPaymentsSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestOpnPaymentsSource:+ def setup_method(self):+ self.source = OpnPaymentsSource()+ self.team_id = 123+ self.config = OpnPaymentsSourceConfig(secret_key="skey_test_123")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.OPNPAYMENTS++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "OpnPayments"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert not config.unreleasedSource+ assert config.iconPath == "/static/services/opn_payments.png"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["secret_key"]++ def test_secret_key_field_is_secret_password(self):+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "secret_key")+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_lists_tables_without_credentials(self):+ assert self.source.lists_tables_without_credentials is True++ def test_default_api_version_is_supported_and_not_deprecated(self):+ assert self.source.default_version in self.source.supported_versions+ assert self.source.get_version_deprecation(self.source.default_version) is None++ def test_get_schemas(self):+ schemas = self.source.get_schemas(self.config, self.team_id)++ assert {schema.name for schema in schemas} == set(ENDPOINTS)+ assert all(schema.supports_incremental for schema in schemas)++ def test_incremental_schemas_advertise_their_fields(self):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ for name in ENDPOINTS:+ assert schemas[name].incremental_fields == INCREMENTAL_FIELDS[name]++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["Charges"])+ assert len(schemas) == 1+ assert schemas[0].name == "Charges"++ def test_get_schemas_filtered_unknown_name_returns_empty(self):+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://api.omise.co/charges",+ ],+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable_errors)++ @pytest.mark.parametrize(+ "other_error",+ [+ "500 Server Error for url: https://api.omise.co/charges",+ "429 Client Error: Too Many Requests",+ ],+ )+ def test_non_retryable_errors_does_not_match_transient(self, other_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable_errors)++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.opn_payments.source.validate_opn_payments_credentials"+ )+ def test_validate_credentials_resolves_pinned_version(self, mock_validate):+ mock_validate.return_value = (True, None)++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id, api_version="2019-05-29")++ assert is_valid is True+ assert error_message is None+ mock_validate.assert_called_once_with("skey_test_123", "2019-05-29")++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.opn_payments.source.validate_opn_payments_credentials"+ )+ def test_validate_credentials_falls_back_to_default_version(self, mock_validate):+ mock_validate.return_value = (False, "Your Opn Payments secret key is invalid. Check the key and try again.")++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is False+ assert error_message == "Your Opn Payments secret key is invalid. Check the key and try again."+ mock_validate.assert_called_once_with("skey_test_123", "2019-05-29")++ def test_get_resumable_source_manager_binds_resume_config(self):+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is OpnPaymentsResumeConfig++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.opn_payments.source.opn_payments_source"+ )+ def test_source_for_pipeline_plumbs_arguments(self, mock_opn_payments_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "Charges"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"+ inputs.team_id = 777+ inputs.job_id = "job-1"+ inputs.api_version = None+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_opn_payments_source.assert_called_once()+ kwargs = mock_opn_payments_source.call_args.kwargs+ assert kwargs["secret_key"] == "skey_test_123"+ assert kwargs["endpoint"] == "Charges"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["team_id"] == 777+ assert kwargs["job_id"] == "job-1"+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"+ assert kwargs["api_version"] == "2019-05-29"++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.opn_payments.source.opn_payments_source"+ )+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_opn_payments_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "Customers"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"+ inputs.api_version = None++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_opn_payments_source.call_args.kwargs["db_incremental_field_last_value"] is None