Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): add e-conomic orders and ledger entry tables (#115317)

Tom Owersadb5a7679ad0
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
index c88833615e14..4424b884a6f0 100644
--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
@@ -514,8 +514,6 @@
1 products/warehouse_sources/backend/temporal/data_imports/sources/dynatrace/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/e2b/e2b.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/e2b/settings.py
-1 products/warehouse_sources/backend/temporal/data_imports/sources/e_conomic/e_conomic.py
-1 products/warehouse_sources/backend/temporal/data_imports/sources/e_conomic/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/easypost/easypost.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/easypost/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/easypromos/easypromos.py
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 433724649363..76a993c36e72 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -2813,10 +2813,10 @@ Today (18): `accounting_years`, `accounts`, `currencies`, `customer_groups`, `cu
Diffed against: <https://restdocs.e-conomic.com/>
-- [ ] `GET /journals/{journalNumber}/entries` — the actual accounting entries; today only the journal headers are synced, so no transaction-level ledger exists (high)
-- [ ] `GET /accounting-years/{year}/entries` — full general-ledger entry stream for a financial year - the core fact table of the whole API (high)
-- [ ] `GET /accounts/{accountNumber}/accounting-years/{year}/entries` — per-account ledger entries, letting you reconcile the accounts table already synced (high)
-- [ ] `GET /orders, /orders/drafts, /orders/sent, /orders/archived` — sales orders with their state slices - the pre-invoice half of the revenue pipeline is entirely missing (high)
+- [x] `GET /journals/{journalNumber}/entries` — the actual accounting entries; today only the journal headers are synced, so no transaction-level ledger exists (high)
+- [x] `GET /accounting-years/{year}/entries` — full general-ledger entry stream for a financial year - the core fact table of the whole API (high)
+- [ ] `GET /accounts/{accountNumber}/accounting-years/{year}/entries` — per-account ledger entries, letting you reconcile the accounts table already synced (high). Skipped: it returns a per-account subset of `/accounting-years/{year}/entries`, which is now synced as `accounting_year_entries` and carries `account` on every row, so a second table would only duplicate it.
+- [x] `GET /orders, /orders/drafts, /orders/sent, /orders/archived` — sales orders with their state slices - the pre-invoice half of the revenue pipeline is entirely missing (high)
- [ ] `GET /vat-types and GET /vat-accounts` — VAT code lookup resolving the vatZone/vatAccount references already carried on accounts, products and invoice lines (high)
- [ ] `GET /accounting-years/{year}/totals and /accounting-years/{year}/periods/{p}/totals` — account balances per year and per period - the trial-balance figures, without recomputing from entries (high)
- [ ] `GET /accounting-years/{year}/periods` — accounting-period lookup that every entry and total is bucketed by (medium)
diff --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.md
index ae51b9108585..33777d2e85b9 100644
--- 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.md
@@ -33,34 +33,50 @@ live API (`https://restapi.e-conomic.com`) using e-conomic's public demo agreeme
## 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 |
+| 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 |
+| `orders_drafts` | `/orders/drafts` | `orderNumber` | `orderNumber` | full refresh | rows leave the table when the order is sent |
+| `orders_sent` | `/orders/sent` | `orderNumber` | `orderNumber` | full refresh | rows leave the table when the order is archived |
+| `orders_archived` | `/orders/archived` | `orderNumber` | `orderNumber` | full refresh | no `lastUpdated`; partition by `date` |
+| `accounting_year_entries` | `/accounting-years/{year}/entries` | `accountingYear`, `entryNumber` | `entryNumber` | full refresh | fan-out over `accounting_years` via each year's `entries` link |
+| `journal_entries` | `/journals/{n}/entries` | `journalNumber`, `journalEntryNumber` | `journalEntryNumber` | full refresh | fan-out over `journals`; unbooked entries only |
## 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.
+## Fan-out endpoints
+
+- `accounting_year_entries` reads `/accounting-years/{year}/entries` once per accounting year. A year
+ that spans two calendar years is named `YYYY/YYYY` but uses another form in URLs, so the path comes
+ from the parent row's `entries` link. The entry number restarts with each accounting year, so the
+ year is part of the primary key.
+- `journal_entries` reads `/journals/{journalNumber}/entries` once per journal. These are entries that
+ are not booked yet; booking moves them to the accounting-year entries.
+- Both are full refresh. Resume state records which parents finished and the page of the current one.
+- `/accounts/{accountNumber}/accounting-years/{year}/entries` is not synced: it returns a per-account
+ subset of `accounting_year_entries`, which already carries `account`.
+
## 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`).
+Other sub-resources (customer contacts, invoice lines, vouchers, totals, periods) and the separate
+sub-APIs on `apis.e-conomic.com` (subscriptions, etc.) are out of scope for now.
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.py
index 3a0954ad106a..15f767de76c8 100644
--- 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.py
@@ -229,4 +229,122 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"lastUpdated": "Timestamp of the last modification to the draft.",
},
},
+ "orders_drafts": {
+ "description": "A draft sales order that has not been sent to the customer yet.",
+ "docs_url": "https://restdocs.e-conomic.com/#get-orders-drafts",
+ "columns": {
+ "orderNumber": "Reference number of the order.",
+ "date": "Order issue date.",
+ "dueDate": "Date the order is due for payment.",
+ "currency": "Order currency (ISO 4217 code).",
+ "exchangeRate": "Exchange rate between the order currency and the base currency.",
+ "netAmount": "Total amount before taxes and discounts, in the order currency.",
+ "netAmountInBaseCurrency": "Total amount before taxes and discounts, in the base currency.",
+ "grossAmount": "Total amount after taxes and discounts, in the order currency.",
+ "grossAmountInBaseCurrency": "Total amount after taxes and discounts, in the base currency.",
+ "marginInBaseCurrency": "Difference between the cost price of the items and the net order amount, in the base currency.",
+ "marginPercentage": "Margin as a percentage of the net order amount.",
+ "vatAmount": "Total VAT on the order, in the order currency.",
+ "costPriceInBaseCurrency": "Total cost of the items on the order, in the base currency.",
+ "customer": "The customer the order is for.",
+ "paymentTerms": "Payment terms applied to the order.",
+ "recipient": "The actual recipient of the order.",
+ "project": "The project the order is connected to.",
+ "lastUpdated": "Timestamp of the last modification to the order.",
+ },
+ },
+ "orders_sent": {
+ "description": "A sales order that has been sent to the customer but not yet archived.",
+ "docs_url": "https://restdocs.e-conomic.com/#get-orders-sent",
+ "columns": {
+ "orderNumber": "Reference number of the order.",
+ "date": "Order issue date.",
+ "dueDate": "Date the order is due for payment.",
+ "currency": "Order currency (ISO 4217 code).",
+ "exchangeRate": "Exchange rate between the order currency and the base currency.",
+ "netAmount": "Total amount before taxes and discounts, in the order currency.",
+ "netAmountInBaseCurrency": "Total amount before taxes and discounts, in the base currency.",
+ "grossAmount": "Total amount after taxes and discounts, in the order currency.",
+ "grossAmountInBaseCurrency": "Total amount after taxes and discounts, in the base currency.",
+ "marginInBaseCurrency": "Difference between the cost price of the items and the net order amount, in the base currency.",
+ "marginPercentage": "Margin as a percentage of the net order amount.",
+ "vatAmount": "Total VAT on the order, in the order currency.",
+ "costPriceInBaseCurrency": "Total cost of the items on the order, in the base currency.",
+ "customer": "The customer the order is for.",
+ "paymentTerms": "Payment terms applied to the order.",
+ "recipient": "The actual recipient of the order.",
+ "project": "The project the order is connected to.",
+ },
+ },
+ "orders_archived": {
+ "description": "An archived sales order, typically one that has been turned into an invoice.",
+ "docs_url": "https://restdocs.e-conomic.com/#get-orders-archived",
+ "columns": {
+ "orderNumber": "Reference number of the order.",
+ "date": "Order issue date.",
+ "dueDate": "Date the order is due for payment.",
+ "currency": "Order currency (ISO 4217 code).",
+ "exchangeRate": "Exchange rate between the order currency and the base currency.",
+ "netAmount": "Total amount before taxes and discounts, in the order currency.",
+ "netAmountInBaseCurrency": "Total amount before taxes and discounts, in the base currency.",
+ "grossAmount": "Total amount after taxes and discounts, in the order currency.",
+ "grossAmountInBaseCurrency": "Total amount after taxes and discounts, in the base currency.",
+ "marginInBaseCurrency": "Difference between the cost price of the items and the net order amount, in the base currency.",
+ "marginPercentage": "Margin as a percentage of the net order amount.",
+ "vatAmount": "Total VAT on the order, in the order currency.",
+ "costPriceInBaseCurrency": "Total cost of the items on the order, in the base currency.",
+ "customer": "The customer the order is for.",
+ "paymentTerms": "Payment terms applied to the order.",
+ "recipient": "The actual recipient of the order.",
+ "project": "The project the order is connected to.",
+ },
+ },
+ "accounting_year_entries": {
+ "description": "A booked general-ledger entry, listed per accounting year. One row per posting to an account.",
+ "docs_url": "https://restdocs.e-conomic.com/#get-accounting-years-accountingyear-entries",
+ "columns": {
+ "accountingYear": "The accounting year the entry is booked in, in the format YYYY or YYYY/YYYY.",
+ "entryNumber": "Identifier of the entry line within its accounting year.",
+ "account": "The account the entry is posted to.",
+ "amount": "Entry amount in the entry currency.",
+ "amountInBaseCurrency": "Entry amount in the base currency.",
+ "currency": "Entry currency (ISO 4217 code).",
+ "date": "Entry date.",
+ "dueDate": "Date the related invoice is due for payment.",
+ "entryType": "The type of entry, for example a customer invoice, a customer payment or a finance voucher.",
+ "text": "Short description of the entry.",
+ "voucherNumber": "Identifier of the voucher the entry belongs to.",
+ "customer": "The customer the entry relates to, if any.",
+ "supplier": "The supplier the entry relates to, if any.",
+ "supplierInvoiceNumber": "Identifier of the supplier invoice, if any.",
+ "bookedInvoice": "The booked invoice the entry relates to, if any.",
+ "vatAccount": "The account used for VAT.",
+ "remainder": "Remaining open amount on the entry.",
+ "remainderInBaseCurrency": "Remaining open amount on the entry, in the base currency.",
+ "project": "The project the entry relates to, if any.",
+ "departmentalDistribution": "The departments the entry is distributed between.",
+ },
+ },
+ "journal_entries": {
+ "description": "An entry waiting in a journal (daybook) that has not been booked yet. Booking moves it to the general ledger.",
+ "docs_url": "https://restdocs.e-conomic.com/#get-journals-journalnumber-entries",
+ "columns": {
+ "journalNumber": "The journal the entry is in.",
+ "journalEntryNumber": "Identifier of the entry in the journal.",
+ "entryType": "The type of entry.",
+ "date": "Entry date.",
+ "dueDate": "Date the entry is due for payment.",
+ "amount": "Entry amount.",
+ "amountDefaultCurrency": "Entry amount in the base currency.",
+ "account": "The account the entry is posted to.",
+ "contraAccount": "The account used for the funds.",
+ "currency": "The entry currency.",
+ "exchangeRate": "Exchange rate between the base currency and the entry currency.",
+ "text": "Text on the entry.",
+ "voucher": "The voucher the entry belongs to.",
+ "customer": "The customer the entry is based on, if any.",
+ "supplier": "The supplier the entry is based on, if any.",
+ "supplierInvoiceNumber": "Identifier of the supplier invoice, if any.",
+ },
+ },
}
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.py
index d3d232bf4b59..7917e2a53833 100644
--- 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.py
@@ -11,26 +11,32 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
rest_api_resource,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import AuthConfigBase
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ build_dependent_resource,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
JSONResponsePaginator,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ClientConfig
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.e_conomic.settings import E_CONOMIC_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.e_conomic.settings import (
+ E_CONOMIC_ENDPOINTS,
+ PAGE_SIZE,
+)
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
-
[email protected](frozen=True)
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
+ # Fan-out endpoints instead checkpoint which parents finished and where the current one stopped.
+ fanout_state: Optional[dict[str, Any]] = None
def _headers() -> dict[str, str]:
@@ -104,6 +110,27 @@ class EConomicNextPagePaginator(JSONResponsePaginator):
_assert_trusted_url(self._next_url)
+def _add_entries_path(row: dict[str, Any]) -> dict[str, Any]:
+ row["entries_path"] = urlparse(row["entries"]).path
+ return row
+
+
+_PARENT_DATA_MAPS = {"accounting_year_entries": _add_entries_path}
+
+
+def _client_config(app_secret_token: str, agreement_grant_token: str) -> ClientConfig:
+ return {
+ "base_url": E_CONOMIC_BASE_URL,
+ "headers": _headers(),
+ "auth": EConomicTokenAuth(app_secret_token, agreement_grant_token),
+ "paginator": EConomicNextPagePaginator(),
+ # Pin every request — including next-page and seeded resume URLs — to the API host, and
+ # refuse redirects, so the credential headers can never be carried off-host.
+ "allowed_hosts": [E_CONOMIC_HOST],
+ "allow_redirects": False,
+ }
+
+
def e_conomic_source(
app_secret_token: str,
agreement_grant_token: str,
@@ -116,6 +143,41 @@ def e_conomic_source(
incremental_field: str | None = None,
) -> SourceResponse:
config = E_CONOMIC_ENDPOINTS[endpoint]
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+
+ if config.fanout is not None:
+
+ def save_fanout_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ if state:
+ resumable_source_manager.save_state(EConomicResumeConfig(fanout_state=state))
+
+ child = build_dependent_resource(
+ endpoint_configs=E_CONOMIC_ENDPOINTS,
+ child_endpoint=endpoint,
+ fanout=config.fanout,
+ client_config=_client_config(app_secret_token, agreement_grant_token),
+ parent_data_map=_PARENT_DATA_MAPS.get(endpoint),
+ parent_endpoint_extra={"data_selector": "collection"},
+ # Explicit, because the framework treats a path ending in a placeholder ("{entries_path}") as a
+ # single-entity lookup and would otherwise fetch only its first page.
+ child_endpoint_extra={"data_selector": "collection", "paginator": EConomicNextPagePaginator()},
+ page_size_param="pagesize",
+ path_format_values={},
+ team_id=team_id,
+ job_id=job_id,
+ db_incremental_field_last_value=None,
+ resume_hook=save_fanout_checkpoint,
+ initial_paginator_state=resume.fanout_state if resume else None,
+ )
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: child,
+ primary_keys=config.primary_keys,
+ sort_mode=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,
+ )
params: dict[str, Any] = {"pagesize": PAGE_SIZE}
if config.sort:
@@ -129,16 +191,7 @@ def e_conomic_source(
params["filter"] = f"{incremental_field}$gte:{formatted}"
rest_config: RESTAPIConfig = {
- "client": {
- "base_url": E_CONOMIC_BASE_URL,
- "headers": _headers(),
- "auth": EConomicTokenAuth(app_secret_token, agreement_grant_token),
- "paginator": EConomicNextPagePaginator(),
- # Pin every request — including next-page and seeded resume URLs — to the API host, and
- # refuse redirects, so the credential headers can never be carried off-host.
- "allowed_hosts": [E_CONOMIC_HOST],
- "allow_redirects": False,
- },
+ "client": _client_config(app_secret_token, agreement_grant_token),
"resource_defaults": {},
"resources": [
{
@@ -155,10 +208,8 @@ def e_conomic_source(
}
initial_paginator_state: Optional[dict[str, Any]] = None
- if resumable_source_manager.can_resume():
- resume = resumable_source_manager.load_state()
- if resume is not None and resume.next_url:
- initial_paginator_state = {"next_url": resume.next_url}
+ if resume is not None and resume.next_url:
+ initial_paginator_state = {"next_url": resume.next_url}
def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
# Persist only when a next page remains; saved AFTER a page is yielded so a crash re-yields the
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.py
index 7aec7e4d2957..f2e9db6e2f18 100644
--- 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.py
@@ -1,14 +1,20 @@
from dataclasses import dataclass, field
from typing import Optional
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ DependentEndpointConfig,
+)
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+# Max page size the API allows for classic offset pagination.
+PAGE_SIZE = 1000
+
def _incremental_field(name: str, field_type: IncrementalFieldType) -> IncrementalField:
return {"label": name, "type": field_type, "field": name, "field_type": field_type}
-@dataclass
+@dataclass(frozen=True)
class EConomicEndpointConfig:
name: str
# Path on https://restapi.e-conomic.com. Uses hyphens (e.g. /customer-groups) while the schema/table
@@ -22,12 +28,17 @@ class EConomicEndpointConfig:
# 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).
+ # (only for tiny single-page endpoints whose number field the API refuses to sort by). Fan-out
+ # children sort through `fanout.child_params` instead: rows are only ordered within one parent.
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
+ # Set for per-parent sub-collections (e.g. entries per accounting year).
+ fanout: Optional[DependentEndpointConfig] = None
+ page_size: int = PAGE_SIZE
+ default_incremental_field: Optional[str] = None
# Endpoint catalog. Incremental support is set ONLY where the live API honors a server-side timestamp /
@@ -153,6 +164,62 @@ E_CONOMIC_ENDPOINTS: dict[str, EConomicEndpointConfig] = {
# can't be guaranteed ascending for a watermark — full refresh only.
sort="draftInvoiceNumber",
),
+ # Orders move draft -> sent -> archived, so a row leaves the drafts and sent tables when its state
+ # changes. Full refresh keeps each table an exact snapshot of its state slice.
+ "orders_drafts": EConomicEndpointConfig(
+ name="orders_drafts",
+ path="/orders/drafts",
+ primary_keys=["orderNumber"],
+ sort="orderNumber",
+ ),
+ "orders_sent": EConomicEndpointConfig(
+ name="orders_sent",
+ path="/orders/sent",
+ primary_keys=["orderNumber"],
+ sort="orderNumber",
+ ),
+ "orders_archived": EConomicEndpointConfig(
+ name="orders_archived",
+ path="/orders/archived",
+ primary_keys=["orderNumber"],
+ sort="orderNumber",
+ # Archived orders carry no `lastUpdated` to filter on, so full refresh only.
+ partition_key="date",
+ ),
+ "accounting_year_entries": EConomicEndpointConfig(
+ name="accounting_year_entries",
+ path="{entries_path}",
+ # The entry number restarts with each accounting year, so the year is part of the key.
+ primary_keys=["accountingYear", "entryNumber"],
+ partition_key="date",
+ fanout=DependentEndpointConfig(
+ parent_name="accounting_years",
+ # Years spanning two calendar years ("2022/2023") use a different form in URLs, so the
+ # path comes from the parent's own `entries` link rather than from `year`.
+ resolve_param="entries_path",
+ resolve_field="entries_path",
+ include_from_parent=["year"],
+ parent_field_renames={"year": "accountingYear"},
+ parent_params={"sort": "year"},
+ child_params={"sort": "entryNumber"},
+ ),
+ ),
+ # Entries still in a journal, not yet booked. Booking moves them to accounting_year_entries, so
+ # full refresh only.
+ "journal_entries": EConomicEndpointConfig(
+ name="journal_entries",
+ path="/journals/{journalNumber}/entries",
+ primary_keys=["journalNumber", "journalEntryNumber"],
+ fanout=DependentEndpointConfig(
+ parent_name="journals",
+ resolve_param="journalNumber",
+ resolve_field="journalNumber",
+ include_from_parent=["journalNumber"],
+ parent_field_renames={"journalNumber": "journalNumber"},
+ parent_params={"sort": "journalNumber"},
+ child_params={"sort": "journalEntryNumber"},
+ ),
+ ),
}
ENDPOINTS = tuple(E_CONOMIC_ENDPOINTS.keys())
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.py
index b31e74d43c11..26b3b7b0168f 100644
--- 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.py
@@ -174,6 +174,62 @@ class TestPagination:
assert params[0]["url"] == resume_url
+class TestAccountingYearEntriesFanout:
+ def _years_page(self) -> Response:
+ return _response(
+ [
+ {"year": "2022", "entries": f"{E_CONOMIC_BASE_URL}/accounting-years/2022/entries"},
+ {"year": "2022/2023", "entries": f"{E_CONOMIC_BASE_URL}/accounting-years/2022_6_2023/entries"},
+ ]
+ )
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_walks_each_year_through_its_entries_link(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ second_page = f"{E_CONOMIC_BASE_URL}/accounting-years/2022/entries?skippages=1"
+ requests_sent = _wire(
+ session,
+ [
+ self._years_page(),
+ _response([{"entryNumber": 1}], next_page=second_page),
+ _response([{"entryNumber": 2}]),
+ _response([{"entryNumber": 1}]),
+ ],
+ )
+
+ rows = _rows(_source("accounting_year_entries", _make_manager()))
+
+ assert [(r["accountingYear"], r["entryNumber"]) for r in rows] == [
+ ("2022", 1),
+ ("2022", 2),
+ ("2022/2023", 1),
+ ]
+ assert [r["url"] for r in requests_sent] == [
+ f"{E_CONOMIC_BASE_URL}/accounting-years",
+ f"{E_CONOMIC_BASE_URL}/accounting-years/2022/entries",
+ second_page,
+ f"{E_CONOMIC_BASE_URL}/accounting-years/2022_6_2023/entries",
+ ]
+ assert requests_sent[1]["params"]["sort"] == "entryNumber"
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_resume_skips_completed_years(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ requests_sent = _wire(session, [self._years_page(), _response([{"entryNumber": 5}])])
+ manager = _make_manager(
+ EConomicResumeConfig(
+ fanout_state={"completed": ["/accounting-years/2022/entries"], "current": None, "child_state": None}
+ )
+ )
+
+ rows = _rows(_source("accounting_year_entries", manager))
+
+ assert [(r["accountingYear"], r["entryNumber"]) for r in rows] == [("2022/2023", 5)]
+ assert requests_sent[-1]["url"] == f"{E_CONOMIC_BASE_URL}/accounting-years/2022_6_2023/entries"
+ saved = manager.save_state.call_args.args[0]
+ assert "/accounting-years/2022_6_2023/entries" in saved.fanout_state["completed"]
+
+
class TestErrorHandling:
@parameterized.expand([("server_error", 500), ("bad_gateway", 503), ("throttled", 429)])
@mock.patch(CLIENT_SESSION_PATCH)