: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): implement e_conomic import source (#66750)
Tom Owersc403df02d835
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 1597cdc3c292..fc96df023a9e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -105,6 +105,7 @@ the row lists both.| docuseal | HTTP | requests | ✅ || doit | HTTP | requests | ✅ || drip | HTTP | requests | ✅ |+| e_conomic | HTTP | requests | ✅ || easypost | HTTP | requests | ✅ || easypromos | HTTP | requests | ✅ || freshdesk | HTTP | requests | ✅ |@@ -379,7 +380,6 @@ doesn't conflict with concurrent PRs.- dwolla- dynamics365- dynamodb-- e_conomic- ebay- eloqua- employment_herodiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/e_conomic/api_inventory.md b/products/warehouse_sources/backend/temporal/data_imports/sources/e_conomic/api_inventory.mdnew file mode 100644index 000000000000..ae51b9108585--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/e_conomic/api_inventory.md@@ -0,0 +1,66 @@+# Visma e-conomic API inventory++Reference notes for the `e_conomic` source. All behavior below was verified with `curl` against the+live API (`https://restapi.e-conomic.com`) using e-conomic's public demo agreement+(`X-AppSecretToken: demo`, `X-AgreementGrantToken: demo`).++## Auth++- Two custom headers: `X-AppSecretToken` (per-app developer secret) and `X-AgreementGrantToken`+ (per-agreement grant issued when a user installs the app). Not OAuth.+- No per-resource scopes — a valid grant token reads the whole agreement.+- Bad app-secret **or** grant token → `401 Unauthorized` (the API does not distinguish the two, and+ there is no `403` for missing scope).+- Cheap validation probe: `GET /self` (returns agreement/company metadata).++## Response shape & pagination++- List endpoints return `{"collection": [...], "pagination": {...}, "self": "..."}`.+- Offset pagination: `pagesize` (max **1000**) + `skippages`. Responses carry HATEOAS links+ `pagination.firstPage` / `nextPage` / `lastPage`. We follow `nextPage` until absent.+- `nextPage` preserves `pagesize`, `sort` and `filter` (URL-encoded), so resuming a sync is just+ "GET the saved `nextPage` URL".++## Incremental filtering++- Server-side filtering via `filter=<field>$<op>:<value>` with Mongo-style operators (`$gte`, `$gt`, …).+- Confirmed the filter is genuinely applied (future-date cutoff → 0 results; past-date → all results).+- `lastUpdated` filtering coverage **varies per endpoint** — present on customers, products and draft+ invoices; absent on suppliers and the reference tables.+- **Sort enums vary per endpoint** and are enforced (`400` on an unsupported field). An incremental+ field is only usable when the endpoint can also `sort` ascending by it (so rows arrive in watermark+ order). `sort=lastUpdated` works on customers/products but **`400`s on draft invoices**.++## Endpoint matrix++| Schema | Path | Primary key | Sort | Incremental | Notes |+| ---------------------------- | ----------------------------- | -------------------------------- | -------------------------------- | ---------------------------------- | ------------------------------------------------------- |+| `customers` | `/customers` | `customerNumber` | `lastUpdated` | ✅ `lastUpdated` (DateTime) | |+| `customer_groups` | `/customer-groups` | `customerGroupNumber` | `customerGroupNumber` | full refresh | |+| `products` | `/products` | `productNumber` | `lastUpdated` | ✅ `lastUpdated` (DateTime) | |+| `product_groups` | `/product-groups` | `productGroupNumber` | `productGroupNumber` | full refresh | |+| `suppliers` | `/suppliers` | `supplierNumber` | `supplierNumber` | full refresh | no `lastUpdated` field; filter on it errors |+| `supplier_groups` | `/supplier-groups` | `supplierGroupNumber` | `supplierGroupNumber` | full refresh | |+| `accounts` | `/accounts` | `accountNumber` | `accountNumber` | full refresh | chart of accounts |+| `accounting_years` | `/accounting-years` | `year` | `year` | full refresh | |+| `journals` | `/journals` | `journalNumber` | `journalNumber` | full refresh | |+| `currencies` | `/currencies` | `code` | `code` | full refresh | |+| `payment_terms` | `/payment-terms` | `paymentTermsNumber` | _(none)_ | full refresh | `sort=paymentTermsNumber` → 400; tiny single-page table |+| `departments` | `/departments` | `departmentNumber` | `departmentNumber` | full refresh | |+| `departmental_distributions` | `/departmental-distributions` | `departmentalDistributionNumber` | `departmentalDistributionNumber` | full refresh | |+| `units` | `/units` | `unitNumber` | `unitNumber` | full refresh | |+| `vat_zones` | `/vat-zones` | `vatZoneNumber` | `vatZoneNumber` | full refresh | |+| `employees` | `/employees` | `employeeNumber` | `employeeNumber` | full refresh | |+| `invoices_booked` | `/invoices/booked` | `bookedInvoiceNumber` | `bookedInvoiceNumber` | ✅ `bookedInvoiceNumber` (Integer) | immutable; partition by stable `date` |+| `invoices_drafts` | `/invoices/drafts` | `draftInvoiceNumber` | `draftInvoiceNumber` | full refresh | has `lastUpdated` filter, but `sort=lastUpdated` → 400 |++## Throttling++- The API throttles and can return `429` (and transient `5xx`). Retry with backoff; honor `Retry-After`+ when present. Published rate-limit numbers are not clearly documented.++## Not implemented (yet)++Sub-resources/fan-out (customer contacts, invoice lines, account entries per accounting year) and the+separate sub-APIs on `apis.e-conomic.com` (subscriptions, etc.) are out of scope for the initial source.+Account entries in particular require a per-accounting-year fan-out (`/accounting-years/{year}/entries`).diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/e_conomic/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/e_conomic/canonical_descriptions.pynew file mode 100644index 000000000000..3a0954ad106a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/e_conomic/canonical_descriptions.py@@ -0,0 +1,232 @@+"""Canonical, documentation-sourced descriptions for Visma e-conomic endpoints and columns.++Sourced from the official e-conomic REST API reference (https://restdocs.e-conomic.com). Keyed by the+endpoint names in `settings.py` `E_CONOMIC_ENDPOINTS`, which match the `ExternalDataSchema.name` of a+synced table. Columns absent here fall back to LLM enrichment.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "customers": {+ "description": "A debtor (customer) you sell to. Holds billing details, payment terms and the customer's running balance.",+ "docs_url": "https://restdocs.e-conomic.com/#get-customers",+ "columns": {+ "customerNumber": "Unique identifier of the customer.",+ "name": "Customer name.",+ "currency": "The customer's default currency (ISO 4217 code).",+ "paymentTerms": "Default payment terms applied to the customer's invoices.",+ "customerGroup": "The customer group this customer belongs to.",+ "address": "Street address.",+ "city": "City.",+ "zip": "Postal code.",+ "country": "Country.",+ "email": "Primary email address.",+ "balance": "The customer's current outstanding balance in the base currency.",+ "dueAmount": "Amount currently overdue.",+ "vatZone": "VAT zone determining how VAT is calculated for the customer.",+ "lastUpdated": "Timestamp of the last modification to the customer (used for incremental sync).",+ },+ },+ "customer_groups": {+ "description": "A grouping of customers, typically used to assign a common sales account.",+ "docs_url": "https://restdocs.e-conomic.com/#get-customer-groups",+ "columns": {+ "customerGroupNumber": "Unique identifier of the customer group.",+ "name": "Customer group name.",+ "account": "The sales account customers in this group post to.",+ },+ },+ "products": {+ "description": "A product or service you sell, with pricing and inventory references.",+ "docs_url": "https://restdocs.e-conomic.com/#get-products",+ "columns": {+ "productNumber": "Unique identifier of the product.",+ "name": "Product name.",+ "description": "Product description.",+ "costPrice": "Cost price of the product.",+ "recommendedPrice": "Recommended retail price.",+ "salesPrice": "Default sales price.",+ "barred": "Whether the product is barred from being used on new entries.",+ "productGroup": "The product group this product belongs to.",+ "unit": "Unit the product is sold in.",+ "lastUpdated": "Timestamp of the last modification to the product (used for incremental sync).",+ },+ },+ "product_groups": {+ "description": "A grouping of products that share sales accounts and inventory settings.",+ "docs_url": "https://restdocs.e-conomic.com/#get-product-groups",+ "columns": {+ "productGroupNumber": "Unique identifier of the product group.",+ "name": "Product group name.",+ "salesAccounts": "Sales accounts products in this group post to.",+ "inventoryEnabled": "Whether inventory tracking is enabled for this group.",+ },+ },+ "suppliers": {+ "description": "A creditor (supplier) you buy from, with payment and contact details.",+ "docs_url": "https://restdocs.e-conomic.com/#get-suppliers",+ "columns": {+ "supplierNumber": "Unique identifier of the supplier.",+ "name": "Supplier name.",+ "currency": "The supplier's default currency (ISO 4217 code).",+ "paymentTerms": "Default payment terms for the supplier.",+ "supplierGroup": "The supplier group this supplier belongs to.",+ "vatZone": "VAT zone determining how VAT is calculated for the supplier.",+ "email": "Primary email address.",+ "address": "Street address.",+ "city": "City.",+ "zip": "Postal code.",+ "country": "Country.",+ "costAccount": "The default cost account purchases from this supplier post to.",+ },+ },+ "supplier_groups": {+ "description": "A grouping of suppliers, used to assign a common cost account.",+ "docs_url": "https://restdocs.e-conomic.com/#get-supplier-groups",+ "columns": {+ "supplierGroupNumber": "Unique identifier of the supplier group.",+ "name": "Supplier group name.",+ "account": "The account suppliers in this group post to.",+ },+ },+ "accounts": {+ "description": "An account in the chart of accounts, including its type and current balance.",+ "docs_url": "https://restdocs.e-conomic.com/#get-accounts",+ "columns": {+ "accountNumber": "Unique account number in the chart of accounts.",+ "name": "Account name.",+ "accountType": "Type of account (e.g. profitAndLoss, status, heading, totalFrom).",+ "balance": "Current balance of the account.",+ "debitCredit": "Whether the account is a debit or credit account.",+ "blockDirectEntries": "Whether direct entries to the account are blocked.",+ },+ },+ "accounting_years": {+ "description": "A financial (accounting) year and the date range it covers.",+ "docs_url": "https://restdocs.e-conomic.com/#get-accounting-years",+ "columns": {+ "year": "The accounting year identifier (e.g. 2024 or 2024/2025).",+ "fromDate": "First day of the accounting year.",+ "toDate": "Last day of the accounting year.",+ },+ },+ "journals": {+ "description": "A journal used for grouping and posting entries.",+ "docs_url": "https://restdocs.e-conomic.com/#get-journals",+ "columns": {+ "journalNumber": "Unique identifier of the journal.",+ "name": "Journal name.",+ "settings": "Posting settings for the journal.",+ },+ },+ "currencies": {+ "description": "A currency available in the agreement.",+ "docs_url": "https://restdocs.e-conomic.com/#get-currencies",+ "columns": {+ "code": "ISO 4217 currency code (e.g. DKK, EUR, USD).",+ "name": "Currency name.",+ "isoNumber": "ISO 4217 numeric currency code.",+ },+ },+ "payment_terms": {+ "description": "A set of payment terms (credit days and type) applied to invoices.",+ "docs_url": "https://restdocs.e-conomic.com/#get-payment-terms",+ "columns": {+ "paymentTermsNumber": "Unique identifier of the payment terms.",+ "name": "Payment terms name.",+ "daysOfCredit": "Number of days of credit granted.",+ "paymentTermsType": "Type of payment terms (e.g. net, invoiceMonth, paidInCash).",+ "description": "Description of the payment terms.",+ },+ },+ "departments": {+ "description": "A department used to tag entries for dimensional reporting.",+ "docs_url": "https://restdocs.e-conomic.com/#get-departments",+ "columns": {+ "departmentNumber": "Unique identifier of the department.",+ "name": "Department name.",+ },+ },+ "departmental_distributions": {+ "description": "A rule for distributing an entry across multiple departments.",+ "docs_url": "https://restdocs.e-conomic.com/#get-departmental-distributions",+ "columns": {+ "departmentalDistributionNumber": "Unique identifier of the departmental distribution.",+ "name": "Distribution name.",+ "distributionType": "How the amount is distributed across departments.",+ "barred": "Whether the distribution is barred from new entries.",+ },+ },+ "units": {+ "description": "A unit of measure that products can be sold in (e.g. hours, pieces).",+ "docs_url": "https://restdocs.e-conomic.com/#get-units",+ "columns": {+ "unitNumber": "Unique identifier of the unit.",+ "name": "Unit name.",+ },+ },+ "vat_zones": {+ "description": "A VAT zone determining how VAT is applied to customers and suppliers.",+ "docs_url": "https://restdocs.e-conomic.com/#get-vat-zones",+ "columns": {+ "vatZoneNumber": "Unique identifier of the VAT zone.",+ "name": "VAT zone name.",+ "enabledForCustomer": "Whether the zone can be assigned to customers.",+ "enabledForSupplier": "Whether the zone can be assigned to suppliers.",+ },+ },+ "employees": {+ "description": "An employee in the agreement, used as a sales person on invoices.",+ "docs_url": "https://restdocs.e-conomic.com/#get-employees",+ "columns": {+ "employeeNumber": "Unique identifier of the employee.",+ "name": "Employee name.",+ "employeeGroup": "The employee group this employee belongs to.",+ "email": "Employee email address.",+ "phone": "Employee phone number.",+ },+ },+ "invoices_booked": {+ "description": "A booked (finalized, immutable) sales invoice with its amounts and customer reference.",+ "docs_url": "https://restdocs.e-conomic.com/#get-invoices-booked",+ "columns": {+ "bookedInvoiceNumber": "Sequential identifier of the booked invoice (monotonic; used for incremental sync).",+ "orderNumber": "Associated order number, if any.",+ "date": "Booking date of the invoice.",+ "dueDate": "Date the invoice is due for payment.",+ "currency": "Invoice currency (ISO 4217 code).",+ "exchangeRate": "Exchange rate to the base currency at booking time.",+ "netAmount": "Net amount in the invoice currency.",+ "netAmountInBaseCurrency": "Net amount converted to the base currency.",+ "grossAmount": "Gross amount (incl. VAT) in the invoice currency.",+ "grossAmountInBaseCurrency": "Gross amount converted to the base currency.",+ "vatAmount": "Total VAT amount on the invoice.",+ "roundingAmount": "Rounding adjustment applied to the total.",+ "remainder": "Outstanding amount remaining on the invoice.",+ "customer": "The customer the invoice was issued to.",+ "paymentTerms": "Payment terms applied to the invoice.",+ },+ },+ "invoices_drafts": {+ "description": "A draft (not yet booked, editable) sales invoice.",+ "docs_url": "https://restdocs.e-conomic.com/#get-invoices-drafts",+ "columns": {+ "draftInvoiceNumber": "Unique identifier of the draft invoice.",+ "date": "Invoice date.",+ "dueDate": "Date the invoice would be due for payment.",+ "currency": "Invoice currency (ISO 4217 code).",+ "exchangeRate": "Exchange rate to the base currency.",+ "netAmount": "Net amount in the invoice currency.",+ "netAmountInBaseCurrency": "Net amount converted to the base currency.",+ "grossAmount": "Gross amount (incl. VAT) in the invoice currency.",+ "grossAmountInBaseCurrency": "Gross amount converted to the base currency.",+ "vatAmount": "Total VAT amount on the invoice.",+ "customer": "The customer the draft is for.",+ "paymentTerms": "Payment terms applied to the draft.",+ "lastUpdated": "Timestamp of the last modification to the draft.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/e_conomic/e_conomic.py b/products/warehouse_sources/backend/temporal/data_imports/sources/e_conomic/e_conomic.pynew file mode 100644index 000000000000..c943a5e8eb86--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/e_conomic/e_conomic.py@@ -0,0 +1,213 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import urlencode, urlparse++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+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.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.e_conomic.settings import (+ E_CONOMIC_ENDPOINTS,+ EConomicEndpointConfig,+)++E_CONOMIC_BASE_URL = "https://restapi.e-conomic.com"+E_CONOMIC_HOST = urlparse(E_CONOMIC_BASE_URL).netloc++# Max page size the API allows for classic offset pagination.+PAGE_SIZE = 1000++REQUEST_TIMEOUT_SECONDS = 60+MAX_RETRY_ATTEMPTS = 5+++class EConomicRetryableError(Exception):+ """Raised on a 429 or 5xx so tenacity retries with backoff."""++ pass+++class EConomicResumeConfig:+ # Full URL of the next page to fetch. The API's pagination links already carry pagesize, sort and+ # filter, so resuming is just "GET this URL".+ next_url: str | None = None+++def _headers(app_secret_token: str, agreement_grant_token: str) -> dict[str, str]:+ return {+ "X-AppSecretToken": app_secret_token,+ "X-AgreementGrantToken": agreement_grant_token,+ "Content-Type": "application/json",+ }+++def _assert_trusted_url(url: str) -> None:+ """Guard against following a pagination/resume URL off the e-conomic host.++ The session carries `X-AppSecretToken`/`X-AgreementGrantToken` on every request, so a `nextPage`+ link or persisted resume URL pointing anywhere other than the API host would leak those tokens.+ We only ever fetch HATEOAS links the API itself returns (or our own resume state), so anything+ off-host is unexpected and we abort rather than send credentials to it.+ """+ parsed = urlparse(url)+ if parsed.scheme != "https" or parsed.netloc != E_CONOMIC_HOST:+ raise ValueError(f"Refusing to fetch untrusted e-conomic URL: {url}")+++def _format_incremental_value(value: Any) -> str:+ """Format an incremental cursor value for an e-conomic `filter` expression.++ Datetimes go out as UTC `...Z` (the format the API returns and accepts), dates as `YYYY-MM-DD`,+ and monotonic integer cursors (e.g. bookedInvoiceNumber) as their plain decimal string.+ """+ if isinstance(value, datetime):+ utc_value = value.astimezone(UTC) if value.tzinfo is not None else value.replace(tzinfo=UTC)+ return utc_value.strftime("%Y-%m-%dT%H:%M:%SZ")+ if isinstance(value, date):+ return value.strftime("%Y-%m-%d")+ return str(value)+++def _build_initial_url(+ config: EConomicEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ incremental_field: str | None,+) -> str:+ """Build the first-page URL. Pagination links thereafter carry these params forward."""+ params: list[tuple[str, str]] = [("pagesize", str(PAGE_SIZE))]++ if config.sort:+ params.append(("sort", config.sort))++ # Server-side incremental filter. `>=` (re-fetching the boundary row) is safe because merge dedupes+ # on the primary key, and it avoids missing rows that share the cursor value.+ if should_use_incremental_field and incremental_field and db_incremental_field_last_value is not None:+ formatted = _format_incremental_value(db_incremental_field_last_value)+ params.append(("filter", f"{incremental_field}$gte:{formatted}"))++ return f"{E_CONOMIC_BASE_URL}{config.path}?{urlencode(params)}"+++@retry(+ retry=retry_if_exception_type((EConomicRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(session: requests.Session, url: str, logger: FilteringBoundLogger) -> dict:+ # Validate before every GET so untrusted resume state and `nextPage` links can never carry the+ # auth headers off-host. Redirects are disabled for the same reason: a redirect could bounce the+ # request (and its tokens) to an arbitrary host that this check never sees.+ _assert_trusted_url(url)+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS, allow_redirects=False)++ # 429 (throttled) and transient 5xx are retryable. The API may send Retry-After on a 429; the+ # exponential-jitter backoff is a safe, deterministic substitute when it's absent.+ if response.status_code == 429 or response.status_code >= 500:+ raise EConomicRetryableError(f"e-conomic API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"e-conomic API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++def get_rows(+ app_secret_token: str,+ agreement_grant_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[EConomicResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ incremental_field: str | None = None,+) -> Iterator[list[dict[str, Any]]]:+ config = E_CONOMIC_ENDPOINTS[endpoint]+ # One session reused across pages so the connection is kept alive; tokens are redacted from logs and+ # sample capture because they're carried in custom headers the name-based scrubbers don't recognise.+ session = make_tracked_session(+ headers=_headers(app_secret_token, agreement_grant_token),+ redact_values=(app_secret_token, agreement_grant_token),+ )++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume is not None and resume.next_url:+ url: str | None = resume.next_url+ logger.debug(f"e-conomic: resuming {endpoint} from URL: {url}")+ else:+ url = _build_initial_url(+ config, should_use_incremental_field, db_incremental_field_last_value, incremental_field+ )++ while url is not None:+ data = _fetch_page(session, url, logger)++ items = data.get("collection") or []+ next_url = (data.get("pagination") or {}).get("nextPage")++ if items:+ yield items++ if not next_url:+ break++ # Save AFTER yielding so a crash re-yields the last page (deduped on merge) rather than skipping+ # it. Advance the URL before the next fetch so we don't loop on the same page.+ resumable_source_manager.save_state(EConomicResumeConfig(next_url=next_url))+ url = next_url+++def e_conomic_source(+ app_secret_token: str,+ agreement_grant_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[EConomicResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ config = E_CONOMIC_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ app_secret_token=app_secret_token,+ agreement_grant_token=agreement_grant_token,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ incremental_field=incremental_field,+ ),+ primary_keys=config.primary_keys,+ # Ascending order only holds when we send a sort field; endpoints with no sortable column+ # (e.g. payment_terms) return rows in an unspecified order, so we don't claim a sort mode.+ sort_mode="asc" if config.sort else None,+ 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 validate_credentials(app_secret_token: str, agreement_grant_token: str) -> bool:+ """Probe the cheap `/self` endpoint. Any non-200 (the API returns 401 for a bad app-secret OR+ agreement-grant token) means the credentials are unusable."""+ try:+ session = make_tracked_session(+ headers=_headers(app_secret_token, agreement_grant_token),+ redact_values=(app_secret_token, agreement_grant_token),+ )+ response = session.get(f"{E_CONOMIC_BASE_URL}/self", timeout=10)+ return response.status_code == 200+ except Exception:+ return Falsediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/e_conomic/posthog_com_doc.mdx b/products/warehouse_sources/backend/temporal/data_imports/sources/e_conomic/posthog_com_doc.mdxnew file mode 100644index 000000000000..981a0eb2c371--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/e_conomic/posthog_com_doc.mdx@@ -0,0 +1,82 @@+<!--+This is the user-facing source doc. It belongs in the posthog.com repo at+contents/docs/cdp/sources/e-conomic.md (served at /docs/cdp/sources/e-conomic). It lives here only+because no posthog.com checkout was available when the source was implemented — move it there and+delete this copy. The slug `e-conomic` must match `docsUrl` in get_source_config.+-->++---++title: Linking e-conomic as a source+sidebar: Docs+showTitle: true+availability: { free: full, selfServe: full, enterprise: full }+sourceId: EConomic+beta: true++---++import SourceSetupIntro from '../_snippets/source-setup-intro.mdx'+import SyncModes from '../_snippets/sync-modes.mdx'+import TroubleshootingLink from '../_snippets/dw-troubleshooting-link.mdx'+import AlphaRelease from '../_snippets/alpha-release.mdx'++<AlphaRelease />++Sync your [Visma e-conomic](https://www.e-conomic.com/) accounting data — customers, suppliers,+products, invoices, the chart of accounts, and more — into PostHog so you can join financial data with+product and revenue analytics.++## Prerequisites++To connect e-conomic you need two tokens:++- An **app secret token** for a registered e-conomic app (created in the [e-conomic Developer+ portal](https://www.e-conomic.com/developer)).+- An **agreement grant token**, issued when an e-conomic user grants your app access to their agreement+ via the app's installation URL.++Both tokens grant read access to the whole agreement — e-conomic has no per-resource scopes.++## Adding a data source++<SourceSetupIntro />++Provide:++- **App secret token** — your app's secret from the e-conomic Developer portal.+- **Agreement grant token** — the grant token issued for the agreement you want to sync.++PostHog sends these as the `X-AppSecretToken` and `X-AgreementGrantToken` headers on every request.++## Sync modes++<SyncModes />++Most e-conomic tables are full-refresh only. Tables that expose a reliable server-side cursor support+**incremental** sync:++- `customers` and `products` sync incrementally on `lastUpdated`.+- `invoices_booked` syncs incrementally on `bookedInvoiceNumber` (booked invoices are immutable and+ numbered sequentially, so this never skips or re-counts entries).++Draft invoices carry a `lastUpdated` timestamp, but e-conomic does not allow sorting by it, so they are+synced as full refresh to avoid missing edits.++## Configuration++<SourceParameters />++## Supported tables++<SourceTables />++## Troubleshooting++- **401 Unauthorized** — one or both tokens are invalid or revoked. e-conomic returns the same status+ for a bad app secret token and a bad agreement grant token. Re-check both, re-grant the app access to+ the agreement if needed, and reconnect.+- **Rate limiting (429)** — e-conomic throttles heavy traffic. PostHog retries with backoff+ automatically; large initial syncs may simply take longer.++<TroubleshootingLink />diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/e_conomic/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/e_conomic/settings.pynew file mode 100644index 000000000000..7aec7e4d2957--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/e_conomic/settings.py@@ -0,0 +1,162 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+++def _incremental_field(name: str, field_type: IncrementalFieldType) -> IncrementalField:+ return {"label": name, "type": field_type, "field": name, "field_type": field_type}+++@dataclass+class EConomicEndpointConfig:+ name: str+ # Path on https://restapi.e-conomic.com. Uses hyphens (e.g. /customer-groups) while the schema/table+ # name (the dict key) uses underscores.+ path: str+ primary_keys: list[str]+ # Advertised incremental options. Empty => full refresh only. Every advertised field MUST be both+ # server-side filterable (`filter=<field>$gte:<value>`) AND sortable ascending on this endpoint —+ # otherwise the watermark can't checkpoint safely. Verified per-endpoint against the live API.+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Field passed as `sort=` on every request. For incremental endpoints it equals the incremental+ # field so rows arrive ascending and the watermark advances correctly. For full-refresh endpoints+ # it's a stable identifier so pagination can't skip/duplicate rows across pages. `None` => no sort+ # (only for tiny single-page endpoints whose number field the API refuses to sort by).+ sort: Optional[str] = None+ # Stable, immutable date field for storage partitioning. Never a field that mutates (e.g.+ # lastUpdated) — partitions would rewrite on every sync.+ partition_key: Optional[str] = None+ should_sync_default: bool = True+++# Endpoint catalog. Incremental support is set ONLY where the live API honors a server-side timestamp /+# monotonic filter AND can sort ascending by that field (both confirmed with curl against the demo+# agreement). Everything else is full refresh — including suppliers (no `lastUpdated`) and draft invoices+# (the API rejects `sort=lastUpdated`, so ascending order can't be guaranteed for a watermark).+E_CONOMIC_ENDPOINTS: dict[str, EConomicEndpointConfig] = {+ "customers": EConomicEndpointConfig(+ name="customers",+ path="/customers",+ primary_keys=["customerNumber"],+ sort="lastUpdated",+ incremental_fields=[_incremental_field("lastUpdated", IncrementalFieldType.DateTime)],+ ),+ "customer_groups": EConomicEndpointConfig(+ name="customer_groups",+ path="/customer-groups",+ primary_keys=["customerGroupNumber"],+ sort="customerGroupNumber",+ ),+ "products": EConomicEndpointConfig(+ name="products",+ path="/products",+ primary_keys=["productNumber"],+ sort="lastUpdated",+ incremental_fields=[_incremental_field("lastUpdated", IncrementalFieldType.DateTime)],+ ),+ "product_groups": EConomicEndpointConfig(+ name="product_groups",+ path="/product-groups",+ primary_keys=["productGroupNumber"],+ sort="productGroupNumber",+ ),+ "suppliers": EConomicEndpointConfig(+ name="suppliers",+ path="/suppliers",+ primary_keys=["supplierNumber"],+ sort="supplierNumber",+ ),+ "supplier_groups": EConomicEndpointConfig(+ name="supplier_groups",+ path="/supplier-groups",+ primary_keys=["supplierGroupNumber"],+ sort="supplierGroupNumber",+ ),+ "accounts": EConomicEndpointConfig(+ name="accounts",+ path="/accounts",+ primary_keys=["accountNumber"],+ sort="accountNumber",+ ),+ "accounting_years": EConomicEndpointConfig(+ name="accounting_years",+ path="/accounting-years",+ primary_keys=["year"],+ sort="year",+ ),+ "journals": EConomicEndpointConfig(+ name="journals",+ path="/journals",+ primary_keys=["journalNumber"],+ sort="journalNumber",+ ),+ "currencies": EConomicEndpointConfig(+ name="currencies",+ path="/currencies",+ primary_keys=["code"],+ sort="code",+ ),+ "payment_terms": EConomicEndpointConfig(+ name="payment_terms",+ path="/payment-terms",+ primary_keys=["paymentTermsNumber"],+ # The API rejects sort=paymentTermsNumber (400); this is a tiny single-page table, so no sort.+ sort=None,+ ),+ "departments": EConomicEndpointConfig(+ name="departments",+ path="/departments",+ primary_keys=["departmentNumber"],+ sort="departmentNumber",+ ),+ "departmental_distributions": EConomicEndpointConfig(+ name="departmental_distributions",+ path="/departmental-distributions",+ primary_keys=["departmentalDistributionNumber"],+ sort="departmentalDistributionNumber",+ ),+ "units": EConomicEndpointConfig(+ name="units",+ path="/units",+ primary_keys=["unitNumber"],+ sort="unitNumber",+ ),+ "vat_zones": EConomicEndpointConfig(+ name="vat_zones",+ path="/vat-zones",+ primary_keys=["vatZoneNumber"],+ sort="vatZoneNumber",+ ),+ "employees": EConomicEndpointConfig(+ name="employees",+ path="/employees",+ primary_keys=["employeeNumber"],+ sort="employeeNumber",+ ),+ "invoices_booked": EConomicEndpointConfig(+ name="invoices_booked",+ path="/invoices/booked",+ primary_keys=["bookedInvoiceNumber"],+ # Booked invoices are immutable and numbered monotonically, so the invoice number is a safe,+ # gap-free incremental cursor — unlike `date`, which a user can backdate and would let the+ # watermark skip late entries. `date` is the stable booking date, used only for partitioning.+ sort="bookedInvoiceNumber",+ partition_key="date",+ incremental_fields=[_incremental_field("bookedInvoiceNumber", IncrementalFieldType.Integer)],+ ),+ "invoices_drafts": EConomicEndpointConfig(+ name="invoices_drafts",+ path="/invoices/drafts",+ primary_keys=["draftInvoiceNumber"],+ # Drafts carry `lastUpdated` and the API filters on it, but it refuses sort=lastUpdated, so rows+ # can't be guaranteed ascending for a watermark — full refresh only.+ sort="draftInvoiceNumber",+ ),+}++ENDPOINTS = tuple(E_CONOMIC_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in E_CONOMIC_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/e_conomic/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/e_conomic/source.pyindex 591818688640..7e573fc9410c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/e_conomic/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/e_conomic/source.py@@ -1,19 +1,42 @@-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.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+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+from products.warehouse_sources.backend.temporal.data_imports.sources.e_conomic.e_conomic import (+ EConomicResumeConfig,+ e_conomic_source,+ validate_credentials as validate_e_conomic_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.e_conomic.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import EConomicSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class EConomicSource(SimpleSource[EConomicSourceConfig]):+class EConomicSource(ResumableSource[EConomicSourceConfig, EConomicResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.ECONOMIC@@ -24,7 +47,105 @@ class EConomicSource(SimpleSource[EConomicSourceConfig]):name=SchemaExternalDataSourceType.E_CONOMIC,category=DataWarehouseSourceCategory.FINANCE___ACCOUNTING,label="e-conomic",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Visma e-conomic API tokens to pull your accounting data into the PostHog Data warehouse.++e-conomic authenticates with two tokens sent as request headers:+- **App secret token** — your app's secret, from the [e-conomic Developer portal](https://www.e-conomic.com/developer).+- **Agreement grant token** — issued when an e-conomic user grants your app access to their agreement.++Both tokens grant read access to the whole agreement; e-conomic has no per-resource scopes.""",iconPath="/static/services/e_conomic.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/e-conomic",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="app_secret_token",+ label="App secret token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="agreement_grant_token",+ label="Agreement grant token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.e_conomic.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # e-conomic returns 401 for an invalid/revoked app-secret OR agreement-grant token. Retrying+ # can never fix a credential problem, so stop the sync. Match the stable status text and base+ # host, not the per-request path/query.+ "401 Client Error: Unauthorized for url: https://restapi.e-conomic.com": "Your e-conomic tokens are invalid or have been revoked. Check your app secret token and agreement grant token, then reconnect.",+ "403 Client Error: Forbidden for url: https://restapi.e-conomic.com": "Your e-conomic tokens do not have access to this data. Re-grant the app access to the agreement, then reconnect.",+ }++ def get_schemas(+ self,+ config: EConomicSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _build_schema(endpoint: str) -> SourceSchema:+ incremental_fields = INCREMENTAL_FIELDS.get(endpoint, [])+ has_incremental = len(incremental_fields) > 0+ return SourceSchema(+ name=endpoint,+ supports_incremental=has_incremental,+ supports_append=has_incremental,+ incremental_fields=incremental_fields,+ )++ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: EConomicSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_e_conomic_credentials(config.app_secret_token, config.agreement_grant_token):+ return True, None++ return False, "Invalid e-conomic tokens. Check your app secret token and agreement grant token."++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[EConomicResumeConfig]:+ return ResumableSourceManager[EConomicResumeConfig](inputs, EConomicResumeConfig)++ def source_for_pipeline(+ self,+ config: EConomicSourceConfig,+ resumable_source_manager: ResumableSourceManager[EConomicResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return e_conomic_source(+ app_secret_token=config.app_secret_token,+ agreement_grant_token=config.agreement_grant_token,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ 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,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/e_conomic/tests/test_e_conomic.py b/products/warehouse_sources/backend/temporal/data_imports/sources/e_conomic/tests/test_e_conomic.pynew file mode 100644index 000000000000..8c07bfab615a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/e_conomic/tests/test_e_conomic.py@@ -0,0 +1,232 @@+from datetime import UTC, date, datetime+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++import requests+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.e_conomic.e_conomic import (+ E_CONOMIC_BASE_URL,+ EConomicResumeConfig,+ EConomicRetryableError,+ _build_initial_url,+ _fetch_page,+ _format_incremental_value,+ e_conomic_source,+ get_rows,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.e_conomic.settings import (+ E_CONOMIC_ENDPOINTS,+ ENDPOINTS,+)+++def _make_manager(resume: EConomicResumeConfig | None = None) -> MagicMock:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = resume is not None+ manager.load_state.return_value = resume+ return manager+++def _fake_response(status_code: int, body: dict | None = None) -> MagicMock:+ response = MagicMock(spec=requests.Response)+ response.status_code = status_code+ response.ok = status_code < 400+ response.text = ""+ response.json.return_value = body or {}++ def _raise() -> None:+ if status_code >= 400:+ raise requests.HTTPError(f"{status_code} Client Error", response=response)++ response.raise_for_status.side_effect = _raise+ return response+++class TestFormatIncrementalValue:+ @parameterized.expand(+ [+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14Z"),+ ("naive_datetime", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14Z"),+ ("date_value", date(2026, 3, 4), "2026-03-04"),+ ("integer_cursor", 1052, "1052"),+ ("string_passthrough", "abc", "abc"),+ ]+ )+ def test_format_incremental_value(self, _name: str, value: Any, expected: str) -> None:+ assert _format_incremental_value(value) == expected++ def test_naive_datetime_no_offset_suffix(self) -> None:+ # A naive cursor is treated as UTC, and must not gain a +00:00 offset the API would reject.+ assert "+00:00" not in _format_incremental_value(datetime(2026, 3, 4, 2, 58, 14))+++class TestBuildInitialUrl:+ def test_full_refresh_url_has_pagesize_and_sort_no_filter(self) -> None:+ url = _build_initial_url(E_CONOMIC_ENDPOINTS["customer_groups"], False, None, None)+ assert url.startswith(f"{E_CONOMIC_BASE_URL}/customer-groups?")+ assert "pagesize=1000" in url+ assert "sort=customerGroupNumber" in url+ assert "filter=" not in url++ def test_endpoint_without_sort_omits_sort_param(self) -> None:+ url = _build_initial_url(E_CONOMIC_ENDPOINTS["payment_terms"], False, None, None)+ assert "sort=" not in url++ def test_incremental_datetime_builds_gte_filter(self) -> None:+ url = _build_initial_url(+ E_CONOMIC_ENDPOINTS["customers"], True, datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC), "lastUpdated"+ )+ # `$` and `:` are percent-encoded by urlencode; the API accepts the encoded form.+ assert "filter=lastUpdated%24gte%3A2026-01-02T03%3A04%3A05Z" in url+ assert "sort=lastUpdated" in url++ def test_incremental_integer_builds_gte_filter(self) -> None:+ url = _build_initial_url(E_CONOMIC_ENDPOINTS["invoices_booked"], True, 1052, "bookedInvoiceNumber")+ assert "filter=bookedInvoiceNumber%24gte%3A1052" in url++ def test_incremental_without_last_value_omits_filter(self) -> None:+ url = _build_initial_url(E_CONOMIC_ENDPOINTS["customers"], True, None, "lastUpdated")+ assert "filter=" not in url+++class TestFetchPage:+ @parameterized.expand([("throttled", 429), ("server_error", 500), ("bad_gateway", 503)])+ def test_retryable_status_raises_retryable_error(self, _name: str, status_code: int) -> None:+ session = MagicMock()+ session.get.return_value = _fake_response(status_code)+ # Bypass the @retry decorator (tenacity sets `__wrapped__`) so we assert the raise logic without+ # ~15s of real backoff sleeps per case.+ with pytest.raises(EConomicRetryableError):+ _fetch_page.__wrapped__(session, "https://restapi.e-conomic.com/customers", MagicMock()) # type: ignore[attr-defined]++ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])+ def test_client_error_raises_http_error(self, _name: str, status_code: int) -> None:+ session = MagicMock()+ session.get.return_value = _fake_response(status_code)+ with pytest.raises(requests.HTTPError):+ _fetch_page(session, "https://restapi.e-conomic.com/customers", MagicMock())++ def test_success_returns_json(self) -> None:+ session = MagicMock()+ session.get.return_value = _fake_response(200, {"collection": [{"customerNumber": 1}]})+ assert _fetch_page(session, "https://restapi.e-conomic.com/customers", MagicMock()) == {+ "collection": [{"customerNumber": 1}]+ }++ def test_does_not_follow_redirects(self) -> None:+ # Redirects are disabled so a bounce can't carry the auth headers to another host.+ session = MagicMock()+ session.get.return_value = _fake_response(200, {"collection": []})+ _fetch_page(session, "https://restapi.e-conomic.com/customers", MagicMock())+ assert session.get.call_args.kwargs["allow_redirects"] is False++ @parameterized.expand(+ [+ ("other_host", "https://evil.example.com/customers"),+ ("subdomain_spoof", "https://restapi.e-conomic.com.evil.example.com/customers"),+ ("http_scheme", "http://restapi.e-conomic.com/customers"),+ ("no_scheme", "//restapi.e-conomic.com/customers"),+ ]+ )+ def test_untrusted_url_raises_without_request(self, _name: str, url: str) -> None:+ # An off-host or non-https URL must abort before any GET that would leak the auth headers.+ session = MagicMock()+ with pytest.raises(ValueError):+ _fetch_page(session, url, MagicMock())+ session.get.assert_not_called()+++class TestGetRows:+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.e_conomic.e_conomic.make_tracked_session")+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.e_conomic.e_conomic._fetch_page")+ def test_follows_next_page_links_until_absent(self, mock_fetch: MagicMock, _mock_session: MagicMock) -> None:+ page1 = {+ "collection": [{"customerNumber": 1}],+ "pagination": {"nextPage": "https://restapi.e-conomic.com/customers?skippages=1"},+ }+ page2 = {"collection": [{"customerNumber": 2}], "pagination": {}}+ mock_fetch.side_effect = [page1, page2]++ manager = _make_manager()+ batches = list(get_rows("app", "grant", "customers", MagicMock(), manager))++ assert batches == [[{"customerNumber": 1}], [{"customerNumber": 2}]]+ assert mock_fetch.call_count == 2++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.e_conomic.e_conomic.make_tracked_session")+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.e_conomic.e_conomic._fetch_page")+ def test_saves_state_after_yielding_each_page(self, mock_fetch: MagicMock, _mock_session: MagicMock) -> None:+ next_url = "https://restapi.e-conomic.com/customers?skippages=1"+ mock_fetch.side_effect = [+ {"collection": [{"customerNumber": 1}], "pagination": {"nextPage": next_url}},+ {"collection": [{"customerNumber": 2}], "pagination": {}},+ ]+ manager = _make_manager()++ list(get_rows("app", "grant", "customers", MagicMock(), manager))++ # State is saved once (only when a next page exists) and points at the not-yet-fetched page.+ manager.save_state.assert_called_once_with(EConomicResumeConfig(next_url=next_url))++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.e_conomic.e_conomic.make_tracked_session")+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.e_conomic.e_conomic._fetch_page")+ def test_resumes_from_saved_state(self, mock_fetch: MagicMock, _mock_session: MagicMock) -> None:+ resume_url = "https://restapi.e-conomic.com/customers?skippages=5"+ mock_fetch.return_value = {"collection": [{"customerNumber": 99}], "pagination": {}}+ manager = _make_manager(EConomicResumeConfig(next_url=resume_url))++ list(get_rows("app", "grant", "customers", MagicMock(), manager))++ # First (and only) fetch starts at the resumed URL, not the endpoint's first page.+ assert mock_fetch.call_args_list[0].args[1] == resume_url++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.e_conomic.e_conomic.make_tracked_session")+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.e_conomic.e_conomic._fetch_page")+ def test_empty_collection_yields_nothing(self, mock_fetch: MagicMock, _mock_session: MagicMock) -> None:+ mock_fetch.return_value = {"collection": [], "pagination": {}}+ assert list(get_rows("app", "grant", "customers", MagicMock(), _make_manager())) == []+++class TestECONomicSourceResponse:+ @parameterized.expand(sorted(ENDPOINTS))+ def test_primary_keys_match_settings(self, endpoint: str) -> None:+ config = E_CONOMIC_ENDPOINTS[endpoint]+ response = e_conomic_source("app", "grant", endpoint, MagicMock(), _make_manager())+ assert response.primary_keys == config.primary_keys+ # Only sortable endpoints advertise ascending order; unsortable ones (e.g. payment_terms) don't.+ assert response.sort_mode == ("asc" if config.sort else None)++ def test_booked_invoices_partition_on_stable_date(self) -> None:+ response = e_conomic_source("app", "grant", "invoices_booked", MagicMock(), _make_manager())+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["date"]+ assert response.partition_format == "month"++ def test_non_partitioned_endpoint_has_no_partitioning(self) -> None:+ response = e_conomic_source("app", "grant", "customers", MagicMock(), _make_manager())+ assert response.partition_mode is None+ assert response.partition_keys is None+++class TestValidateCredentials:+ @parameterized.expand([("ok", 200, True), ("unauthorized", 401, False), ("server_error", 500, False)])+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.e_conomic.e_conomic.make_tracked_session")+ def test_status_code_maps_to_bool(+ self, _name: str, status_code: int, expected: bool, mock_session: MagicMock+ ) -> None:+ session = MagicMock()+ session.get.return_value = _fake_response(status_code)+ mock_session.return_value = session+ assert validate_credentials("app", "grant") is expected++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.e_conomic.e_conomic.make_tracked_session")+ def test_request_exception_is_false(self, mock_session: MagicMock) -> None:+ session = MagicMock()+ session.get.side_effect = requests.ConnectionError()+ mock_session.return_value = session+ assert validate_credentials("app", "grant") is Falsediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/e_conomic/tests/test_e_conomic_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/e_conomic/tests/test_e_conomic_source.pynew file mode 100644index 000000000000..099e20884414--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/e_conomic/tests/test_e_conomic_source.py@@ -0,0 +1,135 @@+from typing import Any++import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.e_conomic.e_conomic import EConomicResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.e_conomic.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.e_conomic.source import EConomicSource+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import EConomicSourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType++INCREMENTAL_ENDPOINTS = {"customers", "products", "invoices_booked"}+++def _make_inputs(**overrides: Any) -> mock.MagicMock:+ inputs = mock.MagicMock()+ inputs.schema_name = overrides.get("schema_name", "customers")+ inputs.should_use_incremental_field = overrides.get("should_use_incremental_field", False)+ inputs.db_incremental_field_last_value = overrides.get("db_incremental_field_last_value", None)+ inputs.incremental_field = overrides.get("incremental_field", None)+ return inputs+++class TestECONomicSource:+ def setup_method(self) -> None:+ self.source = EConomicSource()+ self.team_id = 123+ self.config = EConomicSourceConfig(app_secret_token="secret", agreement_grant_token="grant")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.ECONOMIC++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config++ assert config.name.value == "EConomic"+ assert config.label == "e-conomic"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is not True+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/e-conomic"++ assert [f.name for f in config.fields] == ["app_secret_token", "agreement_grant_token"]+ for token_field in config.fields:+ assert isinstance(token_field, SourceFieldInputConfig)+ assert token_field.type == SourceFieldInputConfigType.PASSWORD+ assert token_field.required is True+ assert token_field.secret is True++ def test_lists_tables_without_credentials(self) -> None:+ # Static endpoint catalog (no I/O), so the public docs can render the table list.+ assert self.source.lists_tables_without_credentials is True+ assert len(self.source.get_documented_tables()) == len(ENDPOINTS)++ def test_get_schemas_matches_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("endpoint", sorted(ENDPOINTS))+ def test_get_schemas_incremental_flags(self, endpoint: str) -> None:+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == endpoint)+ expected_incremental = endpoint in INCREMENTAL_ENDPOINTS+ assert schema.supports_incremental is expected_incremental+ assert schema.supports_append is expected_incremental+ assert schema.incremental_fields == INCREMENTAL_FIELDS[endpoint]++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["customers"])+ assert [s.name for s in schemas] == ["customers"]++ def test_get_schemas_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ @pytest.mark.parametrize("expected_key", ["401 Client Error: Unauthorized", "403 Client Error: Forbidden"])+ def test_non_retryable_errors(self, expected_key: str) -> None:+ assert any(expected_key in key for key in self.source.get_non_retryable_errors())++ @pytest.mark.parametrize(+ "is_valid, expected_valid, expected_has_message",+ [(True, True, False), (False, False, True)],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.e_conomic.source.validate_e_conomic_credentials"+ )+ def test_validate_credentials(+ self,+ mock_validate: mock.MagicMock,+ is_valid: bool,+ expected_valid: bool,+ expected_has_message: bool,+ ) -> None:+ mock_validate.return_value = is_valid+ valid, message = self.source.validate_credentials(self.config, self.team_id)+ assert valid is expected_valid+ assert (message is not None) is expected_has_message+ mock_validate.assert_called_once_with(self.config.app_secret_token, self.config.agreement_grant_token)++ def test_get_resumable_source_manager_bound_to_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(_make_inputs())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is EConomicResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.e_conomic.source.e_conomic_source")+ def test_source_for_pipeline_passes_arguments(self, mock_source: mock.MagicMock) -> None:+ inputs = _make_inputs(+ schema_name="customers",+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-01-01T00:00:00Z",+ incremental_field="lastUpdated",+ )+ manager = mock.MagicMock(spec=ResumableSourceManager)++ self.source.source_for_pipeline(self.config, manager, inputs)++ _, kwargs = mock_source.call_args+ assert kwargs["app_secret_token"] == self.config.app_secret_token+ assert kwargs["agreement_grant_token"] == self.config.agreement_grant_token+ assert kwargs["endpoint"] == "customers"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"+ assert kwargs["incremental_field"] == "lastUpdated"++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.e_conomic.source.e_conomic_source")+ def test_source_for_pipeline_drops_last_value_when_not_incremental(self, mock_source: mock.MagicMock) -> None:+ inputs = _make_inputs(should_use_incremental_field=False, db_incremental_field_last_value="ignored")+ self.source.source_for_pipeline(self.config, mock.MagicMock(spec=ResumableSourceManager), inputs)++ _, kwargs = mock_source.call_args+ assert kwargs["db_incremental_field_last_value"] is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 7bd67e61fea8..1409219a51af 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -1005,7 +1005,8 @@ class DynamoDBSourceConfig(config.Config):@config.configclass EConomicSourceConfig(config.Config):- pass+ app_secret_token: str+ agreement_grant_token: str@config.config