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 Flutterwave source (#77135)

Tom Owers030972a8c1b4
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 2185dfae53bf..092d1a63e54f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -266,6 +266,7 @@ the row lists both.
| flexmail | HTTP | requests | ✅ |
| float_app | HTTP | requests | ✅ |
| flowlu | HTTP | requests | ✅ |
+| flutterwave | HTTP | requests + `rest_source.RESTClient` | ✅ |
| fly_io | HTTP | requests | ✅ |
| formbricks | HTTP | requests | ✅ |
| fred | HTTP | requests | ✅ |
@@ -954,7 +955,6 @@ doesn't conflict with concurrent PRs.
- flexmail
- flexport
- flowlu
-- flutterwave
- fly_io
- formbricks
- fortnox
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/flutterwave/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/flutterwave/canonical_descriptions.py
new file mode 100644
index 000000000000..08f51dd6b628
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/flutterwave/canonical_descriptions.py
@@ -0,0 +1,176 @@
+"""Canonical, documentation-sourced descriptions for Flutterwave v3 endpoints and columns.
+
+Sourced from the official Flutterwave v3 API reference (https://developer.flutterwave.com/v3.0.0/reference).
+Keyed by the endpoint names in `settings.py` `FLUTTERWAVE_ENDPOINTS`, which match the
+`ExternalDataSchema.name` of a synced Flutterwave table. Columns absent here fall back to LLM enrichment.
+"""
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+_V3_REFERENCE = "https://developer.flutterwave.com/v3.0.0/reference"
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "transactions": {
+ "description": "A payment collected on the Flutterwave account, one row per charge attempt across every payment method (card, bank transfer, mobile money, USSD).",
+ "docs_url": f"{_V3_REFERENCE}/get-all-transactions",
+ "columns": {
+ "id": "Flutterwave's unique identifier for the transaction.",
+ "tx_ref": "The merchant's own reference for the transaction, supplied when the payment was initiated.",
+ "flw_ref": "Flutterwave's reference for the transaction, used when contacting support.",
+ "amount": "Amount the customer was asked to pay, in the transaction currency.",
+ "charged_amount": "Amount actually charged to the customer, including Flutterwave's fee where the merchant passes it on.",
+ "app_fee": "Flutterwave's fee for processing the transaction.",
+ "merchant_fee": "Additional fee the merchant added on top of the transaction.",
+ "amount_settled": "Amount due to the merchant after fees, in the settlement currency.",
+ "currency": "ISO 4217 currency code the transaction was charged in.",
+ "status": "Outcome of the charge, one of successful, failed, or pending.",
+ "payment_type": "Payment method used, for example card, account, banktransfer, or mobilemoney.",
+ "processor_response": "Message returned by the payment processor for the charge attempt.",
+ "auth_model": "Authentication model applied to the charge, for example PIN, VBVSECURECODE, or NOAUTH.",
+ "narration": "Description shown to the customer on their statement.",
+ "ip": "IP address the payment was initiated from.",
+ "device_fingerprint": "Fingerprint of the device the payment was initiated from.",
+ "created_at": "Date and time the transaction was created, in UTC.",
+ "account_id": "Identifier of the Flutterwave merchant account the transaction belongs to.",
+ "customer": "Details of the customer who paid, including their id, name, email, and phone number.",
+ "card": "Details of the card used, where the transaction was a card payment.",
+ "meta": "Custom key/value metadata attached to the transaction when it was initiated.",
+ },
+ },
+ "settlements": {
+ "description": "A payout of collected funds from the Flutterwave balance to the merchant's settlement bank account.",
+ "docs_url": f"{_V3_REFERENCE}/get-all-settlements",
+ "columns": {
+ "id": "Unique identifier for the settlement.",
+ "account_id": "Identifier of the Flutterwave merchant account being settled.",
+ "merchant_name": "Name of the merchant the settlement was paid to.",
+ "merchant_email": "Email address on the merchant account.",
+ "currency": "ISO 4217 currency code the settlement was paid in.",
+ "gross_amount": "Total value of the transactions included in this settlement, before deductions.",
+ "app_fee": "Flutterwave's fees deducted from the gross amount.",
+ "net_amount": "Amount actually paid out to the merchant after fees and other deductions.",
+ "status": "State of the settlement, for example processed or flagged.",
+ "flag_message": "Reason the settlement was flagged, where it was held for review.",
+ "transaction_date": "Date of the transactions covered by this settlement.",
+ "created_at": "Date and time the settlement record was created, in UTC.",
+ },
+ },
+ "refunds": {
+ "description": "Money returned to a customer against a previously successful transaction.",
+ "docs_url": f"{_V3_REFERENCE}/get-all-refunds",
+ "columns": {
+ "id": "Unique identifier for the refund.",
+ "account_id": "Identifier of the Flutterwave merchant account the refund was issued from.",
+ "transaction_id": "Identifier of the transaction that was refunded.",
+ "flw_ref": "Flutterwave's reference for the refund.",
+ "amount_refunded": "Amount returned to the customer.",
+ "status": "State of the refund, for example completed or failed.",
+ "destination": "Where the refunded money was sent, for example back to the original payment method.",
+ "comment": "Note recorded against the refund when it was created.",
+ "settlement_id": "Identifier of the settlement the refund was deducted from.",
+ "meta": "Additional metadata recorded against the refund, including its funding source.",
+ "created_at": "Date and time the refund was created, in UTC.",
+ },
+ },
+ "transfers": {
+ "description": "An outbound payout initiated by the merchant to a bank account, mobile money wallet, or Flutterwave balance.",
+ "docs_url": f"{_V3_REFERENCE}/get-all-transfers",
+ "columns": {
+ "id": "Unique identifier for the transfer.",
+ "reference": "The merchant's own reference for the transfer.",
+ "account_number": "Recipient account number the money was sent to.",
+ "bank_code": "Code of the recipient's bank.",
+ "bank_name": "Name of the recipient's bank.",
+ "full_name": "Name of the recipient.",
+ "amount": "Amount sent, in the transfer currency.",
+ "fee": "Flutterwave's fee for making the transfer.",
+ "currency": "ISO 4217 currency code the recipient was paid in.",
+ "debit_currency": "ISO 4217 currency code the merchant's balance was debited in.",
+ "status": "State of the transfer, for example NEW, PENDING, SUCCESSFUL, or FAILED.",
+ "narration": "Description shown on the recipient's statement.",
+ "complete_message": "Message returned by the processor once the transfer finished.",
+ "requires_approval": "Whether the transfer needs approval before it is sent.",
+ "is_approved": "Whether an approval-gated transfer has been approved.",
+ "meta": "Custom key/value metadata attached to the transfer.",
+ "created_at": "Date and time the transfer was created, in UTC.",
+ },
+ },
+ "chargebacks": {
+ "description": "A payment dispute raised by a customer or their bank against a transaction.",
+ "docs_url": f"{_V3_REFERENCE}/list-a-chargeback",
+ "columns": {
+ "id": "Unique identifier for the chargeback.",
+ "transaction_id": "Identifier of the disputed transaction.",
+ "tx_ref": "The merchant's own reference for the disputed transaction.",
+ "flw_ref": "Flutterwave's reference for the disputed transaction.",
+ "amount": "Amount being disputed.",
+ "currency": "ISO 4217 currency code of the disputed amount.",
+ "status": "Outcome of the dispute, one of initiated, accepted, declined, won, or lost.",
+ "stage": "Stage the dispute has reached in the chargeback lifecycle.",
+ "comment": "Reason given for the dispute.",
+ "due_date": "Deadline for responding to the dispute.",
+ "meta": "Additional dispute metadata, including uploaded proof and the dispute history.",
+ "created_at": "Date and time the chargeback was raised, in UTC.",
+ },
+ },
+ "payment_plans": {
+ "description": "A recurring billing plan definition that customers can be subscribed to.",
+ "docs_url": f"{_V3_REFERENCE}/get-payment-plans",
+ "columns": {
+ "id": "Unique identifier for the payment plan.",
+ "name": "Name given to the plan.",
+ "amount": "Amount charged on each billing cycle. Zero means the amount is set per subscription.",
+ "interval": "How often the plan bills, for example daily, weekly, monthly, or yearly.",
+ "duration": "Number of billing cycles the plan runs for. Zero means it runs until cancelled.",
+ "status": "State of the plan, either active or cancelled.",
+ "currency": "ISO 4217 currency code the plan bills in.",
+ "plan_token": "Token identifying the plan when initiating a payment against it.",
+ "created_at": "Date and time the plan was created, in UTC.",
+ },
+ },
+ "subscriptions": {
+ "description": "A customer's enrolment against a payment plan, one row per subscribed customer.",
+ "docs_url": f"{_V3_REFERENCE}/get-all-subscriptions",
+ "columns": {
+ "id": "Unique identifier for the subscription.",
+ "amount": "Amount charged on each billing cycle for this subscription.",
+ "customer": "Details of the subscribed customer, including their id and email address.",
+ "plan": "Identifier of the payment plan the customer is subscribed to.",
+ "status": "State of the subscription, either active or cancelled.",
+ "created_at": "Date and time the customer subscribed, in UTC.",
+ },
+ },
+ "subaccounts": {
+ "description": "A collection subaccount used to split incoming payments with another party.",
+ "docs_url": f"{_V3_REFERENCE}/fetch-all-subaccounts",
+ "columns": {
+ "id": "Unique identifier for the subaccount.",
+ "subaccount_id": "Reference used to attach the subaccount to a payment split.",
+ "account_number": "Bank account number funds are split to.",
+ "account_bank": "Code of the bank holding the subaccount's account.",
+ "bank_name": "Name of the bank holding the subaccount's account.",
+ "business_name": "Business the subaccount belongs to.",
+ "full_name": "Name on the subaccount's bank account.",
+ "split_type": "How the split is calculated, either percentage or flat.",
+ "split_value": "Share of each payment routed to the subaccount, interpreted per split_type.",
+ "country": "ISO country code the subaccount's bank account is held in.",
+ "meta": "Custom key/value metadata attached to the subaccount.",
+ "created_at": "Date and time the subaccount was created, in UTC.",
+ },
+ },
+ "beneficiaries": {
+ "description": "A saved payout recipient that transfers can be sent to without re-entering their bank details.",
+ "docs_url": f"{_V3_REFERENCE}/list-all-beneficiaries",
+ "columns": {
+ "id": "Unique identifier for the beneficiary.",
+ "account_number": "The beneficiary's bank account number.",
+ "bank_code": "Code of the beneficiary's bank.",
+ "bank_name": "Name of the beneficiary's bank.",
+ "full_name": "Name on the beneficiary's bank account.",
+ "meta": "Custom key/value metadata attached to the beneficiary.",
+ "created_at": "Date and time the beneficiary was saved, in UTC.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/flutterwave/flutterwave.py b/products/warehouse_sources/backend/temporal/data_imports/sources/flutterwave/flutterwave.py
new file mode 100644
index 000000000000..4670454464b3
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/flutterwave/flutterwave.py
@@ -0,0 +1,178 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, datetime, timedelta
+from typing import Any, Optional
+
+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 (
+ Endpoint,
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ PageNumberPaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ BearerTokenAuthConfig,
+ ResponseAction,
+)
+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.flutterwave.settings import FLUTTERWAVE_ENDPOINTS
+
+FLUTTERWAVE_API_HOST = "https://api.flutterwave.com"
+
+# Floor of the mandatory date window on /transactions. Flutterwave has no merchant records that
+# predate the platform, so this pulls the full history on every sync without having to guess when the
+# account was opened.
+EARLIEST_WINDOW_START = "2016-01-01"
+
+# The API's `from`/`to` window is day-granular and Flutterwave does not expose the account's
+# reporting timezone, so the window end is padded by a day rather than pinned to UTC today. Pinning
+# it would clip records booked "today" in a timezone ahead of UTC.
+WINDOW_END_PADDING_DAYS = 1
+
+# v3 answers "no records in this range" on some list endpoints with HTTP 400 rather than an empty
+# `data` array, so those bodies are treated as an empty page instead of failing the sync. The match
+# is deliberately narrow: a genuine parameter error ("page parameter must be a positive integer")
+# does not carry this wording and still raises. Both cases are listed because the substring match is
+# case sensitive and v3 is inconsistent about capitalizing "found".
+_NO_RECORDS_RESPONSE_ACTIONS: list[ResponseAction] = [
+ {"status_code": 400, "content": "found", "action": "ignore"},
+ {"status_code": 400, "content": "Found", "action": "ignore"},
+]
+
+
+class FlutterwaveResumeConfig:
+ # 1-based page number to resume pagination from. 1 means "start from the beginning".
+ next_page: int = 1
+
+
+def base_url(api_version: str) -> str:
+ return f"{FLUTTERWAVE_API_HOST}/{api_version}"
+
+
+def _auth_config(secret_key: str) -> BearerTokenAuthConfig:
+ return {"type": "bearer", "token": secret_key}
+
+
+def _window_end() -> str:
+ return (datetime.now(UTC).date() + timedelta(days=WINDOW_END_PADDING_DAYS)).isoformat()
+
+
+def validate_credentials(secret_key: str, api_version: str) -> tuple[bool, str | None]:
+ # /subaccounts is the cheapest authenticated probe: no required params, a small body, and it only
+ # needs the account's secret key. Its response also carries subaccount bank details, so keep it
+ # out of the HTTP diagnostic sample store (capture=False).
+ ok, status = validate_via_probe(
+ lambda: make_tracked_session(redact_values=(secret_key,), capture=False),
+ f"{base_url(api_version)}/subaccounts",
+ headers={"Authorization": f"Bearer {secret_key}", "Accept": "application/json"},
+ )
+ if ok:
+ return True, None
+ if status in (401, 403):
+ return False, "Invalid Flutterwave secret key. Check the key in your Flutterwave dashboard and try again."
+ if status == 400:
+ # The key was accepted; v3 uses 400 for "no subaccounts on this account", which is not a
+ # credential problem.
+ return True, None
+ return False, "Could not reach the Flutterwave API. Try again in a few minutes."
+
+
+def get_rows(
+ secret_key: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ api_version: str,
+ resumable_source_manager: ResumableSourceManager[FlutterwaveResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = FLUTTERWAVE_ENDPOINTS[endpoint]
+
+ params: dict[str, Any] = {}
+ if config.requires_date_window:
+ # /transactions requires `from`/`to`, so a full refresh sends the whole history window: the
+ # earliest-possible floor through today (padded a day for timezones ahead of UTC).
+ params["from"] = EARLIEST_WINDOW_START
+ params["to"] = _window_end()
+
+ endpoint_config: Endpoint = {
+ "path": config.path,
+ "params": params,
+ "data_selector": "data",
+ # Every v3 list endpoint is page-numbered from 1 and reports the page count under
+ # `meta.page_info.total_pages`, which stops pagination without paying an extra empty page.
+ # Page size is left to the API: v3 documents no maximum, and an over-cap value 4xxs.
+ "paginator": PageNumberPaginator(base_page=1, total_path="meta.page_info.total_pages"),
+ "response_actions": _NO_RECORDS_RESPONSE_ACTIONS,
+ }
+
+ rest_config: RESTAPIConfig = {
+ "client": {
+ "base_url": base_url(api_version),
+ "headers": {"Accept": "application/json"},
+ "auth": _auth_config(secret_key),
+ # These bodies carry bank account numbers and transaction metadata, so keep them out of
+ # the HTTP diagnostic sample store (requests are still metered and logged).
+ "session": make_tracked_session(redact_values=(secret_key,), capture=False),
+ },
+ "resources": [{"name": endpoint, "endpoint": endpoint_config}],
+ }
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resume is not None and resume.next_page > 1:
+ initial_paginator_state = {"page": resume.next_page}
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # The framework calls this AFTER a page is yielded and only while a next page remains, so a
+ # crash re-yields the next page rather than skipping it (the merge dedupes on primary key).
+ if state and state.get("page") is not None:
+ resumable_source_manager.save_state(FlutterwaveResumeConfig(next_page=int(state["page"])))
+
+ yield from rest_api_resource(
+ rest_config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+
+def flutterwave_source(
+ secret_key: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ api_version: str,
+ resumable_source_manager: ResumableSourceManager[FlutterwaveResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = FLUTTERWAVE_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ secret_key=secret_key,
+ endpoint=endpoint,
+ team_id=team_id,
+ job_id=job_id,
+ api_version=api_version,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/flutterwave/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/flutterwave/settings.py
new file mode 100644
index 000000000000..8410f533dc76
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/flutterwave/settings.py
@@ -0,0 +1,56 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.types import IncrementalField
+
+# Flutterwave v3's only server-side timestamp filter is the `from`/`to` window over each record's
+# `created_at`, and the API exposes no `updated_at` cursor. Transactions, settlements, refunds,
+# transfers, chargebacks, and payment plans all keep mutating after they are created (statuses flip,
+# refunds and chargebacks resolve, plans get cancelled), so a `created_at` watermark would advance
+# past those rows and never reread the later lifecycle change, leaving the warehouse permanently
+# stale. Until Flutterwave exposes an update cursor, every endpoint here syncs as full refresh so the
+# merge always sees each record's current state.
+
+
+@dataclass
+class FlutterwaveEndpointConfig:
+ name: str
+ path: str
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # `created_at` is stamped when the record is written and never moves, so it partitions cleanly by
+ # month for an efficient merge.
+ partition_key: Optional[str] = "created_at"
+ # /transactions documents `from` and `to` as required, so the floor window is sent on every run.
+ requires_date_window: bool = False
+
+
+FLUTTERWAVE_ENDPOINTS: dict[str, FlutterwaveEndpointConfig] = {
+ # Every payment collected on the account. `from`/`to` are documented as required here.
+ "transactions": FlutterwaveEndpointConfig(
+ name="transactions",
+ path="/transactions",
+ requires_date_window=True,
+ ),
+ # Payouts of collected funds to the merchant's settlement account.
+ "settlements": FlutterwaveEndpointConfig(name="settlements", path="/settlements"),
+ # Money returned to customers against a previously successful charge.
+ "refunds": FlutterwaveEndpointConfig(name="refunds", path="/refunds"),
+ # Outbound payouts initiated by the merchant.
+ "transfers": FlutterwaveEndpointConfig(name="transfers", path="/transfers"),
+ # Customer-initiated payment disputes.
+ "chargebacks": FlutterwaveEndpointConfig(name="chargebacks", path="/chargebacks"),
+ # Recurring billing plan definitions.
+ "payment_plans": FlutterwaveEndpointConfig(name="payment_plans", path="/payment-plans"),
+ # Customer enrolments against a payment plan.
+ "subscriptions": FlutterwaveEndpointConfig(name="subscriptions", path="/subscriptions"),
+ # Collection subaccounts used for split payments.
+ "subaccounts": FlutterwaveEndpointConfig(name="subaccounts", path="/subaccounts"),
+ # Saved payout recipients.
+ "beneficiaries": FlutterwaveEndpointConfig(name="beneficiaries", path="/beneficiaries"),
+}
+
+ENDPOINTS = tuple(FLUTTERWAVE_ENDPOINTS.keys())
+
+# No endpoint syncs incrementally (see the module comment above), so the schema builder receives an
+# empty map and advertises every table as full-refresh.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/flutterwave/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/flutterwave/source.py
index 3c70f2b4b30e..50dcf7fbfd5a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/flutterwave/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/flutterwave/source.py
@@ -1,13 +1,34 @@
-from typing import cast
+from typing import Optional, cast
from 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, SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.flutterwave.flutterwave import (
+ FlutterwaveResumeConfig,
+ flutterwave_source,
+ validate_credentials as validate_flutterwave_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.flutterwave.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.flutterwave import (
FlutterwaveSourceConfig,
)
@@ -15,7 +36,16 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class FlutterwaveSource(SimpleSource[FlutterwaveSourceConfig]):
+class FlutterwaveSource(ResumableSource[FlutterwaveSourceConfig, FlutterwaveResumeConfig]):
+ # v3 is Flutterwave's generally available API and the version every request below calls (the
+ # `/v3` base-URL segment). v4 exists but is still a public beta on a separate host with a
+ # different OAuth flow, so it is not what a new source should land customers on.
+ supported_versions = ("v3",)
+ default_version = "v3"
+ api_docs_url = "https://developer.flutterwave.com/docs/versioning"
+
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.FLUTTERWAVE
@@ -26,7 +56,78 @@ class FlutterwaveSource(SimpleSource[FlutterwaveSourceConfig]):
name=SchemaExternalDataSourceType.FLUTTERWAVE,
category=DataWarehouseSourceCategory.PAYMENTS___BILLING,
label="Flutterwave",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Flutterwave secret key to sync your payments data into the PostHog Data warehouse.
+
+You can find your secret key under Settings > API in the [Flutterwave dashboard](https://app.flutterwave.com/dashboard/settings/apis). Test keys only return sandbox records, so use your live secret key to sync live data.""",
iconPath="/static/services/flutterwave.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/flutterwave",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="secret_key",
+ label="Secret key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="FLWSECK-...",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.flutterwave.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.flutterwave.com": "Your Flutterwave secret key is invalid or has been rotated. Copy the current key from your Flutterwave dashboard, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.flutterwave.com": "Your Flutterwave secret key does not have access to this data. Check the key's permissions in your Flutterwave dashboard, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: FlutterwaveSourceConfig,
+ 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: FlutterwaveSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ return validate_flutterwave_credentials(config.secret_key, self.resolve_api_version(api_version))
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[FlutterwaveResumeConfig]:
+ return ResumableSourceManager[FlutterwaveResumeConfig](inputs, FlutterwaveResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: FlutterwaveSourceConfig,
+ resumable_source_manager: ResumableSourceManager[FlutterwaveResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return flutterwave_source(
+ secret_key=config.secret_key,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ api_version=self.resolve_api_version(inputs.api_version),
+ 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,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/flutterwave/tests/test_flutterwave.py b/products/warehouse_sources/backend/temporal/data_imports/sources/flutterwave/tests/test_flutterwave.py
new file mode 100644
index 000000000000..df701658766d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/flutterwave/tests/test_flutterwave.py
@@ -0,0 +1,340 @@
+import json
+from collections.abc import Iterable
+from datetime import UTC, datetime
+from typing import Any, cast
+
+import pytest
+from freezegun import freeze_time
+from unittest import mock
+
+import requests
+from parameterized import parameterized
+from requests import Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import (
+ RESTClientRetryableError,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.flutterwave.flutterwave import (
+ EARLIEST_WINDOW_START,
+ FlutterwaveResumeConfig,
+ base_url,
+ flutterwave_source,
+ validate_credentials,
+)
+
+# get_rows builds the tracked session (capture=False) and hands it to the REST client, and
+# validate_credentials builds its probe session, both via this import — so one patch covers both.
+SESSION_PATCH = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.flutterwave.flutterwave.make_tracked_session"
+)
+SLEEP_PATCH = "tenacity.nap.time.sleep"
+
+BASE_URL = base_url("v3")
+
+
+def _response(body: Any, *, status: int = 200, reason: str = "OK") -> Response:
+ resp = Response()
+ resp.status_code = status
+ resp.reason = reason
+ resp.url = f"{BASE_URL}/transactions"
+ resp.headers["Content-Type"] = "application/json"
+ resp._content = b"" if body is None else json.dumps(body).encode()
+ return resp
+
+
+def _page(rows: list[dict[str, Any]], total_pages: int = 1) -> dict[str, Any]:
+ return {
+ "status": "success",
+ "message": "fetched",
+ "meta": {"page_info": {"total": len(rows), "current_page": 1, "total_pages": total_pages}},
+ "data": rows,
+ }
+
+
+def _make_manager(resume_state: FlutterwaveResumeConfig | 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]) -> tuple[list[dict[str, Any]], list[Any]]:
+ session.headers = {}
+ param_snapshots: list[dict[str, Any]] = []
+ auth_snapshots: list[Any] = []
+
+ def _prepare(request: Any) -> mock.MagicMock:
+ param_snapshots.append(dict(request.params or {}))
+ auth_snapshots.append(request.auth)
+ return mock.MagicMock()
+
+ session.prepare_request.side_effect = _prepare
+ session.send.side_effect = responses
+ return param_snapshots, auth_snapshots
+
+
+def _rows(source_response: Any) -> list[dict[str, Any]]:
+ return [row for page in cast("Iterable[Any]", source_response.items()) for row in page]
+
+
+def _source(endpoint: str, manager: mock.MagicMock | None = None, **kwargs: Any) -> Any:
+ return flutterwave_source(
+ secret_key="FLWSECK-test",
+ endpoint=endpoint,
+ team_id=1,
+ job_id="j",
+ api_version="v3",
+ resumable_source_manager=manager if manager is not None else _make_manager(),
+ **kwargs,
+ )
+
+
+class TestPagination:
+ @mock.patch(SESSION_PATCH)
+ def test_walks_pages_until_total_pages(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ params, auths = _wire(
+ session,
+ [_response(_page([{"id": 1}], total_pages=2)), _response(_page([{"id": 2}], total_pages=2))],
+ )
+
+ rows = _rows(_source("subaccounts"))
+
+ assert [r["id"] for r in rows] == [1, 2]
+ # Stops on meta.page_info.total_pages instead of paying for an extra empty page.
+ assert session.send.call_count == 2
+ assert [p["page"] for p in params] == [1, 2]
+ # The secret rides on framework bearer auth, never a query param.
+ assert auths[0].token == "FLWSECK-test"
+ assert "seckey" not in params[0]
+
+ @mock.patch(SESSION_PATCH)
+ def test_empty_page_stops_pagination(self, MockSession: mock.MagicMock) -> None:
+ # A body that claims more pages than it has must not loop forever on empty responses.
+ session = MockSession.return_value
+ _wire(session, [_response(_page([], total_pages=9))])
+
+ assert _rows(_source("subaccounts")) == []
+ assert session.send.call_count == 1
+
+ @mock.patch(SESSION_PATCH)
+ def test_resumes_from_saved_page(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ params, _auths = _wire(session, [_response(_page([{"id": 7}], total_pages=4))])
+
+ rows = _rows(_source("subaccounts", _make_manager(FlutterwaveResumeConfig(next_page=4))))
+
+ assert [r["id"] for r in rows] == [7]
+ assert params[0]["page"] == 4
+
+ @mock.patch(SESSION_PATCH)
+ def test_saves_page_after_yielding_and_only_while_pages_remain(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ _wire(
+ session,
+ [_response(_page([{"id": 1}], total_pages=2)), _response(_page([{"id": 2}], total_pages=2))],
+ )
+
+ manager = _make_manager()
+ _rows(_source("subaccounts", manager))
+
+ # Only page 1 has a page after it, so exactly one checkpoint is written and it points at 2.
+ assert [c.args[0] for c in manager.save_state.call_args_list] == [FlutterwaveResumeConfig(next_page=2)]
+
+
+class TestDateWindow:
+ @parameterized.expand(
+ [
+ ("settlements",),
+ ("refunds",),
+ ("transfers",),
+ ("chargebacks",),
+ ("payment_plans",),
+ ]
+ )
+ @mock.patch(SESSION_PATCH)
+ def test_optional_window_endpoints_send_no_window_on_full_refresh(
+ self, endpoint: str, MockSession: mock.MagicMock
+ ) -> None:
+ # A full refresh must pull the whole history; a stray `from` would silently truncate it.
+ session = MockSession.return_value
+ params, _auths = _wire(session, [_response(_page([{"id": 1}]))])
+
+ _rows(
+ _source(
+ endpoint,
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=datetime(2024, 1, 15, tzinfo=UTC),
+ )
+ )
+
+ assert "from" not in params[0]
+ assert "to" not in params[0]
+
+ @parameterized.expand(
+ [
+ ("subscriptions",),
+ ("subaccounts",),
+ ("beneficiaries",),
+ ]
+ )
+ @mock.patch(SESSION_PATCH)
+ def test_endpoints_without_a_window_never_send_one(self, endpoint: str, MockSession: mock.MagicMock) -> None:
+ # These endpoints do not accept `from`/`to`; sending them risks 4xxing the whole run.
+ session = MockSession.return_value
+ params, _auths = _wire(session, [_response(_page([{"id": 1}]))])
+
+ _rows(_source(endpoint, should_use_incremental_field=False, db_incremental_field_last_value=None))
+
+ assert "from" not in params[0]
+ assert "to" not in params[0]
+
+ @freeze_time("2026-06-15T23:30:00Z")
+ @mock.patch(SESSION_PATCH)
+ def test_transactions_always_sends_the_required_window(self, MockSession: mock.MagicMock) -> None:
+ # /transactions documents `from`/`to` as required, so every full refresh sends the whole
+ # history window. `to` is padded a day past UTC today so records booked "today" in a timezone
+ # ahead of UTC are not clipped.
+ session = MockSession.return_value
+ params, _auths = _wire(session, [_response(_page([{"id": 1}]))])
+
+ _rows(_source("transactions", should_use_incremental_field=False, db_incremental_field_last_value=None))
+
+ assert params[0]["from"] == EARLIEST_WINDOW_START
+ assert params[0]["to"] == "2026-06-16"
+
+
+class TestNoRecordsResponses:
+ @parameterized.expand(
+ [
+ ("lowercase", {"status": "error", "message": "No settlements found", "data": None}),
+ ("capitalized", {"status": "error", "message": "Transaction Not Found", "data": None}),
+ ]
+ )
+ @mock.patch(SESSION_PATCH)
+ def test_empty_range_400_reads_as_an_empty_table(
+ self, _name: str, body: dict[str, Any], MockSession: mock.MagicMock
+ ) -> None:
+ # v3 answers "no records in this range" with a 400 on some list endpoints; a merchant with an
+ # empty table must sync zero rows rather than fail the job.
+ session = MockSession.return_value
+ _wire(session, [_response(body, status=400, reason="Bad Request")])
+
+ assert _rows(_source("settlements")) == []
+ assert session.send.call_count == 1
+
+ @mock.patch(SESSION_PATCH)
+ def test_genuine_parameter_error_still_raises(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ _wire(
+ session,
+ [
+ _response(
+ {"status": "error", "message": "page parameter must be a positive integer", "data": None},
+ status=400,
+ reason="Bad Request",
+ )
+ ],
+ )
+
+ with pytest.raises(requests.HTTPError):
+ _rows(_source("settlements"))
+
+
+class TestErrorHandling:
+ @parameterized.expand([("unauthorized", 401, "Unauthorized"), ("forbidden", 403, "Forbidden")])
+ @mock.patch(SESSION_PATCH)
+ def test_credential_errors_surface_the_matchable_message(
+ self, _name: str, status: int, reason: str, MockSession: mock.MagicMock
+ ) -> None:
+ # get_non_retryable_errors matches on this exact status text plus host, so it must not be
+ # swallowed or retried.
+ session = MockSession.return_value
+ _wire(session, [_response({"status": "error"}, status=status, reason=reason)])
+
+ with pytest.raises(requests.HTTPError) as exc_info:
+ _rows(_source("transactions"))
+ assert f"{status} Client Error" in str(exc_info.value)
+ assert "https://api.flutterwave.com" in str(exc_info.value)
+ assert session.send.call_count == 1
+
+ @parameterized.expand([("rate_limited", 429, "Too Many Requests"), ("server_error", 503, "Service Unavailable")])
+ @mock.patch(SLEEP_PATCH)
+ @mock.patch(SESSION_PATCH)
+ def test_transient_statuses_are_retried_by_the_transport(
+ self, _name: str, status: int, reason: str, MockSession: mock.MagicMock, _sleep: mock.MagicMock
+ ) -> None:
+ session = MockSession.return_value
+ _wire(session, [_response({}, status=status, reason=reason), _response(_page([{"id": 1}]))])
+
+ assert [r["id"] for r in _rows(_source("transactions"))] == [1]
+ assert session.send.call_count == 2
+
+ @mock.patch(SLEEP_PATCH)
+ @mock.patch(SESSION_PATCH)
+ def test_persistent_rate_limit_raises_retryable(self, MockSession: mock.MagicMock, _sleep: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ _wire(session, [_response({}, status=429, reason="Too Many Requests")] * 5)
+
+ with pytest.raises(RESTClientRetryableError):
+ _rows(_source("transactions"))
+
+
+class TestSourceResponseMetadata:
+ @parameterized.expand(
+ [
+ ("transactions",),
+ ("settlements",),
+ ("refunds",),
+ ("transfers",),
+ ("chargebacks",),
+ ("payment_plans",),
+ ("subscriptions",),
+ ("subaccounts",),
+ ("beneficiaries",),
+ ]
+ )
+ def test_every_endpoint_partitions_on_created_at(self, endpoint: str) -> None:
+ response = _source(endpoint)
+ assert response.name == endpoint
+ assert response.primary_keys == ["id"]
+ # Every endpoint is full-refresh, so the pipeline never consults sort_mode; it stays the
+ # framework default.
+ assert response.sort_mode == "asc"
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == ["created_at"]
+
+
+class TestValidateCredentials:
+ @parameterized.expand(
+ [
+ ("ok", 200, True),
+ # v3 answers "no subaccounts on this account" with a 400; the key was still accepted.
+ ("no_records", 400, True),
+ ("unauthorized", 401, False),
+ ("forbidden", 403, False),
+ ("server_error", 500, False),
+ ]
+ )
+ def test_status_maps_to_validity(self, _name: str, status_code: int, expected: bool) -> None:
+ session = mock.MagicMock()
+ session.get.return_value = mock.MagicMock(status_code=status_code)
+ with mock.patch(SESSION_PATCH, return_value=session):
+ valid, message = validate_credentials("FLWSECK-test", "v3")
+ assert valid is expected
+ assert (message is None) is expected
+
+ def test_network_failure_is_not_valid(self) -> None:
+ session = mock.MagicMock()
+ session.get.side_effect = requests.ConnectionError("boom")
+ with mock.patch(SESSION_PATCH, return_value=session):
+ valid, message = validate_credentials("FLWSECK-test", "v3")
+ assert valid is False
+ assert message is not None
+
+ def test_probe_targets_the_pinned_api_version(self) -> None:
+ session = mock.MagicMock()
+ session.get.return_value = mock.MagicMock(status_code=200)
+ with mock.patch(SESSION_PATCH, return_value=session):
+ validate_credentials("FLWSECK-test", "v3")
+ assert session.get.call_args.args[0] == "https://api.flutterwave.com/v3/subaccounts"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/flutterwave/tests/test_flutterwave_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/flutterwave/tests/test_flutterwave_source.py
new file mode 100644
index 000000000000..cfdc608083cb
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/flutterwave/tests/test_flutterwave_source.py
@@ -0,0 +1,178 @@
+from typing import Any
+
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.schema import (
+ ExternalDataSourceType as SchemaExternalDataSourceType,
+ 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.flutterwave.flutterwave import (
+ FlutterwaveResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.flutterwave.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.flutterwave.source import FlutterwaveSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+SOURCE_MODULE_PATCH = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.flutterwave.source.flutterwave_source"
+)
+
+
+def _source_inputs(**overrides: Any) -> MagicMock:
+ inputs = MagicMock()
+ inputs.schema_name = overrides.get("schema_name", "transactions")
+ inputs.team_id = overrides.get("team_id", 1)
+ inputs.job_id = overrides.get("job_id", "job-1")
+ inputs.api_version = overrides.get("api_version", None)
+ inputs.should_use_incremental_field = overrides.get("should_use_incremental_field", True)
+ inputs.db_incremental_field_last_value = overrides.get("db_incremental_field_last_value", "2024-01-15 00:00:00")
+ return inputs
+
+
+class TestSourceConfig:
+ def test_source_type(self) -> None:
+ assert FlutterwaveSource().source_type == ExternalDataSourceType.FLUTTERWAVE
+
+ def test_config_identity_and_release_contract(self) -> None:
+ config = FlutterwaveSource().get_source_config
+ assert config.name == SchemaExternalDataSourceType.FLUTTERWAVE
+ # Alpha but released: the finished source must be reachable, so unreleasedSource stays off.
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert not config.unreleasedSource
+ # The doc slug is derived from this URL; a mismatch 404s the docs page.
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/flutterwave"
+
+ def test_secret_key_is_a_required_secret_field(self) -> None:
+ fields = FlutterwaveSource().get_source_config.fields
+ secret_fields = [f for f in fields if isinstance(f, SourceFieldInputConfig) and f.name == "secret_key"]
+ assert len(secret_fields) == 1
+ field = secret_fields[0]
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+ assert field.required is True
+ assert field.secret is True
+
+ def test_pins_the_generally_available_api_version(self) -> None:
+ # The request layer builds its base URL from this pin, so a drift here silently retargets
+ # every customer's sync at a different API surface.
+ source = FlutterwaveSource()
+ assert source.supported_versions == ("v3",)
+ assert source.default_version == "v3"
+ assert source.resolve_api_version(None) == "v3"
+
+
+class TestGetSchemas:
+ @parameterized.expand(
+ [
+ ("transactions",),
+ ("settlements",),
+ ("refunds",),
+ ("transfers",),
+ ("chargebacks",),
+ ("payment_plans",),
+ ("subscriptions",),
+ ("subaccounts",),
+ ("beneficiaries",),
+ ]
+ )
+ def test_every_endpoint_is_full_refresh(self, endpoint: str) -> None:
+ # Flutterwave v3 has no update cursor and its records mutate after creation, so no endpoint
+ # may advertise incremental sync (a created_at watermark would strand later status changes).
+ schemas = {s.name: s for s in FlutterwaveSource().get_schemas(MagicMock(), team_id=1)}
+ assert schemas[endpoint].supports_incremental is False
+ assert schemas[endpoint].supports_append is False
+ assert schemas[endpoint].incremental_fields == []
+
+ def test_names_filter(self) -> None:
+ schemas = FlutterwaveSource().get_schemas(MagicMock(), team_id=1, names=["refunds"])
+ assert [s.name for s in schemas] == ["refunds"]
+
+
+class TestNonRetryableErrors:
+ @parameterized.expand(
+ [
+ (
+ "unauthorized",
+ "401 Client Error: Unauthorized for url: https://api.flutterwave.com/v3/transactions?page=1",
+ ),
+ ("forbidden", "403 Client Error: Forbidden for url: https://api.flutterwave.com/v3/settlements"),
+ ]
+ )
+ def test_credential_errors_are_non_retryable(self, _name: str, observed: str) -> None:
+ assert any(key in observed for key in FlutterwaveSource().get_non_retryable_errors())
+
+ @parameterized.expand(
+ [
+ ("read_timeout", "HTTPSConnectionPool(host='api.flutterwave.com', port=443): Read timed out."),
+ (
+ "server_error",
+ "500 Server Error: Internal Server Error for url: https://api.flutterwave.com/v3/transactions",
+ ),
+ ("rate_limited", "429 Client Error: Too Many Requests for url: https://api.flutterwave.com/v3/transfers"),
+ ]
+ )
+ def test_transient_errors_stay_retryable(self, _name: str, observed: str) -> None:
+ assert not any(key in observed for key in FlutterwaveSource().get_non_retryable_errors())
+
+
+class TestSourceForPipeline:
+ def test_threads_credentials_endpoint_and_api_version(self) -> None:
+ with patch(SOURCE_MODULE_PATCH) as mock_source:
+ FlutterwaveSource().source_for_pipeline(
+ config=MagicMock(secret_key="FLWSECK-test"),
+ resumable_source_manager=MagicMock(),
+ inputs=_source_inputs(schema_name="transactions", should_use_incremental_field=False),
+ )
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["secret_key"] == "FLWSECK-test"
+ assert kwargs["endpoint"] == "transactions"
+ # An unset pin must resolve to default_version, not fall through as None and break the URL.
+ assert kwargs["api_version"] == "v3"
+
+ def test_watermark_dropped_on_full_refresh(self) -> None:
+ # Every endpoint is full-refresh, so a stored watermark must never leak into the query, or an
+ # unwanted `from` filter would silently truncate the pull.
+ with patch(SOURCE_MODULE_PATCH) as mock_source:
+ FlutterwaveSource().source_for_pipeline(
+ config=MagicMock(secret_key="FLWSECK-test"),
+ resumable_source_manager=MagicMock(),
+ inputs=_source_inputs(schema_name="subaccounts", should_use_incremental_field=False),
+ )
+ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None
+
+
+class TestValidateCredentials:
+ @parameterized.expand([("valid", (True, None), True), ("invalid", (False, "nope"), False)])
+ def test_delegates_to_the_transport_probe(
+ self, _name: str, probe_result: tuple[bool, str | None], expected: bool
+ ) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.flutterwave.source.validate_flutterwave_credentials",
+ return_value=probe_result,
+ ) as probe:
+ valid, _message = FlutterwaveSource().validate_credentials(MagicMock(secret_key="FLWSECK-test"), team_id=1)
+ assert valid is expected
+ assert probe.call_args.args == ("FLWSECK-test", "v3")
+
+
+class TestResumableManager:
+ def test_returns_manager_bound_to_resume_config(self) -> None:
+ manager = FlutterwaveSource().get_resumable_source_manager(MagicMock())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is FlutterwaveResumeConfig
+
+
+class TestDocumentedTables:
+ def test_lists_tables_without_credentials(self) -> None:
+ # Static endpoint catalog (no I/O), so the public docs Supported tables section renders.
+ source = FlutterwaveSource()
+ assert source.lists_tables_without_credentials is True
+ assert {t["name"] for t in source.get_documented_tables()} == set(ENDPOINTS)
+
+ def test_canonical_descriptions_cover_every_endpoint(self) -> None:
+ assert set(FlutterwaveSource().get_canonical_descriptions().keys()) == set(ENDPOINTS)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/flutterwave.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/flutterwave.py
index 235b9837f5be..4d9a84e195ea 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/flutterwave.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/flutterwave.py
@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class FlutterwaveSourceConfig(config.Config):
- pass
+ secret_key: str