: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 the sage intacct import source (#115589)
Tom Owers399ca0910724
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 215c3de0910b..4a7309385ee0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -711,6 +711,7 @@ the row lists both.| runpod | HTTP | requests | ✅ || safetyculture | HTTP | requests | ✅ || sage_hr | HTTP | requests | ✅ |+| sage_intacct | HTTP | requests + `rest_source.RESTClient` | ✅ || salesforce | HTTP | requests + `rest_source.RESTClient` | ✅ || salesflare | HTTP | requests | ✅ || salesloft | HTTP | requests | ✅ |@@ -1395,7 +1396,6 @@ doesn't conflict with concurrent PRs.- rocketlane- rss- safetyculture-- sage_intacct- sailthru- salesforce_marketing_cloud- salestricsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/sageintacct.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/sageintacct.pyindex ed28e77256e8..e230f015869e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/sageintacct.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/sageintacct.py@@ -6,4 +6,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass SageIntacctSourceConfig(config.Config):- pass+ client_id: str+ client_secret: str+ username: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sage_intacct/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sage_intacct/canonical_descriptions.pynew file mode 100644index 000000000000..442c4b407387--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sage_intacct/canonical_descriptions.py@@ -0,0 +1,42 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_COMMON_COLUMNS = {+ "key": "The system-assigned key for the Sage Intacct record.",+ "id": "The identifier for the Sage Intacct record.",+ "href": "The API path for this record.",+}++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "Customers": {+ "description": "A customer that buys goods or services from the company.",+ "docs_url": "https://developer.sage.com/intacct/apis/intacct/1/intacct-openapi",+ "columns": _COMMON_COLUMNS,+ },+ "Vendors": {+ "description": "A vendor that supplies goods or services to the company.",+ "docs_url": "https://developer.sage.com/intacct/apis/intacct/1/intacct-openapi",+ "columns": _COMMON_COLUMNS,+ },+ "Invoices": {+ "description": "An accounts receivable invoice that records charges to a customer.",+ "docs_url": "https://developer.sage.com/intacct/apis/intacct/1/intacct-openapi",+ "columns": _COMMON_COLUMNS,+ },+ "Bills": {+ "description": "An accounts payable bill that records charges from a vendor.",+ "docs_url": "https://developer.sage.com/intacct/apis/intacct/1/intacct-openapi",+ "columns": _COMMON_COLUMNS,+ },+ "GLAccounts": {+ "description": "A general ledger account in the company chart of accounts.",+ "docs_url": "https://developer.sage.com/intacct/apis/intacct/1/intacct-openapi",+ "columns": _COMMON_COLUMNS,+ },+ "JournalEntries": {+ "description": "A journal entry that records a transaction in the general ledger.",+ "docs_url": "https://developer.sage.com/intacct/apis/intacct/1/intacct-openapi",+ "columns": _COMMON_COLUMNS,+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sage_intacct/sage_intacct.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sage_intacct/sage_intacct.pynew file mode 100644index 000000000000..a61875f61dfa--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sage_intacct/sage_intacct.py@@ -0,0 +1,138 @@+from collections.abc import Iterator+from typing import Any+from urllib.parse import quote++from requests import Request, Response++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import OAuth2Auth+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ BasePaginator,+ SinglePagePaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import RESTClient+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.sageintacct import (+ SageIntacctSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.sage_intacct.settings import (+ BASE_URL,+ PAGE_SIZE,+ TOKEN_URL,+)+++@frozen+class SageIntacctResumeConfig:+ next_start: int+++class SageIntacctPaginator(BasePaginator):+ def __init__(self, start: int = 1) -> None:+ super().__init__()+ self.start = start++ def init_request(self, request: Request) -> None:+ self.update_request(request)++ def update_request(self, request: Request) -> None:+ if request.json is None:+ request.json = {}+ request.json["start"] = self.start++ def update_state(self, response: Response, data: list[Any] | None = None) -> None:+ body = response.json()+ if not isinstance(body, dict) or not isinstance(body.get("ia::result"), list):+ raise ValueError("Sage Intacct returned an invalid query result")+ metadata = body.get("ia::meta")+ if not isinstance(metadata, dict) or "next" not in metadata:+ raise ValueError("Sage Intacct returned no pagination metadata")+ next_start = metadata["next"]+ if next_start is None:+ self._has_next_page = False+ return+ if isinstance(next_start, bool) or not isinstance(next_start, int) or next_start <= self.start:+ raise ValueError("Sage Intacct pagination did not advance")+ self.start = next_start+ self._has_next_page = True++ def get_resume_state(self) -> dict[str, Any] | None:+ return {"next_start": self.start} if self.has_next_page else None+++def make_client(config: SageIntacctSourceConfig) -> RESTClient:+ return RESTClient(+ base_url=BASE_URL,+ auth=OAuth2Auth(+ token_url=TOKEN_URL,+ client_id=config.client_id,+ client_secret=config.client_secret,+ grant_type="client_credentials",+ extra_token_request_params={"username": config.username},+ ),+ allow_redirects=False,+ allowed_hosts=["api.intacct.com"],+ )+++def probe_credentials(config: SageIntacctSourceConfig, object_name: str) -> None:+ client = make_client(config)+ try:+ for _ in client.paginate(+ "services/core/query",+ method="POST",+ json={"object": object_name, "fields": ["key"], "start": 1, "size": 1},+ paginator=SageIntacctPaginator(),+ data_selector='["ia::result"]',+ data_selector_required=True,+ ):+ break+ finally:+ client.session.close()+++def sage_intacct_rows(+ config: SageIntacctSourceConfig,+ object_name: str,+ manager: ResumableSourceManager[SageIntacctResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ state = manager.load_state() if manager.can_resume() else None+ paginator = SageIntacctPaginator(start=state.next_start if state else 1)+ client = make_client(config)+ next_start: int | None = None++ def page_state_hook(next_state: dict[str, Any] | None, has_next_page: bool) -> None:+ nonlocal next_start+ next_start = next_state["next_start"] if next_state is not None else None++ try:+ for references in client.paginate(+ "services/core/query",+ method="POST",+ json={"object": object_name, "fields": ["key"], "orderBy": [{"key": "asc"}], "size": PAGE_SIZE},+ paginator=paginator,+ data_selector='["ia::result"]',+ data_selector_required=True,+ page_state_hook=page_state_hook,+ ):+ rows: list[dict[str, Any]] = []+ for reference in references:+ key = reference.get("key") if isinstance(reference, dict) else None+ if not isinstance(key, str) or not key:+ raise ValueError("Sage Intacct returned a record without a key")+ for records in client.paginate(+ f"objects/{object_name}/{quote(key, safe='')}",+ paginator=SinglePagePaginator(),+ data_selector='["ia::result"]',+ data_selector_required=True,+ ):+ if len(records) != 1 or not isinstance(records[0], dict) or records[0].get("key") != key:+ raise ValueError("Sage Intacct returned an invalid record")+ rows.append(records[0])+ # Save only after every record in this page is ready for the pipeline.+ if next_start is not None:+ manager.save_state(SageIntacctResumeConfig(next_start=next_start))+ yield rows+ finally:+ client.session.close()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sage_intacct/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sage_intacct/settings.pynew file mode 100644index 000000000000..236c3d3c354a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sage_intacct/settings.py@@ -0,0 +1,12 @@+BASE_URL = "https://api.intacct.com/ia/api/v1/"+TOKEN_URL = f"{BASE_URL}oauth2/token"+PAGE_SIZE = 100++ENDPOINTS = {+ "Customers": "accounts-receivable/customer",+ "Vendors": "accounts-payable/vendor",+ "Invoices": "accounts-receivable/invoice",+ "Bills": "accounts-payable/bill",+ "GLAccounts": "general-ledger/account",+ "JournalEntries": "general-ledger/journal-entry",+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sage_intacct/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sage_intacct/source.pyindex 3b38e18f94fc..98074965d0ed 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sage_intacct/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sage_intacct/source.py@@ -1,16 +1,52 @@from typing import cast-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from requests.exceptions import HTTPError++from products.warehouse_sources.backend.facade.source_config import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)+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.rest_source.auth import (+ OAUTH2_PERMANENT_ERROR_MARKER,+ OAuth2AuthRequestError,+)+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,+ schema_for_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.sageintacct import (SageIntacctSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.sage_intacct.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.sage_intacct.sage_intacct import (+ SageIntacctResumeConfig,+ probe_credentials,+ sage_intacct_rows,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.sage_intacct.settings import ENDPOINTSfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class SageIntacctSource(SimpleSource[SageIntacctSourceConfig]):+class SageIntacctSource(ResumableSource[SageIntacctSourceConfig, SageIntacctResumeConfig]):+ lists_tables_without_credentials = True+ supported_versions = ("v1",)+ default_version = "v1"+ api_docs_url = "https://developer.sage.com/intacct/apis/intacct/1/intacct-openapi"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.SAGEINTACCT@@ -21,7 +57,96 @@ class SageIntacctSource(SimpleSource[SageIntacctSourceConfig]):name=ExternalDataSourceType.SAGEINTACCT,category=DataWarehouseSourceCategory.FINANCE___ACCOUNTING,label="Sage Intacct",+ docsUrl="https://posthog.com/docs/cdp/sources/sage-intacct",iconPath="/static/services/sage_intacct.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="client_id",+ label="Client ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="client_secret",+ label="Client secret",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="username",+ label="Web services username",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="UserId@CompanyId",+ caption="Enter UserId@CompanyId or UserId@CompanyId|entityId for access to one entity.",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: SageIntacctSourceConfig,+ 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, {}, names)++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ OAUTH2_PERMANENT_ERROR_MARKER: "Check your Sage Intacct client credentials and web services username.",+ "401 Client Error": "Reconnect Sage Intacct with valid credentials.",+ "403 Client Error": "Give the Sage Intacct user read access to the selected tables.",+ }++ def validate_credentials(+ self,+ config: SageIntacctSourceConfig,+ team_id: int,+ schema_name: str | None = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ object_name = schema_for_resource(ENDPOINTS, schema_name or "Customers")+ try:+ probe_credentials(config, object_name)+ except OAuth2AuthRequestError as error:+ if not error.is_permanent:+ raise+ return False, "Check your Sage Intacct client credentials and web services username."+ except HTTPError as error:+ if error.response is None or error.response.status_code not in (400, 401, 403):+ raise+ return False, "Check your Sage Intacct credentials and read access to this table."+ return True, None++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SageIntacctResumeConfig]:+ return ResumableSourceManager(inputs, SageIntacctResumeConfig)++ def source_for_pipeline(+ self,+ config: SageIntacctSourceConfig,+ resumable_source_manager: ResumableSourceManager[SageIntacctResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ object_name = schema_for_resource(ENDPOINTS, inputs.schema_name)+ if inputs.should_use_incremental_field:+ raise ValueError("Sage Intacct tables require full refresh")+ return SourceResponse(+ name=inputs.schema_name,+ items=lambda: sage_intacct_rows(config, object_name, resumable_source_manager),+ primary_keys=["key"],)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sage_intacct/tests/test_sage_intacct.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sage_intacct/tests/test_sage_intacct.pynew file mode 100644index 000000000000..9603b1c7f455--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sage_intacct/tests/test_sage_intacct.py@@ -0,0 +1,183 @@+from typing import Any+from urllib.parse import parse_qs++import pytest++from requests.exceptions import HTTPError++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import (+ OAuth2AuthRequestError,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import UnknownResourceError+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (+ ScriptedResponse,+ SourceDriver,+ scripted_network,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.sageintacct import (+ SageIntacctSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.sage_intacct.sage_intacct import (+ SageIntacctResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.sage_intacct.source import SageIntacctSource+++def config() -> SageIntacctSourceConfig:+ return SageIntacctSourceConfig(client_id="example-client", client_secret="example-secret", username="user@example")+++def token() -> ScriptedResponse:+ return ScriptedResponse(json={"access_token": "example-access-token", "expires_in": 3600})+++def page(keys: list[str], next_start: int | None) -> ScriptedResponse:+ return ScriptedResponse(json={"ia::result": [{"key": key} for key in keys], "ia::meta": {"next": next_start}})+++def record(key: str) -> ScriptedResponse:+ return ScriptedResponse(json={"ia::result": {"key": key, "name": "Example", "audit": {"modifiedBy": "1"}}})+++ ("schema", "object_name"),+ [+ ("Customers", "accounts-receivable/customer"),+ ("Vendors", "accounts-payable/vendor"),+ ("Invoices", "accounts-receivable/invoice"),+ ("Bills", "accounts-payable/bill"),+ ("GLAccounts", "general-ledger/account"),+ ("JournalEntries", "general-ledger/journal-entry"),+ ],+)+def test_query_pages_hydrate_records_and_commit_checkpoint(schema: str, object_name: str) -> None:+ result = SourceDriver(SageIntacctSource(), config()).run(+ schema, [token(), page(["7"], 20), record("7"), page(["20"], None), record("20")]+ )+ assert result.raised is None+ assert [row["key"] for row in result.rows] == ["7", "20"]+ assert result.rows[0]["audit"] == {"modifiedBy": "1"}+ assert [result.requests[i].json()["start"] for i in (1, 3)] == [1, 20]+ assert result.requests[1].json() == {+ "object": object_name,+ "fields": ["key"],+ "orderBy": [{"key": "asc"}],+ "size": 100,+ "start": 1,+ }+ assert result.paths[2] == f"/ia/api/v1/objects/{object_name}/7"+ assert result.saved_states == result.committed_states == [SageIntacctResumeConfig(next_start=20)]+ assert parse_qs((result.requests[0].body or b"").decode()) == {+ "grant_type": ["client_credentials"],+ "client_id": ["example-client"],+ "client_secret": ["example-secret"],+ "username": ["user@example"],+ }+ assert all(request.headers["authorization"] == "Bearer example-access-token" for request in result.requests[1:])+++def test_resume_starts_at_saved_page_and_ignores_reference_href() -> None:+ result = SourceDriver(SageIntacctSource(), config()).run(+ "Customers",+ [+ token(),+ ScriptedResponse(+ json={+ "ia::result": [{"key": "7", "href": "https://example.com/untrusted"}],+ "ia::meta": {"next": None},+ }+ ),+ record("7"),+ ],+ resume_state=SageIntacctResumeConfig(next_start=20),+ )+ assert result.raised is None+ assert result.requests[1].json()["start"] == 20+ assert result.requests[2].origin == "https://api.intacct.com"+ assert result.rows[0]["key"] == "7"+++def test_failed_detail_does_not_commit_parent_page() -> None:+ result = SourceDriver(SageIntacctSource(), config()).run(+ "Customers", [token(), page(["7", "8"], 20), record("7"), ScriptedResponse(status=403, json={})]+ )+ assert isinstance(result.raised, HTTPError)+ assert result.rows == []+ assert result.saved_states == result.committed_states == []+++ ("body", "message"),+ [+ ({"ia::result": [], "ia::meta": {"next": 1}}, "did not advance"),+ ({"ia::result": [], "ia::meta": {"next": True}}, "did not advance"),+ ({"ia::result": [], "ia::meta": {"next": "20"}}, "did not advance"),+ ({"ia::result": []}, "no pagination metadata"),+ ({"ia::result": {}, "ia::meta": {"next": None}}, "invalid query result"),+ ({"ia::error": {"code": "example-error"}}, "Required data_selector"),+ ({"ia::result": [{}], "ia::meta": {"next": None}}, "without a key"),+ ],+)+def test_bad_query_results_fail_without_silent_data_loss(body: dict[str, Any], message: str) -> None:+ result = SourceDriver(SageIntacctSource(), config()).run("Customers", [token(), ScriptedResponse(json=body)])+ assert isinstance(result.raised, ValueError)+ assert message in str(result.raised)+ assert result.rows == []++[email protected]("body", [{"ia::result": None}, {"ia::result": {"key": "other"}}, {"ia::result": []}])+def test_invalid_detail_fails_before_checkpoint(body: dict[str, Any]) -> None:+ result = SourceDriver(SageIntacctSource(), config()).run(+ "Customers", [token(), page(["7"], 20), ScriptedResponse(json=body)]+ )+ assert isinstance(result.raised, ValueError)+ assert result.saved_states == []+++def test_empty_query_finishes_without_detail_requests() -> None:+ result = SourceDriver(SageIntacctSource(), config()).run("Customers", [token(), page([], None)])+ assert result.raised is None+ assert result.rows == []+ assert len(result.requests) == 2++[email protected]("status", [400, 401, 403])+def test_credential_probe_reports_read_or_auth_failure(status: int) -> None:+ with scripted_network([token(), ScriptedResponse(status=status, json={})]) as network:+ valid, message = SageIntacctSource().validate_credentials(config(), 1, schema_name="Bills")+ assert valid is False+ assert message == "Check your Sage Intacct credentials and read access to this table."+ assert network.requests_log[1].json()["object"] == "accounts-payable/bill"+++def test_credential_probe_success() -> None:+ with scripted_network([token(), page([], None)]) as network:+ assert SageIntacctSource().validate_credentials(config(), 1) == (True, None)+ assert network.requests_log[1].json()["size"] == 1++[email protected]("status", [400, 503])+def test_token_failure_distinguishes_permanent_from_transient(status: int) -> None:+ with scripted_network([ScriptedResponse(status=status, json={"error": "invalid_client"})]):+ if status == 503:+ with pytest.raises(OAuth2AuthRequestError):+ SageIntacctSource().validate_credentials(config(), 1)+ else:+ valid, message = SageIntacctSource().validate_credentials(config(), 1)+ assert valid is False+ assert message == "Check your Sage Intacct client credentials and web services username."+++ ("schema", "inputs", "error"),+ [+ ("Unknown", {}, UnknownResourceError),+ ("Customers", {"incremental_field": "key"}, ValueError),+ ],+)+def test_unsupported_table_or_sync_mode_fails_before_network(+ schema: str, inputs: dict[str, Any], error: type[Exception]+) -> None:+ result = SourceDriver(SageIntacctSource(), config()).run(schema, [], **inputs)+ assert isinstance(result.raised, error)+ assert result.requests == []