: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 easybill import source (#84464)
Tom Owers7227332fe3a8
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/easybill/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/easybill/canonical_descriptions.pynew file mode 100644index 000000000000..e1032f2ca6e0--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/easybill/canonical_descriptions.py@@ -0,0 +1,133 @@+"""Canonical, documentation-sourced descriptions for easybill endpoints and columns.++Sourced from easybill's own OpenAPI spec, served at https://api.easybill.de/rest/v1/swagger.json+and rendered at https://www.easybill.de/api/. Keyed by the resource names in `settings.py`+`ENDPOINTS`, which match the `ExternalDataSchema.name` of a synced easybill table. Columns absent+here fall back to LLM enrichment.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "Documents": {+ "description": "An easybill document: an invoice, credit note, offer, delivery note, reminder, or one of the other document types distinguished by `type`.",+ "docs_url": "https://www.easybill.de/api/",+ "columns": {+ "id": "Unique identifier for the document.",+ "type": "Document type, e.g. INVOICE, CREDIT, OFFER, DELIVERY, REMINDER, STORNO.",+ "number": "The document number shown to the customer.",+ "title": "Title of the document.",+ "customer_id": "ID of the customer the document was issued to.",+ "project_id": "ID of the project the document is linked to, if any.",+ "contact_id": "ID of the customer contact the document was issued to, if any.",+ "amount": "Total amount in cents (e.g. 150 = 1.50 EUR).",+ "amount_net": "Total net amount in cents (e.g. 150 = 1.50 EUR).",+ "currency": "Currency of the document.",+ "status": "Document status. Only meaningful for types that use one (DELIVERY, ORDER, CHARGE and similar).",+ "is_draft": "Whether the document has not yet been finalized.",+ "is_archive": "Whether the document has been archived.",+ "document_date": "The date shown on the document. Defaults to today when omitted; can be null for drafts.",+ "due_date": "Date payment is due.",+ "paid_at": "Date the document was paid, if any.",+ "paid_amount": "Amount already paid, in cents.",+ "created_at": "Time the document was created.",+ "edited_at": "Time the document was last edited.",+ "ref_id": "ID of a related document this one references.",+ "cancel_id": "ID of the cancellation (STORNO) document, if this document was cancelled.",+ "root_id": "ID of the root document in a chain of related documents.",+ },+ },+ "DocumentPayments": {+ "description": "A payment recorded against an easybill document.",+ "docs_url": "https://www.easybill.de/api/",+ "columns": {+ "id": "Unique identifier for the payment.",+ "document_id": "ID of the document this payment is recorded against.",+ "amount": "Payment amount in cents (e.g. 150 = 1.50 EUR).",+ "payment_at": "Date the payment was made.",+ "type": "Payment type.",+ "provider": "Payment provider that processed the payment, if any.",+ "reference": "Free-text reference for the payment.",+ "is_overdue_fee": "Whether this payment covers an overdue fee rather than the document amount.",+ },+ },+ "Customers": {+ "description": "An easybill customer record.",+ "docs_url": "https://www.easybill.de/api/",+ "columns": {+ "id": "Unique identifier for the customer.",+ "number": "Customer number, generated automatically if left blank.",+ "supplier_number": "Supplier number, used when the customer is also a supplier.",+ "group_id": "ID of the customer's primary group.",+ "additional_groups_ids": "IDs of any additional groups the customer belongs to.",+ "company_name": "Company name, for business customers.",+ "first_name": "First name, for individual customers.",+ "last_name": "Last name, for individual customers.",+ "display_name": "Display name shown for the customer.",+ "emails": "Email addresses on file for the customer.",+ "phone_1": "Primary phone number.",+ "phone_2": "Secondary phone number.",+ "mobile": "Mobile phone number.",+ "vat_identifier": "VAT identification number.",+ "tax_number": "Tax number.",+ "country": "Country of the customer's billing address.",+ "city": "City of the customer's billing address.",+ "zip_code": "Postal code of the customer's billing address.",+ "street": "Street of the customer's billing address.",+ "created_at": "Date the customer record was created.",+ "updated_at": "Time the customer record was last updated. Not filterable via the list API, so it can't be used as an incremental cursor.",+ "archived": "Whether the customer has been archived.",+ "due_in_days": "Default number of days until payment is due for this customer's documents.",+ },+ },+ "Positions": {+ "description": "An easybill position: an article or service in the catalogue, used as a line item template on documents.",+ "docs_url": "https://www.easybill.de/api/",+ "columns": {+ "id": "Unique identifier for the position.",+ "type": "Position type.",+ "number": "Article/position number.",+ "description": "The position's name or description.",+ "note": "Internal-use note, not shown to customers.",+ "unit": "Unit the position is sold in (e.g. piece, hour).",+ "vat_percent": "VAT percentage applied to the position.",+ "sale_price": "Default sale price in cents (e.g. 150 = 1.50 EUR).",+ "cost_price": "Cost price in cents (e.g. 150 = 1.50 EUR).",+ "quantity": "Default quantity used when adding this position to a document.",+ "group_id": "ID of the position group this position belongs to.",+ "stock": "Whether stock management is active for this position.",+ "stock_count": "Current stock count.",+ "archived": "Whether the position has been archived.",+ },+ },+ "Projects": {+ "description": "An easybill project, used to group time tracking and billing for a customer engagement.",+ "docs_url": "https://www.easybill.de/api/",+ "columns": {+ "id": "Unique identifier for the project.",+ "name": "Project name.",+ "note": "Free-text note about the project.",+ "customer_id": "ID of the customer this project is for.",+ "status": "Project status.",+ "hourly_rate": "Hourly rate in cents (e.g. 150 = 1.50 EUR).",+ "budget_amount": "Project budget in cents (e.g. 150 = 1.50 EUR).",+ "budget_time": "Time budget in minutes (e.g. 90 = 1 hour 30 minutes).",+ "consumed_amount": "Amount consumed against the budget so far, in cents.",+ "consumed_time": "Time consumed against the budget so far, in minutes.",+ "due_at": "Project due date.",+ },+ },+ "CustomerGroups": {+ "description": "A group used to categorize customers, e.g. for group-specific pricing.",+ "docs_url": "https://www.easybill.de/api/",+ "columns": {+ "id": "Unique identifier for the customer group.",+ "name": "Group name.",+ "display_name": "Display name shown for the group.",+ "description": "Free-text description of the group.",+ "number": "Group number, can be chosen freely.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/easybill/easybill.py b/products/warehouse_sources/backend/temporal/data_imports/sources/easybill/easybill.pynew file mode 100644index 000000000000..21182e7bca2d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/easybill/easybill.py@@ -0,0 +1,150 @@+from datetime import date, datetime, timedelta+from typing import Any, Optional++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ PageNumberPaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ Endpoint,+ EndpointResource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.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.easybill.settings import (+ EASYBILL_BASE_URL,+ EASYBILL_ENDPOINTS,+ PAGE_LIMIT,+ EasybillEndpointConfig,+)+++@frozen+class EasybillResumeConfig:+ page: int+++def _coerce_date(value: Any) -> Optional[date]:+ if isinstance(value, datetime):+ return value.date()+ if isinstance(value, date):+ return value+ if isinstance(value, str):+ try:+ return datetime.fromisoformat(value.replace("Z", "+00:00")).date()+ except ValueError:+ return None+ return None+++def date_range_since(value: Any) -> Optional[str]:+ """easybill's date filters take a single day or an inclusive "from,to" range - there's no+ open-ended "since" operator. Overlap the start by a day because the filter is day-granular,+ so a row edited earlier the same day as the last watermark could otherwise be missed."""+ start = _coerce_date(value)+ if start is None:+ return None+ return f"{(start - timedelta(days=1)).isoformat()},{date.today().isoformat()}"+++def _build_endpoint_resource(config: EasybillEndpointConfig, should_use_incremental_field: bool) -> EndpointResource:+ endpoint: Endpoint = {+ "path": config.path,+ "data_selector": "items",+ "params": {"limit": PAGE_LIMIT},+ # `pages` in the response envelope is the max page count, so pagination stops exactly at+ # the last page instead of paying one extra empty-page request per sync.+ "paginator": PageNumberPaginator(base_page=1, page_param="page", total_path="pages"),+ }+ if config.incremental_param and should_use_incremental_field:+ endpoint["incremental"] = {+ "start_param": config.incremental_param,+ "cursor_path": config.incremental_param,+ "convert": date_range_since,+ }++ resource: EndpointResource = {+ "name": config.name,+ "table_name": config.table_name,+ "write_disposition": {"disposition": "merge", "strategy": "upsert"}+ if should_use_incremental_field+ else "replace",+ "endpoint": endpoint,+ "table_format": "delta",+ }+ return resource+++def easybill_source(+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[EasybillResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = EASYBILL_ENDPOINTS[endpoint]++ rest_config: RESTAPIConfig = {+ "client": {+ "base_url": EASYBILL_BASE_URL,+ "auth": {"type": "bearer", "token": api_key},+ },+ "resource_defaults": {},+ "resources": [_build_endpoint_resource(config, should_use_incremental_field)],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume_config = resumable_source_manager.load_state()+ if resume_config is not None:+ initial_paginator_state = {"page": resume_config.page}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Only persist when there's a next page to resume to; the Redis TTL handles cleanup on+ # completion. Saved AFTER a page is yielded so a crash re-yields the last page (merge+ # dedupes on primary_keys) rather than skipping it.+ if state and state.get("page") is not None:+ resumable_source_manager.save_state(EasybillResumeConfig(page=int(state["page"])))++ last_value = db_incremental_field_last_value if should_use_incremental_field else None++ resource = rest_api_resource(+ rest_config,+ team_id,+ job_id,+ last_value,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )++ return SourceResponse(+ name=resource.name,+ items=lambda: resource,+ primary_keys=config.primary_keys,+ sort_mode="asc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="week" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ column_hints=resource.column_hints,+ )+++def validate_credentials(api_key: str) -> bool:+ # A cheap, always-available probe: one page of customers. 200 means the key is genuine.+ ok, _status = validate_via_probe(+ lambda: make_tracked_session(redact_values=(api_key,)),+ f"{EASYBILL_BASE_URL}/customers?limit=1",+ headers={"Authorization": f"Bearer {api_key}"},+ )+ return okdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/easybill/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/easybill/settings.pynew file mode 100644index 000000000000..0f196487c2e4--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/easybill/settings.py@@ -0,0 +1,90 @@+from dataclasses import field+from typing import Optional++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++EASYBILL_BASE_URL = "https://api.easybill.de/rest/v1"++# Every list endpoint accepts the same limit/page params, capped at 1000. Requesting the maximum+# keeps request counts low under easybill's tight per-minute rate limits (10/min on PLUS, 60/min+# on BUSINESS).+PAGE_LIMIT = 1000+++@frozen+class EasybillEndpointConfig:+ name: str+ path: str+ table_name: str+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # A stable, creation-time field for datetime partitioning. None when the endpoint exposes no+ # field that's guaranteed not to change after the row is written.+ partition_key: Optional[str] = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # The query param that filters this endpoint by date, if it reliably tracks record+ # modification (e.g. "edited_at"). None means full refresh: either there's no date filter, or+ # the only one available is a business date (a payment/creation date) that doesn't catch+ # updates to existing rows.+ incremental_param: Optional[str] = None+++def _edited_at_field() -> list[IncrementalField]:+ return [+ {+ "label": "edited_at",+ "type": IncrementalFieldType.DateTime,+ "field": "edited_at",+ "field_type": IncrementalFieldType.DateTime,+ }+ ]+++EASYBILL_ENDPOINTS: dict[str, EasybillEndpointConfig] = {+ # The money table: invoices, credit notes, offers, delivery notes and more, distinguished by+ # `type`. `edited_at` is a real last-modified timestamp, so this is the one endpoint that+ # syncs incrementally.+ "Documents": EasybillEndpointConfig(+ name="Documents",+ path="/documents",+ table_name="documents",+ partition_key="created_at",+ incremental_fields=_edited_at_field(),+ incremental_param="edited_at",+ ),+ "DocumentPayments": EasybillEndpointConfig(+ name="DocumentPayments",+ path="/document-payments",+ table_name="document_payments",+ ),+ # `/customers` only filters by `created_at`, which would miss edits to existing customers, so+ # this stays full refresh rather than syncing on a lossy cursor.+ "Customers": EasybillEndpointConfig(+ name="Customers",+ path="/customers",+ table_name="customers",+ partition_key="created_at",+ ),+ "Positions": EasybillEndpointConfig(+ name="Positions",+ path="/positions",+ table_name="positions",+ ),+ "Projects": EasybillEndpointConfig(+ name="Projects",+ path="/projects",+ table_name="projects",+ ),+ "CustomerGroups": EasybillEndpointConfig(+ name="CustomerGroups",+ path="/customer-groups",+ table_name="customer_groups",+ ),+}++ENDPOINTS = tuple(EASYBILL_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in EASYBILL_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/easybill/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/easybill/source.pyindex 5db34d9da536..333d7b6563a2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/easybill/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/easybill/source.py@@ -1,13 +1,34 @@-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, SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.easybill.easybill import (+ EasybillResumeConfig,+ easybill_source,+ validate_credentials as validate_easybill_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.easybill.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.easybill import (EasybillSourceConfig,)@@ -15,7 +36,12 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class EasybillSource(SimpleSource[EasybillSourceConfig]):+class EasybillSource(ResumableSource[EasybillSourceConfig, EasybillResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ # easybill's REST API has a single, fixed `/rest/v1` base path with no documented version+ # header, query param, or changelog — there is nothing to pin.+ api_docs_url = "https://www.easybill.de/api/"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.EASYBILL@@ -26,8 +52,79 @@ class EasybillSource(SimpleSource[EasybillSourceConfig]):name=SchemaExternalDataSourceType.EASYBILL,category=DataWarehouseSourceCategory.FINANCE___ACCOUNTING,label="easybill",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="Enter your easybill API key to sync your invoices, customers and accounting records into the PostHog data warehouse. Generate a key from your easybill account under **username menu > Profil und Einstellungen**.",iconPath="/static/services/easybill.png",- keywords=["invoicing", "billing", "accounting"],- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/easybill",+ keywords=["invoicing", "billing", "accounting", "germany", "gobd"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.easybill.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.easybill.de": "Your easybill API key is invalid or has expired. Generate a new key from your easybill account and reconnect.",+ "403 Client Error: Forbidden for url: https://api.easybill.de": "Your easybill API key does not have access to this data. Check the key's permissions in your easybill account and reconnect.",+ }++ def get_schemas(+ self,+ config: EasybillSourceConfig,+ 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: EasybillSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ if validate_easybill_credentials(config.api_key):+ return True, None++ return False, "Invalid easybill API key"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[EasybillResumeConfig]:+ return ResumableSourceManager[EasybillResumeConfig](inputs, EasybillResumeConfig)++ def source_for_pipeline(+ self,+ config: EasybillSourceConfig,+ resumable_source_manager: ResumableSourceManager[EasybillResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return easybill_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,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/easybill/tests/test_easybill.py b/products/warehouse_sources/backend/temporal/data_imports/sources/easybill/tests/test_easybill.pynew file mode 100644index 000000000000..b38f8e584363--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/easybill/tests/test_easybill.py@@ -0,0 +1,290 @@+import json+from datetime import UTC, date, datetime+from typing import Any++import pytest+from unittest import mock++import requests+from parameterized import parameterized+from requests import HTTPError, Response++from products.warehouse_sources.backend.temporal.data_imports.sources.easybill.easybill import (+ EasybillResumeConfig,+ date_range_since,+ easybill_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.easybill.settings import EASYBILL_ENDPOINTS++# RESTClient builds its session via make_tracked_session in the rest_client module.+CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+# validate_credentials builds its own tracked session in the easybill module.+EASYBILL_SESSION_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.easybill.easybill.make_tracked_session"+)+++def _response(+ items: list[dict[str, Any]] | None,+ *,+ page: int = 1,+ pages: int = 1,+ status: int = 200,+ body_override: dict[str, Any] | None = None,+) -> Response:+ body: dict[str, Any] = (+ body_override+ if body_override is not None+ else {+ "page": page,+ "pages": pages,+ "limit": 1000,+ "total": len(items or []),+ "items": items or [],+ }+ )+ resp = Response()+ resp.status_code = status+ resp._content = json.dumps(body).encode()+ return resp+++def _make_manager(resume_state: EasybillResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:+ """Wire a mock session and capture each request's params AT SEND TIME.++ ``request.params`` is one dict mutated in place across pages, so inspecting it after the run+ would only show the final state — snapshot a copy when each request is prepared instead.+ """+ session.headers = {}+ param_snapshots: list[dict[str, Any]] = []++ def _prepare(request: Any) -> mock.MagicMock:+ param_snapshots.append(dict(request.params or {}))+ prepared = mock.MagicMock()+ prepared.url = request.url+ return prepared++ session.prepare_request.side_effect = _prepare+ session.send.side_effect = responses+ return param_snapshots+++def _rows(source_response: Any) -> list[dict[str, Any]]:+ return [row for page in source_response.items() for row in page]+++def _source(endpoint: str, manager: mock.MagicMock, **kwargs: Any) -> Any:+ return easybill_source("key", endpoint, team_id=1, job_id="j", resumable_source_manager=manager, **kwargs)+++class TestDateRangeSince:+ @parameterized.expand(+ [+ ("datetime", datetime(2024, 3, 10, 12, 0, tzinfo=UTC), f"2024-03-09,{date.today().isoformat()}"),+ ("date", date(2024, 3, 10), f"2024-03-09,{date.today().isoformat()}"),+ ("iso_string", "2024-03-10T00:00:00+00:00", f"2024-03-09,{date.today().isoformat()}"),+ ("iso_string_z", "2024-03-10T00:00:00Z", f"2024-03-09,{date.today().isoformat()}"),+ ("plain_date_string", "2024-03-10", f"2024-03-09,{date.today().isoformat()}"),+ ("none", None, None),+ ("garbage_string", "not-a-date", None),+ ]+ )+ def test_date_range_since(self, _name: str, value: Any, expected: str | None) -> None:+ assert date_range_since(value) == expected+++class TestIncrementalParams:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_documents_incremental_adds_edited_at_range(self, MockSession) -> None:+ session = MockSession.return_value+ params = _wire(session, [_response([{"id": 1}], pages=1)])++ _rows(+ _source(+ "Documents",+ _make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=date(2024, 3, 10),+ )+ )++ assert params[0]["edited_at"] == f"2024-03-09,{date.today().isoformat()}"+ assert params[0]["limit"] == 1000+ assert params[0]["page"] == 1++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_documents_first_sync_omits_filter(self, MockSession) -> None:+ session = MockSession.return_value+ params = _wire(session, [_response([{"id": 1}], pages=1)])++ _rows(+ _source(+ "Documents",+ _make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=None,+ )+ )++ assert "edited_at" not in params[0]++ @parameterized.expand(["DocumentPayments", "Customers", "Positions", "Projects", "CustomerGroups"])+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_non_incremental_endpoints_never_filter(self, endpoint: str, MockSession) -> None:+ session = MockSession.return_value+ params = _wire(session, [_response([{"id": 1}], pages=1)])++ _rows(+ _source(+ endpoint,+ _make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=date(2024, 3, 10),+ )+ )++ assert "edited_at" not in params[0]+++class TestPagination:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_paginates_until_last_page(self, MockSession) -> None:+ session = MockSession.return_value+ params = _wire(+ session,+ [+ _response([{"id": 1}], page=1, pages=2),+ _response([{"id": 2}], page=2, pages=2),+ ],+ )++ manager = _make_manager()+ rows = _rows(_source("Customers", manager))++ assert [r["id"] for r in rows] == [1, 2]+ assert params[0]["page"] == 1+ assert params[1]["page"] == 2+ assert session.send.call_count == 2+ manager.save_state.assert_called_once_with(EasybillResumeConfig(page=2))++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_single_page_makes_one_request(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(session, [_response([{"id": 1}], page=1, pages=1)])++ manager = _make_manager()+ rows = _rows(_source("Customers", manager))++ assert [r["id"] for r in rows] == [1]+ assert session.send.call_count == 1+ manager.save_state.assert_not_called()++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_empty_first_page_stops(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(session, [_response([], page=1, pages=1)])++ rows = _rows(_source("Customers", _make_manager()))++ assert rows == []+ assert session.send.call_count == 1++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_resumes_from_saved_page(self, MockSession) -> None:+ session = MockSession.return_value+ params = _wire(session, [_response([{"id": 2}], page=2, pages=2)])++ manager = _make_manager(EasybillResumeConfig(page=2))+ rows = _rows(_source("Customers", manager))++ assert [r["id"] for r in rows] == [2]+ assert params[0]["page"] == 2+ assert session.send.call_count == 1+++class TestSourceResponseShape:+ @parameterized.expand(+ [+ ("Documents", "documents", "created_at"),+ ("Customers", "customers", "created_at"),+ ("Positions", "positions", None),+ ("Projects", "projects", None),+ ("CustomerGroups", "customer_groups", None),+ ("DocumentPayments", "document_payments", None),+ ]+ )+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_response_shape(+ self,+ endpoint: str,+ table_name: str,+ partition_key: str | None,+ MockSession,+ ) -> None:+ response = _source(endpoint, _make_manager())+ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ assert response.sort_mode == "asc"+ assert EASYBILL_ENDPOINTS[endpoint].table_name == table_name+ if partition_key is None:+ assert response.partition_mode is None+ assert response.partition_keys is None+ else:+ assert response.partition_mode == "datetime"+ assert response.partition_format == "week"+ assert response.partition_keys == [partition_key]+++class TestValidateCredentials:+ @parameterized.expand([("ok", 200, True), ("unauthorized", 401, False), ("forbidden", 403, False)])+ def test_status_mapping(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(EASYBILL_SESSION_PATCH, return_value=session):+ assert validate_credentials("key") is expected++ def test_network_error_is_false(self) -> None:+ session = mock.MagicMock()+ session.get.side_effect = requests.ConnectionError("boom")+ with mock.patch(EASYBILL_SESSION_PATCH, return_value=session):+ assert validate_credentials("key") is False+++class TestRetryAndErrors:+ @parameterized.expand([("rate_limited", 429), ("server_error", 503)])+ @mock.patch("time.sleep", return_value=None)+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_retryable_status_is_retried_then_succeeds(self, _name: str, status_code: int, MockSession, _sleep) -> None:+ # easybill enforces a strict per-minute rate limit (10/min on PLUS, 60/min on BUSINESS)+ # returned as 429; the shared client retries on status so one throttle doesn't fail the sync.+ session = MockSession.return_value+ transient = _response(None, status=status_code, body_override={"error": "transient"})+ ok = _response([{"id": 1}], page=1, pages=1)+ _wire(session, [transient, ok])++ rows = _rows(_source("Customers", _make_manager()))++ assert [r["id"] for r in rows] == [1]+ assert session.send.call_count == 2++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_client_error_fails_loud(self, MockSession) -> None:+ session = MockSession.return_value+ resp = _response(None, status=401, body_override={"error": "unauthorized"})+ resp.url = "https://api.easybill.de/rest/v1/customers"+ _wire(session, [resp])++ with pytest.raises(HTTPError):+ _rows(_source("Customers", _make_manager()))+++if __name__ == "__main__":+ pytest.main([__file__])diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/easybill/tests/test_easybill_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/easybill/tests/test_easybill_source.pynew file mode 100644index 000000000000..229b9971d9d6--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/easybill/tests/test_easybill_source.py@@ -0,0 +1,116 @@+from typing import Any++import pytest+from unittest import mock++from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.easybill import source as source_module+from products.warehouse_sources.backend.temporal.data_imports.sources.easybill.easybill import EasybillResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.easybill.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.easybill.source import EasybillSource+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.easybill import (+ EasybillSourceConfig,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestEasybillSourceClass:+ def setup_method(self) -> None:+ self.source = EasybillSource()+ self.config = EasybillSourceConfig(api_key="key")+ self.team_id = 1++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.EASYBILL++ def test_source_config_has_password_api_key_field(self) -> None:+ config = self.source.get_source_config+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/easybill"+ fields = config.fields or []+ assert len(fields) == 1+ assert fields[0].name == "api_key"+ assert fields[0].type == "password"++ def test_no_unreleased_flag(self) -> None:+ # A finished source ships visible: unreleasedSource must not be set at all.+ assert self.source.get_source_config.unreleasedSource is None++ @parameterized.expand([("401 Client Error",), ("403 Client Error",)])+ def test_non_retryable_errors(self, expected_key_prefix: str) -> None:+ keys = self.source.get_non_retryable_errors()+ assert any(k.startswith(expected_key_prefix) for k in keys)++ def test_get_schemas_lists_every_endpoint(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ def test_only_documents_is_incremental(self) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ assert schemas["Documents"].supports_incremental is True+ assert [f["field"] for f in schemas["Documents"].incremental_fields] == ["edited_at"]+ for name, schema in schemas.items():+ if name != "Documents":+ assert schema.supports_incremental is False, name++ def test_get_schemas_filters_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["Documents", "Customers"])+ assert {s.name for s in schemas} == {"Documents", "Customers"}++ def test_documented_tables_render_without_credentials(self) -> None:+ assert self.source.lists_tables_without_credentials is True+ tables = {t["name"]: t for t in self.source.get_documented_tables()}+ assert set(tables) == set(ENDPOINTS)+ assert tables["Documents"]["description"]++ @parameterized.expand([("valid", True, (True, None)), ("invalid", False, (False, "Invalid easybill API key"))])+ def test_validate_credentials(self, _name: str, api_result: bool, expected: tuple[bool, str | None]) -> None:+ with mock.patch.object(source_module, "validate_easybill_credentials", return_value=api_result):+ assert self.source.validate_credentials(self.config, self.team_id) == expected++ def test_get_resumable_source_manager_bound_to_data_class(self) -> None:+ inputs = mock.Mock()+ manager = self.source.get_resumable_source_manager(inputs)+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is EasybillResumeConfig++ def test_source_for_pipeline_plumbs_incremental_args(self) -> None:+ inputs = mock.Mock()+ inputs.schema_name = "Documents"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2024-01-01"+ manager = mock.Mock()++ with mock.patch.object(source_module, "easybill_source") as mocked:+ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = mocked.call_args.kwargs+ assert kwargs["api_key"] == "key"+ assert kwargs["endpoint"] == "Documents"+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2024-01-01"++ def test_source_for_pipeline_drops_watermark_when_not_incremental(self) -> None:+ inputs = mock.Mock()+ inputs.schema_name = "Customers"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2024-01-01"+ manager = mock.Mock()++ with mock.patch.object(source_module, "easybill_source") as mocked:+ self.source.source_for_pipeline(self.config, manager, inputs)++ assert mocked.call_args.kwargs["db_incremental_field_last_value"] is None+++class TestCanonicalDescriptions:+ def test_keys_are_all_real_endpoints(self) -> None:+ # A canonical entry keyed by a name that isn't an endpoint would silently never render.+ descriptions: dict[str, Any] = EasybillSource().get_canonical_descriptions()+ assert set(descriptions).issubset(set(ENDPOINTS))+ assert "Documents" in descriptions+++if __name__ == "__main__":+ pytest.main([__file__])diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/easybill.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/easybill.pyindex 240dbf11c438..65bc454fe900 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/easybill.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/easybill.py@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass EasybillSourceConfig(config.Config):- pass+ api_key: str