: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 Yoco source (#77141)
Tom Owers393fc29c45aa
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 79838c6ba410..9634b2f2e1c1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -696,6 +696,7 @@ the row lists both.| wufoo | HTTP | requests | ✅ || xendit | HTTP | requests + `rest_source.RESTClient` | ✅ || xmatters | HTTP | requests | ✅ |+| yoco | HTTP | requests + `rest_source.RESTClient` | ✅ || yousign | HTTP + Webhook | requests + `rest_source.RESTClient` + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) || youtube_analytics | HTTP | requests | ✅ || zapier_supported_storage | HTTP | requests | ✅ |@@ -1452,7 +1453,6 @@ doesn't conflict with concurrent PRs.- yahoo_finance- yandex_metrica- ynab-- yoco- yotpo- younium- youtube_datadiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/yoco.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/yoco.pyindex 77f3c5225872..27390ae7044b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/yoco.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/yoco.py@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass YocoSourceConfig(config.Config):- pass+ api_key: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/yoco/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/yoco/canonical_descriptions.pynew file mode 100644index 000000000000..9686b13f3cf9--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/yoco/canonical_descriptions.py@@ -0,0 +1,226 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_API_REFERENCE = "https://developer.yoco.com/api-reference/yoco-api"++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "payments": {+ "description": "Money collected from a customer, in person on a card machine or online through checkout.",+ "docs_url": f"{_API_REFERENCE}/payments/list-payments-v-1-payments-get",+ "columns": {+ "id": "The unique identifier of the payment.",+ "created_at": "The payment creation date and time in ISO 8601 format.",+ "updated_at": "The date and time the payment was last modified in ISO 8601 format.",+ "status": "The state of the payment: approved, cancelled, failed or pending.",+ "total_amount": "The total amount collected, including any tip, with its currency.",+ "amount_excl_tip": "The amount collected excluding the tip.",+ "tip_amount": "The tip portion of the payment.",+ "refunded_amount": "The amount refunded against this payment so far.",+ "payment_method": "How the customer paid, for example card, cash or instant EFT.",+ "payment_source": "Where the payment was taken, for example a card machine or online checkout.",+ "receipt_number": "The receipt number shown to the customer.",+ "display_name": "A human friendly label for the payment.",+ "note": "An optional note captured against the payment.",+ "processing_fees": "The fees Yoco assessed on this payment.",+ "refunds": "The refunds issued against this payment.",+ "order_id": "A reference to the order this payment settles.",+ "checkout_id": "A reference to the online checkout that produced this payment.",+ "external_id": "An identifier supplied by the integration that created the payment.",+ "client_transaction_id": "The identifier provided when creating the transaction via the SDK.",+ "card_machine_id": "A reference to the card machine that took the payment.",+ "staff_id": "A reference to the staff member who took the payment.",+ },+ },+ "orders": {+ "description": "A sale recorded on the point of sale or online, with its line items, payments and refunds.",+ "docs_url": f"{_API_REFERENCE}/orders/list-orders-v-1-orders-get",+ "columns": {+ "id": "The unique identifier of the order.",+ "order_number": "The human friendly order number.",+ "display_name": "A human friendly label for the order.",+ "name": "The name given to the order.",+ "status": "The state of the order: open, completed or cancelled.",+ "created_at": "The order creation date and time in ISO 8601 format.",+ "updated_at": "The date and time the order was last modified in ISO 8601 format.",+ "closed_at": "The date and time the order was closed in ISO 8601 format.",+ "currency": "The ISO 4217 currency code of the order.",+ "location_id": "A reference to the location the order was taken at.",+ "staff_id": "A reference to the staff member who took the order.",+ "amounts": "The gross, net, tax, discount and tip totals for the order.",+ "line_items": "The items sold on the order.",+ "payments": "The payments applied to the order.",+ "refunds": "The refunds issued against the order.",+ "returns": "The items returned against the order.",+ "applied_discounts": "The discounts applied to the order.",+ "total_taxes": "The taxes charged on the order.",+ "note": "An optional note captured against the order.",+ },+ },+ "refunds": {+ "description": "Money returned to a customer against an earlier payment.",+ "docs_url": f"{_API_REFERENCE}/refunds/list-refunds-v-1-refunds-get",+ "columns": {+ "id": "The unique identifier of the refund.",+ "client_transaction_id": "The identifier provided when creating the transaction via the SDK.",+ "created_at": "The refund creation date and time in ISO 8601 format.",+ "updated_at": "The date and time the refund was last modified in ISO 8601 format.",+ "processed_at": "The date and time the refund finished processing in ISO 8601 format.",+ "status": "The state of the refund: approved, failed, pending or rejected.",+ "refund_type": "How the refund was made: auth reversal, credit return or other.",+ "total_amount": "The amount refunded, with its currency.",+ "currency": "The ISO 4217 currency code of the refund.",+ "payment_method": "The method the original payment used.",+ "payment_id": "A reference to the payment being refunded.",+ "order_id": "A reference to the refund order.",+ "order_number": "The human friendly number of the refund order.",+ "original_order_id": "A reference to the order the refunded payment belongs to.",+ "original_order_number": "The human friendly number of the original order.",+ "receipt_number": "The receipt number of the refund.",+ "display_name": "A human friendly label for the refund.",+ "note": "An optional note captured against the refund.",+ "processing_fees": "The fees assessed on the original transaction.",+ "refunded_processing_fees": "The fees returned as part of the refund.",+ "staff_id": "A reference to the staff member who processed the refund.",+ },+ },+ "payouts": {+ "description": "A batch of settled transactions paid out to the business bank account.",+ "docs_url": f"{_API_REFERENCE}/payouts/list-payouts-v-1-payouts-get",+ "columns": {+ "id": "The unique identifier of the payout.",+ "gross_amount": "The total amount of the payout before fees and deductions.",+ "net_amount": "The proceeds of the payout after fees and deductions.",+ "fee_amount": "The total fees assessed on the payout.",+ "payout_fees": "The breakdown of fees assessed on the payout.",+ "capital_repayment_amount": "The amount deducted and paid back towards a cash advance.",+ "payout_type": "The payout speed: standard, fast, instant or weekly.",+ "status": "The state of the payout: unpaid, sent, paid or failed.",+ "created_at": "The payout creation date and time in ISO 8601 format.",+ "updated_at": "The date and time the payout was last modified in ISO 8601 format.",+ },+ },+ "payout_entries": {+ "description": "A single transaction that makes up a payout, mapping payments, refunds and fees to the batch they settled in.",+ "docs_url": f"{_API_REFERENCE}/payouts/list-payout-entries-v-1-payouts-payout-id-payout-entries-get",+ "columns": {+ "id": "The unique identifier of the payout entry.",+ "payout_id": "A reference to the payout that this entry is a part of.",+ "type": "What the entry represents, for example a payment, refund, fee or adjustment.",+ "gross_amount": "The gross amount of this payout entry.",+ "net_amount": "The net proceeds of this payout entry after any fees and deductions.",+ "fee_amount": "The fee associated with this payout entry.",+ "capital_repayment_amount": "The amount deducted and paid back towards a cash advance.",+ "client_transaction_id": "The identifier provided when creating the transaction via the SDK.",+ },+ },+ "payment_links": {+ "description": "A shareable link that lets a customer pay online without a checkout integration.",+ "docs_url": f"{_API_REFERENCE}/payment-links/list-payment-links-v-1-payment-links-get",+ "columns": {+ "id": "The unique identifier of the payment link.",+ "order_id": "A reference to the order the link was created for.",+ "url": "The URL the customer opens to pay.",+ "status": "The state of the link: pending, paid or cancelled.",+ "customer_reference": "The customer name or reference shown on the payment page.",+ "customer_description": "An optional description shown to the customer.",+ "created_at": "The link creation date and time in ISO 8601 format.",+ "updated_at": "The date and time the link was last modified in ISO 8601 format.",+ },+ },+ "items": {+ "description": "A product or service in the business catalogue, with its variants, options and pricing.",+ "docs_url": f"{_API_REFERENCE}/items/list-items-v-1-items-get",+ "columns": {+ "id": "The unique identifier of the item.",+ "type": "Whether the item is a product or a service.",+ "name": "The name of the item.",+ "description": "The description of the item.",+ "created_at": "The item creation date and time in ISO 8601 format.",+ "updated_at": "The date and time the item was last modified in ISO 8601 format.",+ "default_price": "The default price of the item, with its currency.",+ "is_taxable": "Whether tax applies to the item.",+ "category_id": "A reference to the category the item belongs to.",+ "brand_id": "A reference to the brand of the item. Products only.",+ "images": "The images attached to the item.",+ "modifier_groups": "The modifier groups available on the item.",+ "options": "The options that define the item's variants.",+ "taxes": "The taxes that apply to the item.",+ "variants": "The purchasable variants of the item.",+ "has_multiple_variants": "Whether the item has more than one variant.",+ },+ },+ "item_categories": {+ "description": "A grouping of catalogue items, used to organise the point of sale.",+ "docs_url": f"{_API_REFERENCE}/item-categories/list-item-categories-v-1-item-categories-get",+ "columns": {+ "id": "The unique identifier of the category.",+ "name": "The name of the category.",+ "description": "The description of the category.",+ "image": "The image shown for the category in the point of sale app.",+ "parent_category": "The category this category sits under.",+ "created_at": "The category creation date and time in ISO 8601 format.",+ "updated_at": "The date and time the category was last modified in ISO 8601 format.",+ },+ },+ "item_brands": {+ "description": "A brand that catalogue products can be attributed to.",+ "docs_url": f"{_API_REFERENCE}/item-brands/list-item-brands-v-1-item-brands-get",+ "columns": {+ "id": "The unique identifier of the brand.",+ "name": "The name of the brand.",+ "description": "The description of the brand.",+ "image": "The image attached to the brand.",+ "created_at": "The brand creation date and time in ISO 8601 format.",+ "updated_at": "The date and time the brand was last modified in ISO 8601 format.",+ },+ },+ "modifier_groups": {+ "description": "A set of modifiers, such as extras or sizes, that customers can pick from when ordering an item.",+ "docs_url": f"{_API_REFERENCE}/modifier-groups/list-modifier-groups-v-1-modifier-groups-get",+ "columns": {+ "id": "The unique identifier of the modifier group.",+ "name": "The name of the modifier group.",+ "created_at": "The modifier group creation date and time in ISO 8601 format.",+ "min_selections": "The minimum number of modifiers a customer must select. Zero means optional.",+ "max_selections": "The maximum number of modifiers a customer may select. Null means unlimited.",+ "modifiers": "The modifiers in the group, with their pricing and default selection.",+ },+ },+ "locations": {+ "description": "A trading location of the business, used to attribute orders and catalogue availability.",+ "docs_url": f"{_API_REFERENCE}/locations/list-locations-v-1-locations-get",+ "columns": {+ "id": "The unique identifier of the location.",+ "name": "The name of the location.",+ "created_at": "The location creation date and time in ISO 8601 format.",+ "updated_at": "The date and time the location was last modified in ISO 8601 format.",+ },+ },+ "staff": {+ "description": "A staff member of the business, used to attribute payments, orders and refunds.",+ "docs_url": f"{_API_REFERENCE}/staff/list-staff-v-1-staff-get",+ "columns": {+ "id": "The unique identifier of the staff member.",+ "first_name": "The first name of the staff member.",+ "last_name": "The last name of the staff member.",+ "role": "The role of the staff member, for example administrator, manager or staff member.",+ "status": "Whether the staff member is active or inactive.",+ "staff_number": "The identifier for the staff member in an external system.",+ "created_at": "The staff member creation date and time in ISO 8601 format.",+ "updated_at": "The date and time the staff member was last modified in ISO 8601 format.",+ "deleted_at": "The date and time the staff member was removed in ISO 8601 format.",+ },+ },+ "card_machines": {+ "description": "A Yoco card machine registered to the business.",+ "docs_url": f"{_API_REFERENCE}/card-machines/list-card-machines-v-1-card-machines-get",+ "columns": {+ "id": "The unique identifier of the card machine.",+ "serial_number": "The serial number of the device.",+ "nickname": "The name the business gave the device.",+ "created_at": "The device creation date and time in ISO 8601 format.",+ "updated_at": "The date and time the device was last modified in ISO 8601 format.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/yoco/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/yoco/settings.pynew file mode 100644index 000000000000..4b7c282c29d6--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/yoco/settings.py@@ -0,0 +1,181 @@+from dataclasses import dataclass, field+from datetime import timedelta++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ DependentEndpointConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field+from products.warehouse_sources.backend.types import IncrementalField++YOCO_BASE_URL = "https://api.yoco.com"++# Yoco documents a default page size of 50 and no maximum, so we send the documented default+# rather than guessing at a higher cap that the API might reject.+DEFAULT_PAGE_SIZE = 50++# Yoco caps any `created_at`/`updated_at` range at 31 days, and fills in the missing bound 31+# days away when only one is given. An incremental sync therefore walks the interval between+# the watermark and now in windows of at most this size instead of one open-ended `__gte`.+MAX_FILTER_WINDOW = timedelta(days=31)++# Scope each endpoint needs on the API key, surfaced per table in the schema picker.+ENDPOINT_SCOPES: dict[str, str] = {+ "payments": "business/orders:read",+ "orders": "business/orders:read",+ "refunds": "business/orders:read",+ "payment_links": "business/orders:read",+ "payouts": "business/payouts:read",+ "payout_entries": "business/payouts:read",+ "items": "business/catalogue:read",+ "item_categories": "business/catalogue:read",+ "item_brands": "business/catalogue:read",+ "modifier_groups": "business/catalogue:read",+ "locations": "business/locations:read",+ "staff": "business/staff:read",+ "card_machines": "business/devices:read",+}+++# Mutable by choice, not oversight: instances flow into `build_dependent_resource`'s+# `endpoint_configs: Mapping[str, FanoutEndpointLike]`, and mypy treats a frozen dataclass's+# fields as read-only, which is incompatible with that Protocol's plain (read-write) attributes.+@dataclass(frozen=False)+class YocoEndpointConfig:+ name: str+ path: str+ primary_key: list[str]+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ default_incremental_field: str | None = None+ partition_key: str | None = None+ page_size: int = DEFAULT_PAGE_SIZE+ fanout: DependentEndpointConfig | None = None+++def _created_and_updated() -> list[IncrementalField]:+ # Both filters exist on every dated list endpoint. `updated_at` is the better cursor+ # because it also catches later edits, but Yoco types it nullable on several resources,+ # so `created_at` stays available for anyone who sees never-modified rows drop out.+ return [incremental_field("updated_at"), incremental_field("created_at")]+++YOCO_ENDPOINTS: dict[str, YocoEndpointConfig] = {+ "payments": YocoEndpointConfig(+ name="payments",+ path="/v1/payments/",+ primary_key=["id"],+ incremental_fields=_created_and_updated(),+ default_incremental_field="updated_at",+ partition_key="created_at",+ ),+ "orders": YocoEndpointConfig(+ name="orders",+ path="/v1/orders/",+ primary_key=["id"],+ incremental_fields=_created_and_updated(),+ default_incremental_field="updated_at",+ partition_key="created_at",+ ),+ "refunds": YocoEndpointConfig(+ name="refunds",+ path="/v1/refunds/",+ primary_key=["id"],+ incremental_fields=_created_and_updated(),+ default_incremental_field="updated_at",+ partition_key="created_at",+ ),+ "payouts": YocoEndpointConfig(+ name="payouts",+ path="/v1/payouts/",+ primary_key=["id"],+ incremental_fields=_created_and_updated(),+ default_incremental_field="updated_at",+ partition_key="created_at",+ ),+ "payout_entries": YocoEndpointConfig(+ name="payout_entries",+ path="/v1/payouts/{payout_id}/payout_entries",+ # Yoco calls `id` the unique identifier of the payout entry, but this table aggregates+ # entries from every payout and the docs never claim uniqueness beyond the parent, so+ # the payout id is part of the key.+ primary_key=["payout_id", "id"],+ # No date filters and no timestamp on the entry itself: full refresh, no partitioning.+ fanout=DependentEndpointConfig(+ parent_name="payouts",+ resolve_param="payout_id",+ resolve_field="id",+ # Entries already carry `payout_id`, so nothing needs injecting from the parent.+ include_from_parent=[],+ ),+ ),+ "payment_links": YocoEndpointConfig(+ name="payment_links",+ path="/v1/payment_links/",+ primary_key=["id"],+ incremental_fields=_created_and_updated(),+ default_incremental_field="updated_at",+ partition_key="created_at",+ ),+ "items": YocoEndpointConfig(+ name="items",+ path="/v1/items/",+ primary_key=["id"],+ incremental_fields=_created_and_updated(),+ default_incremental_field="updated_at",+ partition_key="created_at",+ ),+ "item_categories": YocoEndpointConfig(+ name="item_categories",+ path="/v1/item_categories/",+ primary_key=["id"],+ incremental_fields=_created_and_updated(),+ default_incremental_field="updated_at",+ partition_key="created_at",+ ),+ "item_brands": YocoEndpointConfig(+ name="item_brands",+ path="/v1/item_brands/",+ primary_key=["id"],+ incremental_fields=_created_and_updated(),+ default_incremental_field="updated_at",+ partition_key="created_at",+ ),+ "modifier_groups": YocoEndpointConfig(+ name="modifier_groups",+ path="/v1/modifier_groups/",+ primary_key=["id"],+ # Only `created_at` is filterable here — the resource has no `updated_at` at all.+ incremental_fields=[incremental_field("created_at")],+ default_incremental_field="created_at",+ partition_key="created_at",+ ),+ "locations": YocoEndpointConfig(+ name="locations",+ path="/v1/locations/",+ primary_key=["id"],+ # The location object has timestamps but the endpoint takes no date filters, so+ # filtering would happen client side. Full refresh instead.+ partition_key="created_at",+ ),+ "staff": YocoEndpointConfig(+ name="staff",+ path="/v1/staff/",+ primary_key=["id"],+ incremental_fields=_created_and_updated(),+ default_incremental_field="updated_at",+ partition_key="created_at",+ ),+ "card_machines": YocoEndpointConfig(+ name="card_machines",+ path="/v1/card_machines/",+ primary_key=["id"],+ incremental_fields=_created_and_updated(),+ default_incremental_field="updated_at",+ partition_key="created_at",+ ),+}++ENDPOINTS = tuple(YOCO_ENDPOINTS)++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in YOCO_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/yoco/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/yoco/source.pyindex e93591bbb86b..3e6f814460d1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/yoco/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/yoco/source.py@@ -1,30 +1,146 @@-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.yoco import YocoSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.yoco import yoco as api_client+from products.warehouse_sources.backend.temporal.data_imports.sources.yoco.settings import ENDPOINTS, INCREMENTAL_FIELDS+from products.warehouse_sources.backend.temporal.data_imports.sources.yoco.yoco import YocoResumeConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType+YOCO_DEVELOPER_CONSOLE_URL = "https://developer.yoco.com/ui"+@SourceRegistry.register-class YocoSource(SimpleSource[YocoSourceConfig]):+class YocoSource(ResumableSource[YocoSourceConfig, YocoResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ # Yoco serves a single unversioned `/v1/` path and documents no version choice, so the+ # framework's unversioned default stands.+ api_docs_url = "https://developer.yoco.com/api-reference"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.YOCO+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url": (+ "Yoco rejected the API key. Create a new key in the Yoco Developer Console and reconnect."+ ),+ "403 Client Error: Forbidden for url": (+ "Your Yoco API key does not have the scope this table needs. Grant the missing scope "+ "in the Yoco Developer Console and reconnect."+ ),+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.yoco.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: YocoSourceConfig,+ 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: YocoSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return api_client.validate_credentials(config.api_key)++ def get_endpoint_permissions(+ self,+ config: YocoSourceConfig,+ team_id: int,+ endpoints: list[str],+ api_version: str | None = None,+ ) -> dict[str, str | None]:+ return api_client.get_endpoint_permissions(config.api_key, endpoints)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[YocoResumeConfig]:+ return ResumableSourceManager[YocoResumeConfig](inputs, YocoResumeConfig)++ def source_for_pipeline(+ self,+ config: YocoSourceConfig,+ resumable_source_manager: ResumableSourceManager[YocoResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return api_client.yoco_source(+ api_key=config.api_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,+ incremental_field=inputs.incremental_field,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.YOCO,category=DataWarehouseSourceCategory.PAYMENTS___BILLING,- label="Yoco (Yoco Technologies)",+ label="Yoco",+ caption=(+ "Import payments, orders, refunds, payouts, catalogue, and staff from your Yoco "+ "business.\n\n"+ f"Create an API key in the [Yoco Developer Console]({YOCO_DEVELOPER_CONSOLE_URL}). "+ "Give the key the scopes for the tables you want to sync: `business/orders:read` "+ "for payments, orders, refunds, and payment links, `business/payouts:read` for "+ "payouts and payout entries, `business/catalogue:read` for items, categories, "+ "brands, and modifier groups, `business/locations:read` for locations, "+ "`business/staff:read` for staff, and `business/devices:read` for card machines."+ ),+ docsUrl="https://posthog.com/docs/cdp/sources/yoco",iconPath="/static/services/yoco.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ keywords=["card machine", "payments", "south africa"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ caption=f"Create a key in the [Yoco Developer Console]({YOCO_DEVELOPER_CONSOLE_URL}).",+ secret=True,+ ),+ ],+ ),+ releaseStatus=ReleaseStatus.ALPHA,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/yoco/tests/test_yoco.py b/products/warehouse_sources/backend/temporal/data_imports/sources/yoco/tests/test_yoco.pynew file mode 100644index 000000000000..ccece13f5ee5--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/yoco/tests/test_yoco.py@@ -0,0 +1,442 @@+from datetime import UTC, datetime+from typing import Any, cast++import pytest+from freezegun import freeze_time+from unittest.mock import MagicMock, Mock, patch++from parameterized import parameterized+from requests import Request++from products.warehouse_sources.backend.temporal.data_imports.sources.yoco.settings import (+ DEFAULT_PAGE_SIZE,+ MAX_FILTER_WINDOW,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.yoco.yoco import (+ YocoCursorPaginator,+ YocoResumeConfig,+ _client_config,+ get_endpoint_permissions,+ get_resource,+ validate_credentials,+ yoco_source,+)+++def _page(next_cursor: Any) -> Mock:+ response = Mock()+ response.json.return_value = {"data": [], "next_cursor": next_cursor}+ return response+++class _FakeResource:+ def __init__(self, name: str, rows: list[dict]) -> None:+ self.name = name+ self._rows = rows++ def add_map(self, mapper):+ self._rows = [mapper(dict(row)) for row in self._rows]+ return self++ def __iter__(self):+ return iter(self._rows)+++class TestYocoPaginator:+ def test_cursor_pages_resend_window_bounds(self) -> None:+ # Yoco echoes filters rather than encoding them in the cursor, so a page that drops the+ # window bounds would walk the merchant's entire history on every incremental sync.+ paginator = YocoCursorPaginator(+ limit=DEFAULT_PAGE_SIZE,+ date_field="updated_at",+ window_start=datetime(2026, 1, 1, tzinfo=UTC),+ window_end=datetime(2026, 1, 20, tzinfo=UTC),+ )+ request = Request()+ paginator.init_request(request)+ assert request.params == {+ "limit": DEFAULT_PAGE_SIZE,+ "updated_at__gte": "2026-01-01T00:00:00Z",+ "updated_at__lte": "2026-01-20T00:00:00Z",+ }++ paginator.update_state(_page("cursor-2"))+ paginator.update_request(request)+ assert paginator.has_next_page is True+ assert request.params == {+ "limit": DEFAULT_PAGE_SIZE,+ "cursor": "cursor-2",+ "updated_at__gte": "2026-01-01T00:00:00Z",+ "updated_at__lte": "2026-01-20T00:00:00Z",+ }++ def test_window_advances_until_the_final_bound(self) -> None:+ # Yoco rejects a range wider than 31 days, so an older watermark must be walked in+ # windows; stopping after the first one would silently truncate the sync.+ paginator = YocoCursorPaginator(+ limit=DEFAULT_PAGE_SIZE,+ date_field="created_at",+ window_start=datetime(2026, 1, 1, tzinfo=UTC),+ window_end=datetime(2026, 4, 1, tzinfo=UTC),+ )+ request = Request()+ paginator.init_request(request)++ windows = [(request.params["created_at__gte"], request.params["created_at__lte"])]+ while True:+ paginator.update_state(_page(None))+ if not paginator.has_next_page:+ break+ paginator.update_request(request)+ windows.append((request.params["created_at__gte"], request.params["created_at__lte"]))++ assert windows == [+ ("2026-01-01T00:00:00Z", "2026-02-01T00:00:00Z"),+ ("2026-02-01T00:00:00Z", "2026-03-04T00:00:00Z"),+ ("2026-03-04T00:00:00Z", "2026-04-01T00:00:00Z"),+ ]+ # The cursor from the previous window must not leak into the next one.+ assert "cursor" not in request.params++ def test_no_window_is_plain_cursor_pagination(self) -> None:+ paginator = YocoCursorPaginator(limit=DEFAULT_PAGE_SIZE)+ request = Request()+ paginator.init_request(request)+ assert request.params == {"limit": DEFAULT_PAGE_SIZE}++ paginator.update_state(_page("cursor-2"))+ assert paginator.has_next_page is True+ paginator.update_state(_page(None))+ assert paginator.has_next_page is False++ @parameterized.expand(+ [+ ("null_cursor", {"data": [], "next_cursor": None}, False),+ ("missing_cursor", {"data": []}, False),+ ("empty_cursor", {"data": [], "next_cursor": ""}, False),+ ("populated_cursor", {"data": [], "next_cursor": "abc"}, True),+ ]+ )+ def test_termination_on_next_cursor(self, _name: str, body: dict, expected: bool) -> None:+ paginator = YocoCursorPaginator(limit=DEFAULT_PAGE_SIZE)+ response = Mock()+ response.json.return_value = body+ paginator.update_state(response)+ assert paginator.has_next_page is expected++ def test_resume_state_round_trip_restores_cursor_and_window(self) -> None:+ paginator = YocoCursorPaginator(+ limit=DEFAULT_PAGE_SIZE,+ date_field="updated_at",+ window_start=datetime(2026, 1, 1, tzinfo=UTC),+ window_end=datetime(2026, 6, 1, tzinfo=UTC),+ )+ paginator.update_state(_page("cursor-9"))+ state = paginator.get_resume_state()+ assert state == {+ "cursor": "cursor-9",+ "window_start": "2026-01-01T00:00:00Z",+ "window_end": "2026-02-01T00:00:00Z",+ }++ resumed = YocoCursorPaginator(+ limit=DEFAULT_PAGE_SIZE,+ date_field="updated_at",+ window_start=datetime(2026, 1, 1, tzinfo=UTC),+ window_end=datetime(2026, 6, 1, tzinfo=UTC),+ )+ resumed.set_resume_state(cast(dict[str, Any], state))+ request = Request()+ resumed.init_request(request)+ assert request.params["cursor"] == "cursor-9"+ assert request.params["updated_at__gte"] == "2026-01-01T00:00:00Z"+ # Resuming must keep walking the remaining windows, not stop at the resumed one.+ resumed.update_state(_page(None))+ assert resumed.has_next_page is True++ def test_no_resume_state_once_exhausted(self) -> None:+ paginator = YocoCursorPaginator(limit=DEFAULT_PAGE_SIZE)+ paginator.update_state(_page(None))+ assert paginator.get_resume_state() is None+++class TestYocoResources:+ @freeze_time("2026-05-01T00:00:00Z")+ def test_incremental_resource_windows_from_the_watermark(self) -> None:+ resource = cast(+ dict[str, Any],+ get_resource(+ "payments",+ should_use_incremental_field=True,+ incremental_field="updated_at",+ db_incremental_field_last_value=datetime(2026, 4, 1, tzinfo=UTC),+ ),+ )+ assert resource["write_disposition"] == {"disposition": "merge", "strategy": "upsert"}+ request = Request()+ resource["endpoint"]["paginator"].init_request(request)+ assert request.params["updated_at__gte"] == "2026-04-01T00:00:00Z"+ assert request.params["updated_at__lte"] == "2026-05-01T00:00:00Z"++ def test_window_never_exceeds_the_api_maximum(self) -> None:+ with freeze_time("2026-05-01T00:00:00Z"):+ resource = cast(+ dict[str, Any],+ get_resource(+ "payments",+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2020, 1, 1, tzinfo=UTC),+ ),+ )+ request = Request()+ resource["endpoint"]["paginator"].init_request(request)+ start = datetime.fromisoformat(request.params["updated_at__gte"].replace("Z", "+00:00"))+ end = datetime.fromisoformat(request.params["updated_at__lte"].replace("Z", "+00:00"))+ assert end - start == MAX_FILTER_WINDOW++ def test_first_incremental_sync_sends_no_date_filter(self) -> None:+ # With no watermark there is nothing to window from; sending a bogus lower bound would+ # make the first sync walk years of 31-day windows instead of one cursor pass.+ resource = cast(+ dict[str, Any],+ get_resource("payments", should_use_incremental_field=True, db_incremental_field_last_value=None),+ )+ request = Request()+ resource["endpoint"]["paginator"].init_request(request)+ assert request.params == {"limit": DEFAULT_PAGE_SIZE}++ def test_full_refresh_resource_replaces_and_sends_no_date_filter(self) -> None:+ resource = cast(dict[str, Any], get_resource("payments", should_use_incremental_field=False))+ assert resource["write_disposition"] == "replace"+ request = Request()+ resource["endpoint"]["paginator"].init_request(request)+ assert request.params == {"limit": DEFAULT_PAGE_SIZE}++ @parameterized.expand(+ [+ ("user_choice_honoured", "payments", "created_at", "created_at__gte"),+ ("unadvertised_field_falls_back", "payments", "closed_at", "updated_at__gte"),+ ("endpoint_without_updated_at", "modifier_groups", None, "created_at__gte"),+ ]+ )+ @freeze_time("2026-05-01T00:00:00Z")+ def test_incremental_field_selection(+ self, _name: str, endpoint: str, incremental_field: str | None, expected_param: str+ ) -> None:+ resource = cast(+ dict[str, Any],+ get_resource(+ endpoint,+ should_use_incremental_field=True,+ incremental_field=incremental_field,+ db_incremental_field_last_value=datetime(2026, 4, 1, tzinfo=UTC),+ ),+ )+ request = Request()+ resource["endpoint"]["paginator"].init_request(request)+ assert expected_param in request.params++ def test_endpoint_without_incremental_fields_stays_full_refresh(self) -> None:+ resource = cast(+ dict[str, Any],+ get_resource(+ "locations",+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 4, 1, tzinfo=UTC),+ ),+ )+ assert resource["write_disposition"] == "replace"+ request = Request()+ resource["endpoint"]["paginator"].init_request(request)+ assert request.params == {"limit": DEFAULT_PAGE_SIZE}++ def test_get_resource_rejects_fanout_endpoint(self) -> None:+ with pytest.raises(ValueError, match="Fan-out endpoint"):+ get_resource("payout_entries", should_use_incremental_field=False)++ def test_client_config_pins_host_and_blocks_redirects(self) -> None:+ # A redirect off api.yoco.com would otherwise replay the bearer token to another host.+ config = _client_config("yoco-key", DEFAULT_PAGE_SIZE)+ assert config["allowed_hosts"] == []+ assert config["allow_redirects"] is False+ assert config["auth"] == {"type": "bearer", "token": "yoco-key"}+++class TestYocoSource:+ @parameterized.expand(+ [+ ("incremental_defers_watermark", True, "desc"),+ ("full_refresh", False, "asc"),+ ]+ )+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.yoco.yoco.rest_api_resource")+ def test_sort_mode_and_partitioning(+ self, _name: str, should_use_incremental_field: bool, expected: str, _mock_resource: MagicMock+ ) -> None:+ response = yoco_source(+ api_key="key",+ endpoint="payments",+ team_id=1,+ job_id="job-1",+ should_use_incremental_field=should_use_incremental_field,+ )+ # Yoco documents no page ordering, so the watermark must only be committed once the run+ # completes — "asc" would advance it past rows the run never fetched.+ assert response.sort_mode == expected+ assert response.primary_keys == ["id"]+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["created_at"]++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.yoco.yoco.rest_api_resource")+ def test_resume_state_seeds_the_paginator(self, mock_resource: MagicMock) -> None:+ manager = MagicMock()+ manager.can_resume.return_value = True+ manager.load_state.return_value = YocoResumeConfig(+ cursor="cursor-4", window_start="2026-02-01T00:00:00Z", window_end="2026-03-01T00:00:00Z"+ )++ yoco_source(+ api_key="key",+ endpoint="payments",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),+ )++ assert mock_resource.call_args.kwargs["initial_paginator_state"] == {+ "cursor": "cursor-4",+ "window_start": "2026-02-01T00:00:00Z",+ "window_end": "2026-03-01T00:00:00Z",+ }++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.yoco.yoco.rest_api_resource")+ def test_resume_hook_saves_only_advancing_state(self, mock_resource: MagicMock) -> None:+ manager = MagicMock()+ manager.can_resume.return_value = False++ yoco_source(api_key="key", endpoint="payments", team_id=1, job_id="job-1", resumable_source_manager=manager)+ resume_hook = mock_resource.call_args.kwargs["resume_hook"]++ resume_hook({"cursor": "cursor-7"})+ assert manager.save_state.call_args.args[0] == YocoResumeConfig(cursor="cursor-7")++ manager.save_state.reset_mock()+ resume_hook(None)+ resume_hook({})+ manager.save_state.assert_not_called()++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.yoco.yoco.build_dependent_resource")+ def test_payout_entries_fanout_wiring(self, mock_build: MagicMock) -> None:+ mock_build.return_value = iter([])++ response = yoco_source(api_key="key", endpoint="payout_entries", team_id=1, job_id="job-1")++ kwargs = mock_build.call_args.kwargs+ assert kwargs["child_endpoint"] == "payout_entries"+ assert kwargs["fanout"].parent_name == "payouts"+ assert kwargs["fanout"].resolve_param == "payout_id"+ # The cursor paginator already sends `limit`; a second size param would be undocumented.+ assert kwargs["page_size_param"] is None+ assert kwargs["should_use_incremental_field"] is False+ # `id` is only documented as unique within its payout, and this table aggregates entries+ # from every payout, so the parent id has to be part of the key.+ assert response.primary_keys == ["payout_id", "id"]++ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources"+ )+ def test_payout_entries_rows_carry_the_parent_id(self, mock_resources: MagicMock) -> None:+ mock_resources.return_value = [+ _FakeResource("payouts", [{"id": "po_1"}]),+ _FakeResource("payout_entries", [{"id": "pe_1", "payout_id": "po_1", "type": "payment"}]),+ ]++ response = yoco_source(api_key="key", endpoint="payout_entries", team_id=1, job_id="job-1")++ assert list(cast(Any, response.items())) == [{"id": "pe_1", "payout_id": "po_1", "type": "payment"}]++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.yoco.yoco.build_dependent_resource")+ def test_payout_entries_fanout_resume_round_trip(self, mock_build: MagicMock) -> None:+ mock_build.return_value = iter([])+ manager = MagicMock()+ manager.can_resume.return_value = True+ manager.load_state.return_value = YocoResumeConfig(+ completed=["/v1/payouts/po_1/payout_entries"],+ current="/v1/payouts/po_2/payout_entries",+ child_state={"cursor": "cursor-2"},+ )++ yoco_source(+ api_key="key",+ endpoint="payout_entries",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=manager,+ )++ kwargs = mock_build.call_args.kwargs+ assert kwargs["initial_paginator_state"] == {+ "completed": ["/v1/payouts/po_1/payout_entries"],+ "current": "/v1/payouts/po_2/payout_entries",+ "child_state": {"cursor": "cursor-2"},+ }++ kwargs["resume_hook"]({"completed": ["a"], "current": "b", "child_state": {"cursor": "c"}})+ assert manager.save_state.call_args.args[0] == YocoResumeConfig(+ completed=["a"], current="b", child_state={"cursor": "c"}+ )+++class TestYocoCredentials:+ @parameterized.expand(+ [+ # A key scoped only to the catalogue still authenticates — 403 must not block setup.+ (200, True, None),+ (403, True, None),+ (401, False, "rejected the API key"),+ (500, False, "unexpected status code"),+ ]+ )+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.yoco.yoco.make_tracked_session")+ def test_validate_credentials_status_mapping(+ self, status: int, expected_valid: bool, fragment: str | None, mock_session: MagicMock+ ) -> None:+ mock_session.return_value.get.return_value = Mock(status_code=status)++ is_valid, message = validate_credentials("yoco-key")++ assert is_valid is expected_valid+ if fragment is None:+ assert message is None+ else:+ assert message is not None and fragment in message++ call = mock_session.return_value.get.call_args+ assert call.args[0] == "https://api.yoco.com/v1/payments/"+ assert call.kwargs["headers"]["Authorization"] == "Bearer yoco-key"+ assert mock_session.call_args.kwargs["allow_redirects"] is False++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.yoco.yoco.make_tracked_session")+ def test_endpoint_permissions_name_the_missing_scope(self, mock_session: MagicMock) -> None:+ def _get(url: str, **_kwargs: Any) -> Mock:+ return Mock(status_code=403 if "/v1/payouts/" in url else 200)++ mock_session.return_value.get.side_effect = _get++ permissions = get_endpoint_permissions("yoco-key", ["payments", "payouts", "payout_entries"])++ assert permissions["payments"] is None+ assert permissions["payouts"] is not None and "business/payouts:read" in permissions["payouts"]+ # Payout entries can only be reached through a payout id, so the parent answers for them.+ assert permissions["payout_entries"] is not None and "business/payouts:read" in permissions["payout_entries"]+ assert mock_session.return_value.get.call_count == 2++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.yoco.yoco.make_tracked_session")+ def test_endpoint_permissions_treat_transport_failures_as_reachable(self, mock_session: MagicMock) -> None:+ # A throttle or network blip is not a missing scope — reporting one would push users to+ # deselect tables they can actually sync.+ mock_session.return_value.get.side_effect = Exception("connection reset")++ assert get_endpoint_permissions("yoco-key", ["payments"]) == {"payments": None}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/yoco/tests/test_yoco_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/yoco/tests/test_yoco_source.pynew file mode 100644index 000000000000..59ed5afc1198--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/yoco/tests/test_yoco_source.py@@ -0,0 +1,135 @@+import pytest+from unittest import mock++from posthog.schema import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)++from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.yoco import YocoSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.yoco.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.yoco.source import YocoSource+from products.warehouse_sources.backend.temporal.data_imports.sources.yoco.yoco import YocoResumeConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestYocoSource:+ def setup_method(self) -> None:+ self.source = YocoSource()+ self.team_id = 123+ self.config = YocoSourceConfig(api_key="yoco-key")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.YOCO++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "Yoco"+ assert config.category == DataWarehouseSourceCategory.PAYMENTS___BILLING+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.iconPath == "/static/services/yoco.png"+ # The source ships visible — a truthy unreleasedSource hides it from every user.+ assert not config.unreleasedSource++ def test_api_key_field_is_a_secret_password(self) -> None:+ config = self.source.get_source_config+ assert [f.name for f in config.fields] == ["api_key"]+ field = config.fields[0]+ assert isinstance(field, SourceFieldInputConfig)+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_get_schemas_endpoints(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ @pytest.mark.parametrize(+ "name,expected_fields",+ [+ ("payments", ["updated_at", "created_at"]),+ ("orders", ["updated_at", "created_at"]),+ ("payouts", ["updated_at", "created_at"]),+ # Modifier groups have no updated_at at all, so only created_at is filterable.+ ("modifier_groups", ["created_at"]),+ # Locations and payout entries take no date filters — client-side filtering would+ # cost a full scan per sync, so they stay full refresh.+ ("locations", []),+ ("payout_entries", []),+ ],+ )+ def test_get_schemas_incremental_fields(self, name: str, expected_fields: list[str]) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ assert [f["field"] for f in schemas[name].incremental_fields] == expected_fields+ assert schemas[name].supports_incremental is bool(expected_fields)++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["payments"])+ assert [s.name for s in schemas] == ["payments"]++ @pytest.mark.parametrize(+ "observed_error,expect_match",+ [+ ("401 Client Error: Unauthorized for url: https://api.yoco.com/v1/payments/", True),+ ("403 Client Error: Forbidden for url: https://api.yoco.com/v1/payouts/", True),+ ("500 Server Error: Internal Server Error for url: https://api.yoco.com/v1/payments/", False),+ ],+ )+ def test_non_retryable_errors_match_auth_failures_only(self, observed_error: str, expect_match: bool) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable) is expect_match++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.yoco.source.api_client")+ def test_validate_credentials_plumbs_api_key(self, mock_client: mock.MagicMock) -> None:+ mock_client.validate_credentials.return_value = (True, None)+ assert self.source.validate_credentials(self.config, self.team_id) == (True, None)+ assert mock_client.validate_credentials.call_args.args == ("yoco-key",)++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.yoco.source.api_client")+ def test_get_endpoint_permissions_plumbs_endpoints(self, mock_client: mock.MagicMock) -> None:+ mock_client.get_endpoint_permissions.return_value = {"payments": None}+ assert self.source.get_endpoint_permissions(self.config, self.team_id, ["payments"]) == {"payments": None}+ assert mock_client.get_endpoint_permissions.call_args.args == ("yoco-key", ["payments"])++ def test_get_resumable_source_manager_bound_to_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert manager._data_class is YocoResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.yoco.source.api_client")+ def test_source_for_pipeline_plumbs_arguments(self, mock_client: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "payments"+ inputs.team_id = self.team_id+ inputs.job_id = "job-1"+ inputs.should_use_incremental_field = True+ inputs.incremental_field = "created_at"+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = mock_client.yoco_source.call_args.kwargs+ assert kwargs["api_key"] == "yoco-key"+ assert kwargs["endpoint"] == "payments"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ # The user's chosen cursor must reach the request layer, not the endpoint default.+ assert kwargs["incremental_field"] == "created_at"+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.yoco.source.api_client")+ def test_source_for_pipeline_omits_watermark_when_not_incremental(self, mock_client: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "payments"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_client.yoco_source.call_args.kwargs["db_incremental_field_last_value"] is None++ def test_canonical_descriptions_cover_endpoints(self) -> None:+ descriptions = self.source.get_canonical_descriptions()+ assert set(descriptions.keys()) == set(ENDPOINTS)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/yoco/yoco.py b/products/warehouse_sources/backend/temporal/data_imports/sources/yoco/yoco.pynew file mode 100644index 000000000000..df36a18a5ab5--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/yoco/yoco.py@@ -0,0 +1,395 @@+from collections.abc import Callable, Iterable+from datetime import UTC, datetime+from typing import Any, Optional, cast++from requests import Request, Response++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import (+ coerce_datetime_to_utc,+)+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.fanout import (+ build_dependent_resource,+)+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 (+ ClientConfig,+ Endpoint,+ EndpointResource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SortMode, SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.yoco.settings import (+ ENDPOINT_SCOPES,+ MAX_FILTER_WINDOW,+ YOCO_BASE_URL,+ YOCO_ENDPOINTS,+ YocoEndpointConfig,+)++REQUEST_TIMEOUT_SECONDS = 30+++@frozen+class YocoResumeConfig:+ """Paginator checkpoint.++ Top-level endpoints save the next `cursor` plus the date window it belongs to. The+ payout-entries fan-out saves the framework's dependent-resource shape instead: which+ parent payouts are done, which one is in flight, and that parent's cursor.+ """++ cursor: Optional[str] = None+ window_start: Optional[str] = None+ window_end: Optional[str] = None+ completed: Optional[list[str]] = None+ current: Optional[str] = None+ child_state: Optional[dict[str, Any]] = None+++def _format_datetime(value: datetime) -> str:+ # Whole seconds only, which rounds the lower bound down. `__gte` is inclusive anyway, so a+ # sync re-reads a few boundary rows (the merge dedupes them) rather than skipping any.+ return value.strftime("%Y-%m-%dT%H:%M:%SZ")+++def _parse_datetime(value: str) -> Optional[datetime]:+ try:+ return coerce_datetime_to_utc(datetime.fromisoformat(value.replace("Z", "+00:00")))+ except ValueError:+ return None+++class YocoCursorPaginator(BasePaginator):+ """Cursor pagination that optionally walks a date range in windows of at most 31 days.++ Yoco returns an opaque `next_cursor` alongside each page and echoes the request filters,+ so every page re-sends the window bounds together with the cursor. Because the API refuses+ a `created_at`/`updated_at` range wider than 31 days, a watermark older than that cannot be+ expressed as a single `__gte`: once a window's pages run out the paginator advances to the+ next window instead of stopping. With no window set (full refresh, or the first incremental+ sync where there is no watermark yet) it is plain cursor pagination over the whole history.+ """++ def __init__(+ self,+ limit: int,+ date_field: Optional[str] = None,+ window_start: Optional[datetime] = None,+ window_end: Optional[datetime] = None,+ ) -> None:+ super().__init__()+ self.limit = limit+ self.date_field = date_field if (window_start is not None and window_end is not None) else None+ self._final_end = window_end if self.date_field else None+ self._window_start = window_start if self.date_field else None+ self._window_end: Optional[datetime] = None+ if self._window_start is not None and self._final_end is not None:+ self._window_end = min(self._window_start + MAX_FILTER_WINDOW, self._final_end)+ self._cursor: Optional[str] = None++ def _apply_params(self, request: Request) -> None:+ if request.params is None:+ request.params = {}+ request.params["limit"] = self.limit+ if self._cursor is None:+ request.params.pop("cursor", None)+ else:+ request.params["cursor"] = self._cursor+ if self.date_field and self._window_start is not None and self._window_end is not None:+ request.params[f"{self.date_field}__gte"] = _format_datetime(self._window_start)+ request.params[f"{self.date_field}__lte"] = _format_datetime(self._window_end)++ def init_request(self, request: Request) -> None:+ self._apply_params(request)++ def update_request(self, request: Request) -> None:+ self._apply_params(request)++ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:+ next_cursor: Any = None+ try:+ body = response.json()+ except ValueError:+ body = None+ if isinstance(body, dict):+ next_cursor = body.get("next_cursor")++ if next_cursor:+ self._cursor = str(next_cursor)+ self._has_next_page = True+ return++ self._cursor = None+ self._has_next_page = self._advance_window()++ def _advance_window(self) -> bool:+ if self._window_end is None or self._final_end is None or self._window_end >= self._final_end:+ return False+ # Windows share their boundary instant because both bounds are inclusive; the merge on+ # primary key collapses the handful of rows that lands in two windows.+ self._window_start = self._window_end+ self._window_end = min(self._window_end + MAX_FILTER_WINDOW, self._final_end)+ return True++ def get_resume_state(self) -> Optional[dict[str, Any]]:+ if not self._has_next_page:+ return None+ state: dict[str, Any] = {}+ if self._cursor is not None:+ state["cursor"] = self._cursor+ if self.date_field and self._window_start is not None and self._window_end is not None:+ state["window_start"] = _format_datetime(self._window_start)+ state["window_end"] = _format_datetime(self._window_end)+ return state or None++ def set_resume_state(self, state: dict[str, Any]) -> None:+ cursor = state.get("cursor")+ self._cursor = str(cursor) if cursor else None+ window_start = state.get("window_start")+ window_end = state.get("window_end")+ if self.date_field and window_start and window_end:+ parsed_start = _parse_datetime(str(window_start))+ parsed_end = _parse_datetime(str(window_end))+ if parsed_start is not None and parsed_end is not None:+ self._window_start = parsed_start+ self._window_end = parsed_end+ self._has_next_page = True+++def _client_config(api_key: str, limit: int) -> ClientConfig:+ return {+ "base_url": YOCO_BASE_URL,+ "auth": {"type": "bearer", "token": api_key},+ "headers": {"Accept": "application/json"},+ # Pin every request (and its bearer token) to api.yoco.com and refuse redirects, so a+ # server-side 3xx can never replay the credential off-host.+ "allowed_hosts": [],+ "allow_redirects": False,+ "paginator": YocoCursorPaginator(limit=limit),+ "request_timeout": REQUEST_TIMEOUT_SECONDS,+ }+++def _resolve_date_field(config: YocoEndpointConfig, incremental_field: Optional[str]) -> Optional[str]:+ advertised = {f["field"] for f in config.incremental_fields}+ if incremental_field in advertised:+ return incremental_field+ return config.default_incremental_field+++def get_resource(+ endpoint: str,+ should_use_incremental_field: bool,+ incremental_field: Optional[str] = None,+ db_incremental_field_last_value: Optional[Any] = None,+) -> EndpointResource:+ config = YOCO_ENDPOINTS[endpoint]+ if config.fanout:+ raise ValueError(f"Fan-out endpoint '{endpoint}' must use the fan-out path")++ use_incremental = should_use_incremental_field and bool(config.incremental_fields)+ window_start = coerce_datetime_to_utc(db_incremental_field_last_value) if use_incremental else None++ endpoint_config: Endpoint = {+ "path": config.path,+ "params": {},+ "data_selector": "data",+ # The `data` envelope is documented on every list endpoint, so a response without it+ # means the shape changed — fail loud instead of silently syncing zero rows.+ "data_selector_required": True,+ "paginator": YocoCursorPaginator(+ limit=config.page_size,+ date_field=_resolve_date_field(config, incremental_field) if use_incremental else None,+ window_start=window_start,+ window_end=datetime.now(UTC) if window_start is not None else None,+ ),+ }++ return {+ "name": config.name,+ "table_name": config.name,+ "write_disposition": {"disposition": "merge", "strategy": "upsert"} if use_incremental else "replace",+ "endpoint": endpoint_config,+ "table_format": "delta",+ }+++def _source_response(+ config: YocoEndpointConfig,+ items_fn: Callable[[], Iterable[Any]],+ sort_mode: SortMode,+) -> SourceResponse:+ return SourceResponse(+ name=config.name,+ items=items_fn,+ primary_keys=config.primary_key,+ sort_mode=sort_mode,+ 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,+ )+++def yoco_source(+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: Optional[ResumableSourceManager[YocoResumeConfig]] = None,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: Optional[str] = None,+) -> SourceResponse:+ config = YOCO_ENDPOINTS[endpoint]+ initial_paginator_state: Optional[dict[str, Any]] = None+ resume_state: Optional[YocoResumeConfig] = None++ if resumable_source_manager is not None and resumable_source_manager.can_resume():+ resume_state = resumable_source_manager.load_state()++ if config.fanout:+ if resume_state is not None and resume_state.completed is not None:+ initial_paginator_state = {+ "completed": resume_state.completed,+ "current": resume_state.current,+ "child_state": resume_state.child_state,+ }++ def save_fanout_checkpoint(state: Optional[dict[str, Any]]) -> None:+ if resumable_source_manager is None or not state:+ return+ resumable_source_manager.save_state(+ YocoResumeConfig(+ completed=list(state.get("completed") or []),+ current=state.get("current"),+ child_state=state.get("child_state"),+ )+ )++ dependent_resource = cast(+ Iterable[Any],+ build_dependent_resource(+ endpoint_configs=YOCO_ENDPOINTS,+ child_endpoint=endpoint,+ fanout=config.fanout,+ client_config=_client_config(api_key, config.page_size),+ path_format_values={},+ team_id=team_id,+ job_id=job_id,+ db_incremental_field_last_value=None,+ should_use_incremental_field=False,+ parent_endpoint_extra={"data_selector": "data", "data_selector_required": True},+ child_endpoint_extra={"data_selector": "data", "data_selector_required": True},+ # The client paginator already sends `limit`, and it is the one that knows how+ # to read `next_cursor`, so the fan-out helper must not add its own size param.+ page_size_param=None,+ resume_hook=save_fanout_checkpoint if resumable_source_manager is not None else None,+ initial_paginator_state=initial_paginator_state,+ ),+ )+ return _source_response(config, lambda: dependent_resource, sort_mode="asc")++ if resume_state is not None and (resume_state.cursor or resume_state.window_start):+ initial_paginator_state = {+ "cursor": resume_state.cursor,+ "window_start": resume_state.window_start,+ "window_end": resume_state.window_end,+ }++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Only persist while there is another page or window to resume to; the Redis TTL+ # cleans up on completion.+ if resumable_source_manager is None or not state:+ return+ resumable_source_manager.save_state(+ YocoResumeConfig(+ cursor=state.get("cursor"),+ window_start=state.get("window_start"),+ window_end=state.get("window_end"),+ )+ )++ rest_config: RESTAPIConfig = {+ "client": _client_config(api_key, config.page_size),+ "resource_defaults": {},+ "resources": [+ get_resource(endpoint, should_use_incremental_field, incremental_field, db_incremental_field_last_value)+ ],+ }++ resource = rest_api_resource(+ rest_config,+ team_id,+ job_id,+ db_incremental_field_last_value,+ resume_hook=save_checkpoint if resumable_source_manager is not None else None,+ initial_paginator_state=initial_paginator_state,+ )++ # Yoco documents no ordering for its cursor pages, so an incremental sync runs with desc+ # semantics: the pipeline holds the watermark until the run finishes rather than advancing+ # it per batch, and an interrupted run repeats its window instead of skipping rows it+ # never fetched.+ sort_mode: SortMode = "desc" if (should_use_incremental_field and config.incremental_fields) else "asc"+ return _source_response(config, lambda: resource, sort_mode=sort_mode)+++def _probe(api_key: str, path: str) -> Response:+ session = make_tracked_session(redact_values=(api_key,), allow_redirects=False)+ return session.get(+ f"{YOCO_BASE_URL}{path}",+ headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},+ params={"limit": 1},+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+++def validate_credentials(api_key: str) -> tuple[bool, str | None]:+ response = _probe(api_key, YOCO_ENDPOINTS["payments"].path)+ # 403 means the token is genuine but lacks `business/orders:read`. Keys can legitimately be+ # scoped to only the catalogue or payouts, so that is not a bad credential — the per-table+ # check reports which tables the key can actually reach.+ if response.status_code in (200, 403):+ return True, None+ if response.status_code == 401:+ return False, "Yoco rejected the API key. Create a new key in the Yoco Developer Console and reconnect."+ return False, f"Yoco API returned an unexpected status code: {response.status_code}"+++def get_endpoint_permissions(api_key: str, endpoints: list[str]) -> dict[str, str | None]:+ permissions: dict[str, str | None] = {}+ # Several endpoints share a scope, so probe each distinct path once.+ probed: dict[str, int] = {}+ for name in endpoints:+ config = YOCO_ENDPOINTS.get(name)+ if config is None:+ permissions[name] = None+ continue+ # Payout entries can only be reached through a payout id; the parent list endpoint+ # needs the same scope, so probing it answers for both.+ path = YOCO_ENDPOINTS[config.fanout.parent_name].path if config.fanout else config.path+ if path not in probed:+ try:+ probed[path] = _probe(api_key, path).status_code+ except Exception:+ # A throttle or network blip is not a missing scope — report reachable and let+ # the sync surface a real failure.+ probed[path] = 200+ status = probed[path]+ if status == 403:+ scope = ENDPOINT_SCOPES.get(name)+ permissions[name] = (+ f"Your Yoco API key is missing the `{scope}` scope." if scope else "Your Yoco API key lacks access."+ )+ else:+ permissions[name] = None+ return permissions