: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(campfire): add product, customer, entity and subscription tables (#101621)
Tom Owers6c95a9f7488a
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.mdindex fc4802c17926..21b732eb609c 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@@ -1228,14 +1228,14 @@ Note: The official API docs list exactly six endpoint groups: Lists, Contacts, F## Campfire — gaps-Today (15): `bank_accounts`, `bank_transactions`, `bill_payments`, `bills`, `chart_of_accounts`, `chart_transactions`, `contracts`, `credit_memos`, `debit_memos`, `departments`, `invoice_payments`, `invoices`, `journal_entries`, `revenue_transactions`, `vendors`+Today (19): `bank_accounts`, `bank_transactions`, `bill_payments`, `bills`, `chart_entities`, `chart_of_accounts`, `chart_transactions`, `contract_subscriptions`, `contracts`, `credit_memos`, `customers`, `debit_memos`, `departments`, `invoice_payments`, `invoices`, `journal_entries`, `products`, `revenue_transactions`, `vendors`Diffed against: <https://docs.campfire.ai/llms.txt>-- [ ] `revenue-recognition/list-contract-products` — contract line items - the revenue detail behind every contract we already sync (high)-- [ ] `revenue-recognition/list-contract-subscriptions` — subscription schedules per contract, needed for ARR/MRR and rev-rec waterfalls (high)-- [ ] `revenue-recognition/list-contract-customers` — lookup table resolving the customer IDs carried on contracts, invoices and revenue transactions (high)-- [ ] `settings/list-chart-entities` — legal entity lookup - every transaction carries an entity ID and multi-entity consolidation is unusable without it (high)+- [x] `revenue-recognition/list-contract-products` — the product catalog behind every contract line item (high)+- [x] `revenue-recognition/list-contract-subscriptions` — subscription schedules per contract, needed for ARR/MRR and rev-rec waterfalls (high)+- [x] `revenue-recognition/list-contract-customers` — lookup table resolving the customer IDs carried on contracts, invoices and revenue transactions (high)+- [x] `settings/list-chart-entities` — legal entity lookup - every transaction carries an entity ID and multi-entity consolidation is unusable without it (high)- [ ] `company-objects/list-custom-dimensions (+ list-custom-dimension-groups)` — the breakdown dimensions tagged on chart transactions and journal entries (medium)- [ ] `revenue-recognition/list-contract-milestones` — milestone-based recognition triggers on contracts we sync (medium)- [ ] `core-accounting/list-fixed-assets` — fixed asset register and depreciation, a whole ledger area currently absent (medium)@@ -1245,7 +1245,7 @@ Diffed against: <https://docs.campfire.ai/llms.txt>- [ ] `core-accounting/list-intercompany-journal-entries` — intercompany JEs are excluded from the journal_entries table today (medium)- [ ] `financial-statements/get-trial-balance (also get-general-ledger, get-balance-sheet, get-income-statement)` — vendor-computed statement rollups users would otherwise rebuild by hand from chart_transactions (medium)-Note: Campfire has no public OpenAPI (docs.campfire.ai/openapi.json 404s) but ships a complete llms.txt index of ~330 documented operations. Note there is no bare list-products endpoint - products are only reachable via list-contract-products and list-product-bundles.+Note: Campfire has no public OpenAPI (docs.campfire.ai/openapi.json 404s) but ships a complete llms.txt index of ~330 documented operations. list-contract-products is the product catalog listing (GET /rr/api/v1/product) rather than a per-contract endpoint, so it covers products on its own; list-product-bundles is still a separate gap. list-contract-subscriptions is only reachable per contract (GET /rr/api/v1/contracts/{contract_id}/subscriptions), so contract_subscriptions fans out over the contracts table.## Canny — gapsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/campfire/campfire.py b/products/warehouse_sources/backend/temporal/data_imports/sources/campfire/campfire.pyindex 3845a6976123..d16540296b23 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/campfire/campfire.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/campfire/campfire.py@@ -1,13 +1,19 @@-import dataclasses+from collections.abc import Iterablefrom datetime import UTC, date, datetime-from typing import Any, Optional+from typing import Any, Optional, castfrom urllib.parse import urlencode, urlparsefrom requests import PreparedRequest, Response+from posthog.dataclasses import frozen+from products.warehouse_sources.backend.temporal.data_imports.sources.campfire.settings import (CAMPFIRE_BASE_URL,CAMPFIRE_ENDPOINTS,+ LAST_MODIFIED_AT,+ LAST_MODIFIED_AT_PARAM,+ REQUEST_TIMEOUT_SECONDS,+ CampfireEndpointConfig,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (@@ -15,19 +21,33 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resrest_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,+ IncrementalConfig,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+@frozenclass CampfireResumeConfig:- # The `next` link of the last fully-yielded page. Absolute URL on api.meetcampfire.com,- # carrying the pagination cursor/offset plus any incremental filter for this job.- next_url: str+ # Top-level endpoints resume from the `next` link of the last fully-yielded page. Absolute+ # URL on api.meetcampfire.com, carrying the pagination cursor/offset plus any incremental+ # filter for this job.+ next_url: str | None = None+ # Fan-out endpoints resume by parent: the contract paths already fully synced, the contract+ # in progress, and that contract's paginator state — see+ # `common.rest_source.__init__._make_paginate_dependent_resource`.+ completed: list[str] | None = None+ current: str | None = None+ child_state: dict[str, Any] | None = Noneclass CampfireTokenAuth(AuthConfigBase):@@ -89,39 +109,62 @@ def _format_incremental_value(value: Any) -> str:return str(value)-def campfire_source(+def _client_config(api_key: str) -> ClientConfig:+ # capture=False keeps accounting responses (amounts, invoice/transaction IDs, free-form+ # business fields the name-based scrubbers can't recognise) out of HTTP sample storage.+ session = make_tracked_session(redact_values=(api_key,), capture=False)+ return {+ "base_url": CAMPFIRE_BASE_URL,+ # Auth (the Token header) is supplied via the framework auth config so its value is+ # redacted from logs; only the non-secret Accept header is set here.+ "headers": {"Accept": "application/json"},+ "auth": CampfireTokenAuth(api_key),+ "session": session,+ "paginator": CampfireNextUrlPaginator(),+ "request_timeout": REQUEST_TIMEOUT_SECONDS,+ }+++def _incremental_config(field_name: str) -> IncrementalConfig | None:+ """Bind a fan-out child's cursor to Campfire's server-side `last_modified_at` filter.++ None for any other field, which leaves the child merging on its primary key with no+ request window rather than sending a filter the endpoint does not have.+ """+ if field_name != LAST_MODIFIED_AT:+ return None+ return {+ "cursor_path": LAST_MODIFIED_AT,+ "start_param": LAST_MODIFIED_AT_PARAM,+ # The framework sends the param on every request, so a first sync needs a floor that+ # selects everything.+ "initial_value": "1970-01-01T00:00:00Z",+ "convert": _format_incremental_value,+ }+++def _top_level_resource(+ config: CampfireEndpointConfig,api_key: str,endpoint: str,team_id: int,job_id: str,resumable_source_manager: ResumableSourceManager[CampfireResumeConfig],- should_use_incremental_field: bool = False,- db_incremental_field_last_value: Optional[Any] = None,-) -> SourceResponse:- config = CAMPFIRE_ENDPOINTS[endpoint]-- params: dict[str, Any] = {"limit": config.page_size, **config.extra_params}+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Optional[Any],+) -> Iterable[Any]:+ params: dict[str, Any] = {**config.extra_params}+ if config.paginated:+ params["limit"] = config.page_sizeif config.use_cursor:# An empty `cursor=` opts the endpoint into cursor pagination; every later page# comes from the response's `next` link.params["cursor"] = ""if should_use_incremental_field and config.incremental_fields and db_incremental_field_last_value is not None:- params["last_modified_at__gte"] = _format_incremental_value(db_incremental_field_last_value)-- # capture=False keeps accounting responses (amounts, invoice/transaction IDs, free-form- # business fields the name-based scrubbers can't recognise) out of HTTP sample storage.- session = make_tracked_session(redact_values=(api_key,), capture=False)+ params[LAST_MODIFIED_AT_PARAM] = _format_incremental_value(db_incremental_field_last_value)rest_config: RESTAPIConfig = {- "client": {- "base_url": CAMPFIRE_BASE_URL,- # Auth (the Token header) is supplied via the framework auth config so its value is- # redacted from logs; only the non-secret Accept header is set here.- "headers": {"Accept": "application/json"},- "auth": CampfireTokenAuth(api_key),- "session": session,- "paginator": CampfireNextUrlPaginator(),- },+ "client": _client_config(api_key),"resource_defaults": {},"resources": [{@@ -129,9 +172,9 @@ def campfire_source("endpoint": {"path": config.path,"params": params,- # DRF list endpoints wrap rows in `results`; a dict without it (or a bare- # list) yields nothing, matching the old lenient parse rather than failing.- "data_selector": "results",+ # A DRF envelope missing `results` (or a bare list where one is expected)+ # yields nothing, matching the old lenient parse rather than failing.+ "data_selector": config.data_selector,},}],@@ -151,7 +194,7 @@ def campfire_source(# Incremental filtering is applied above as a first-page query param; the framework's own# incremental injection is not used, so pass no last value here.- resource = rest_api_resource(+ return rest_api_resource(rest_config,team_id,job_id,@@ -160,6 +203,102 @@ def campfire_source(initial_paginator_state=initial_paginator_state,)++def _fanout_resource(+ config: CampfireEndpointConfig,+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[CampfireResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Optional[Any],+ incremental_field: str | None,+) -> Iterable[Any]:+ assert config.fanout is not None+ parent_config = CAMPFIRE_ENDPOINTS[config.fanout.parent_name]++ initial_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.completed or resume.current):+ initial_state = {+ "completed": resume.completed or [],+ "current": resume.current,+ "child_state": resume.child_state,+ }++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ if state is not None:+ resumable_source_manager.save_state(+ CampfireResumeConfig(+ completed=state.get("completed"),+ current=state.get("current"),+ child_state=state.get("child_state"),+ )+ )++ return cast(+ Iterable[Any],+ build_dependent_resource(+ endpoint_configs=CAMPFIRE_ENDPOINTS,+ child_endpoint=endpoint,+ fanout=config.fanout,+ client_config=_client_config(api_key),+ path_format_values={},+ team_id=team_id,+ job_id=job_id,+ db_incremental_field_last_value=db_incremental_field_last_value,+ should_use_incremental_field=should_use_incremental_field,+ incremental_field=incremental_field,+ incremental_config_factory=_incremental_config,+ parent_endpoint_extra={"data_selector": parent_config.data_selector},+ child_endpoint_extra={"data_selector": config.data_selector},+ # The child endpoint documents no page-size param, so the parent listing asks for+ # its own through `fanout.parent_params`.+ page_size_param=None,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_state,+ ),+ )+++def campfire_source(+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[CampfireResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ config = CAMPFIRE_ENDPOINTS[endpoint]++ if config.fanout is not None:+ resource = _fanout_resource(+ config,+ api_key,+ endpoint,+ team_id,+ job_id,+ resumable_source_manager,+ should_use_incremental_field,+ db_incremental_field_last_value,+ incremental_field,+ )+ else:+ resource = _top_level_resource(+ config,+ api_key,+ endpoint,+ team_id,+ job_id,+ resumable_source_manager,+ should_use_incremental_field,+ db_incremental_field_last_value,+ )+return SourceResponse(name=endpoint,items=lambda: resource,@@ -180,6 +319,7 @@ def validate_credentials(api_key: str, path: str | None = None) -> bool:"""Probe the key with the cheapest call on the given endpoint (chart of accounts whenunset — every Campfire role, including view-only, can GET it)."""probe_path = path or CAMPFIRE_ENDPOINTS["chart_of_accounts"].path+ok, _status = validate_via_probe(lambda: make_tracked_session(redact_values=(api_key,), capture=False),f"{CAMPFIRE_BASE_URL}{probe_path}?{urlencode({'limit': 1})}",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/campfire/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/campfire/canonical_descriptions.pyindex 9212ce341578..95f0a2221763 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/campfire/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/campfire/canonical_descriptions.py@@ -149,6 +149,30 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"last_modified_at": "Timestamp of the last modification to the account record.",},},+ "chart_entities": {+ "description": "Legal entities (ChartEntity records) in the company structure. Every transaction, invoice and contract carries an entity ID, and each entity records its parent, its pre-computed lineage, its reporting currency and its fiscal year start, so multi-entity consolidation can be reconstructed.",+ "docs_url": "https://docs.campfire.ai/api-reference/settings/list-chart-entities",+ "columns": {+ "id": "Unique identifier for the entity.",+ "name": "Name of the entity.",+ "currency": "The entity's reporting currency.",+ "parent": "ID of the parent entity, when the entity sits below another one.",+ "parent_name": "Name of the parent entity.",+ "lineage_array": "Pre-computed lineage array from the root entity down to this entity.",+ "elimination_entity": "ID of the entity that holds this entity's consolidation eliminations.",+ "is_elimination_entity": "Whether the entity exists to hold consolidation eliminations.",+ "primary_entity": "ID of the entity this one adjusts, when it is an adjusting entity.",+ "is_adjusting": "Whether the entity is an adjusting entity (it has a primary entity set).",+ "active": "Whether the entity is active.",+ "fiscal_year_month": "Month the entity's fiscal year starts in.",+ "fiscal_year_day": "Day of the month the entity's fiscal year starts on.",+ "tax_identification_number": "The entity's tax identification number.",+ "is_deleted": "Whether the entity has been deleted.",+ "deleted_at": "Timestamp when the entity was deleted.",+ "created_at": "Timestamp when the entity record was created.",+ "last_modified_at": "Timestamp of the last modification to the entity record.",+ },+ },"contracts": {"description": "Revenue recognition contracts.","docs_url": "https://docs.campfire.ai/api-reference/revenue-recognition/list-contracts",@@ -169,4 +193,121 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"last_modified_at": "Timestamp of the last modification to the revenue transaction record.",},},+ "contract_subscriptions": {+ "description": "Subscription schedules on revenue recognition contracts. Each subscription carries its product, rate, quantity, billing cadence and start and end dates, which is what ARR/MRR and revenue recognition waterfalls are built from. Collected by walking the contracts table, so every row names the contract it belongs to.",+ "docs_url": "https://docs.campfire.ai/api-reference/revenue-recognition/list-contract-subscriptions",+ "columns": {+ "id": "Identifier for the subscription within its contract.",+ "contract": "ID of the Campfire contract the subscription belongs to.",+ "product": "ID of the linked product.",+ "product_name": "Name of the linked product.",+ "product_bundle": "ID of the product bundle the subscription was sold in.",+ "product_bundle_name": "Name of the product bundle the subscription was sold in.",+ "rate": "Price per unit for the subscription.",+ "quantity": "Number of units subscribed.",+ "total_value": "Total contracted value of the subscription.",+ "mrr": "Monthly recurring revenue attributed to the subscription.",+ "counts_toward_mrr": "Whether the subscription is included in recurring revenue totals.",+ "discount": "Discount applied to the subscription.",+ "billing_cadence": "How often the subscription is billed (one_time, monthly, quarterly, biannual or annual).",+ "billing_timing": "Whether the subscription bills in advance or in arrears.",+ "first_invoice_date": "Date of the subscription's first invoice.",+ "start_date": "Date the subscription starts.",+ "end_date": "Date the subscription ends.",+ "renewal_behavior": "Whether the subscription follows its contract's renewal or has a fixed end.",+ "revenue_recognition_type": "How revenue is recognized (RATABLE or RELATIVE_TO_PREPAID_COMMIT).",+ "proration_method": "How partial periods are prorated (standard, thirty_day or daily).",+ "is_contract_amendment": "Whether the subscription came from an amendment to the contract.",+ "source": "System the subscription originated in (SALESFORCE, HUBSPOT, STRIPE or MANUAL).",+ "external_id": "Identifier of the subscription in its source system.",+ "is_deleted": "Whether the subscription has been deleted.",+ "deleted_at": "Timestamp when the subscription was deleted.",+ "created_at": "Timestamp when the subscription record was created.",+ "last_modified_at": "Timestamp of the last modification to the subscription record.",+ },+ },+ "products": {+ "description": "The product catalog behind contract line items, including pricing, usage tiers and the GL accounts each product posts revenue, AR and tax to.",+ "docs_url": "https://docs.campfire.ai/api-reference/revenue-recognition/list-contract-products",+ "columns": {+ "id": "Unique identifier for the product.",+ "product_uuid": "Stable UUID for the product.",+ "product_id": "Your own identifier for the product.",+ "product_name": "Name of the product.",+ "product_description": "Description of the product.",+ "display_name": "Name shown for the product in Campfire.",+ "currency": "Currency the product is priced in.",+ "price": "List price of the product.",+ "cost": "Cost of the product.",+ "is_taxable": "Whether the product is taxable.",+ "is_renewable": "Whether the product renews.",+ "recognize_revenue": "Whether revenue is recognized for the product.",+ "is_immediate_recognition": "Whether revenue is recognized immediately rather than over time.",+ "exclude_from_mrr": "Whether the product is excluded from recurring revenue totals.",+ "revenue_account": "ID of the GL account revenue for the product posts to.",+ "revenue_account_name": "Name of the GL account revenue for the product posts to.",+ "ar_account": "ID of the accounts receivable GL account for the product.",+ "ar_account_name": "Name of the accounts receivable GL account for the product.",+ "invoice_account": "ID of the GL account the product's invoices post to.",+ "invoice_account_name": "Name of the GL account the product's invoices post to.",+ "tax_account_name": "Name of the GL account tax on the product posts to.",+ "department": "ID of the department the product belongs to.",+ "department_name": "Name of the department the product belongs to.",+ "usage_group_count": "Number of usage pricing groups defined on the product.",+ "usage_groups": "Usage pricing groups, each with its pricing model, unit of measure and tiers.",+ "tags": "Tags attached to the product.",+ "stripe_product_id": "Identifier of the matching product in Stripe.",+ "customer": "ID of the Campfire customer account the product belongs to.",+ "is_deleted": "Whether the product has been deleted.",+ "deleted_at": "Timestamp when the product was deleted.",+ "created_at": "Timestamp when the product record was created.",+ "last_modified_at": "Timestamp of the last modification to the product record.",+ },+ },+ "customers": {+ "description": "Customer records referenced by contracts, invoices and revenue transactions, with contact and billing details plus Campfire's rolled-up contract, revenue and receivable totals per customer.",+ "docs_url": "https://docs.campfire.ai/api-reference/revenue-recognition/list-contract-customers",+ "columns": {+ "id": "Unique identifier for the customer.",+ "name": "Name of the customer.",+ "display_name": "Name shown for the customer in Campfire.",+ "dba": "The name the customer does business as.",+ "company_name": "Registered company name of the customer.",+ "status": "Whether the customer is ACTIVE or INACTIVE.",+ "currency": "Currency the customer transacts in.",+ "email": "Primary email address for the customer.",+ "phone_number": "Primary phone number for the customer.",+ "website": "Customer's website.",+ "parent": "ID of the parent customer, when the customer sits below another one.",+ "parent_name": "Name of the parent customer.",+ "lineage_array": "Pre-computed lineage array from the root customer down to this one.",+ "contacts": "Contacts attached to the customer.",+ "payment_term": "ID of the payment term applied to the customer.",+ "payment_term_name_display": "Name of the payment term applied to the customer.",+ "active_contracts": "Number of the customer's contracts that are active.",+ "completed_contracts": "Number of the customer's contracts that have completed.",+ "pending_contracts": "Number of the customer's contracts that have not started.",+ "total_contracts": "Total number of contracts for the customer.",+ "total_revenue": "Revenue recognized for the customer.",+ "total_deferred_revenue": "Revenue billed to the customer but not yet recognized.",+ "total_mrr": "Monthly recurring revenue attributed to the customer.",+ "total_billed": "Total amount invoiced to the customer.",+ "total_unbilled": "Contracted amount not yet invoiced to the customer.",+ "total_paid": "Total amount the customer has paid.",+ "total_outstanding": "Invoiced amount the customer still owes.",+ "total_credit_memos": "Total value of credit memos issued to the customer.",+ "credit_memo_applied": "Credit memo value already applied to the customer's invoices.",+ "credit_memo_available": "Credit memo value still available to apply.",+ "vat_number": "The customer's VAT number.",+ "stripe_customer_id": "Identifier of the matching customer in Stripe.",+ "source": "System the customer record originated in (BILL, BREX, HUBSPOT, MANUAL, PAYROLL or SALESFORCE).",+ "external_id": "Identifier of the customer in its source system.",+ "campfire_id": "Campfire's own reference for the customer.",+ "customer": "ID of the Campfire customer account the record belongs to.",+ "is_deleted": "Whether the customer has been deleted.",+ "deleted_at": "Timestamp when the customer was deleted.",+ "created_at": "Timestamp when the customer record was created.",+ "last_modified_at": "Timestamp of the last modification to the customer record.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/campfire/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/campfire/settings.pyindex 302069087542..9903cf4c12e2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/campfire/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/campfire/settings.py@@ -1,17 +1,27 @@from dataclasses import dataclass, field+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ DependentEndpointConfig,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SortModefrom products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldTypeCAMPFIRE_BASE_URL = "https://api.meetcampfire.com"+DEFAULT_PAGE_SIZE = 500++# (connect, read) seconds. Without it a stalled Campfire response holds an import worker forever.+REQUEST_TIMEOUT_SECONDS: tuple[float, float] = (10.0, 60.0)+# Every incremental-capable Campfire list endpoint filters on the same server-side# `last_modified_at__gte` param (ISO 8601), documented to cover both active and deleted records.+LAST_MODIFIED_AT = "last_modified_at"+LAST_MODIFIED_AT_PARAM = "last_modified_at__gte"LAST_MODIFIED_AT_FIELD: list[IncrementalField] = [{- "label": "last_modified_at",+ "label": LAST_MODIFIED_AT,"type": IncrementalFieldType.DateTime,- "field": "last_modified_at",+ "field": LAST_MODIFIED_AT,"field_type": IncrementalFieldType.DateTime,},]@@ -25,7 +35,10 @@ class CampfireEndpointConfig:incremental_fields: list[IncrementalField] = field(default_factory=list)# Stable created-at style field confirmed present in the endpoint's response schema.partition_key: str | None = None- page_size: int = 500+ # False for the endpoints that return a bare JSON array and document no page-size or+ # pagination params, so rows arrive in one response and `limit` would be undocumented.+ paginated: bool = True+ page_size: int = DEFAULT_PAGE_SIZE# Opt into DRF cursor pagination: pass an empty `cursor=` on the first request and follow# the `next` link. Recommended by Campfire for large/syncing endpoints.use_cursor: bool = False@@ -38,6 +51,18 @@ class CampfireEndpointConfig:# endpoint's default six-month date window).extra_params: dict[str, str] = field(default_factory=dict)primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Set where the endpoint is only reachable per parent record, so rows are collected by+ # iterating the parent listing first.+ fanout: DependentEndpointConfig | None = None++ @property+ def data_selector(self) -> str:+ # DRF list endpoints wrap rows in `results`; the unpaginated ones return a bare array.+ return "results" if self.paginated else "$"++ @property+ def default_incremental_field(self) -> str | None:+ return self.incremental_fields[0]["field"] if self.incremental_fields else NoneCAMPFIRE_ENDPOINTS: dict[str, CampfireEndpointConfig] = {@@ -117,6 +142,13 @@ CAMPFIRE_ENDPOINTS: dict[str, CampfireEndpointConfig] = {name="chart_of_accounts",path="/coa/api/account",),+ # Legal entities. Returns every entity in one bare array, with no page-size or+ # last_modified filter documented, so this table is full refresh only.+ "chart_entities": CampfireEndpointConfig(+ name="chart_entities",+ path="/coa/api/entity",+ paginated=False,+ ),"contracts": CampfireEndpointConfig(name="contracts",path="/rr/api/v1/contracts",@@ -128,10 +160,57 @@ CAMPFIRE_ENDPOINTS: dict[str, CampfireEndpointConfig] = {incremental_fields=LAST_MODIFIED_AT_FIELD,partition_key="created_at",),+ # Subscription schedules hang off a contract, so there is no account-wide listing: the+ # rows are collected by walking `contracts` and fetching each contract's subscriptions.+ "contract_subscriptions": CampfireEndpointConfig(+ name="contract_subscriptions",+ path="/rr/api/v1/contracts/{contract_id}/subscriptions",+ incremental_fields=LAST_MODIFIED_AT_FIELD,+ partition_key="created_at",+ paginated=False,+ # `id` is scoped per contract as far as the docs commit to, and every row carries the+ # contract it belongs to.+ primary_keys=["contract", "id"],+ fanout=DependentEndpointConfig(+ parent_name="contracts",+ resolve_param="contract_id",+ resolve_field="id",+ include_from_parent=[],+ # The child takes no page-size param, so the parent listing asks for its own.+ parent_params={"limit": DEFAULT_PAGE_SIZE},+ ),+ ),+ "products": CampfireEndpointConfig(+ name="products",+ path="/rr/api/v1/product",+ incremental_fields=LAST_MODIFIED_AT_FIELD,+ partition_key="created_at",+ ),+ "customers": CampfireEndpointConfig(+ name="customers",+ path="/rr/api/v1/customers",+ incremental_fields=LAST_MODIFIED_AT_FIELD,+ partition_key="created_at",+ ),}+ENDPOINTS = tuple(CAMPFIRE_ENDPOINTS.keys())INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: config.incremental_fields for name, config in CAMPFIRE_ENDPOINTS.items()}+++def probe_path(schema_name: str) -> str | None:+ """The path a credential probe should call for a schema, or None when it is not a schema.++ A fan-out child's path carries an unresolved parent placeholder, so its parent listing is+ probed instead.+ """+ config = CAMPFIRE_ENDPOINTS.get(schema_name)+ if config is None:+ return None+ if config.fanout is not None:+ return CAMPFIRE_ENDPOINTS[config.fanout.parent_name].path+ return config.pathdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/campfire/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/campfire/source.pyindex 9486c215e84c..e28e346a19f4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/campfire/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/campfire/source.py@@ -13,9 +13,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.campfire.cvalidate_credentials as validate_campfire_credentials,)from products.warehouse_sources.backend.temporal.data_imports.sources.campfire.settings import (- CAMPFIRE_ENDPOINTS,ENDPOINTS,INCREMENTAL_FIELDS,+ probe_path,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (@@ -103,8 +103,8 @@ Create an API user and key on the [API keys page](https://app.meetcampfire.com/vschema_name: Optional[str] = None,api_version: str | None = None,) -> tuple[bool, str | None]:- endpoint_config = CAMPFIRE_ENDPOINTS.get(schema_name) if schema_name else None- if validate_campfire_credentials(config.api_key, path=endpoint_config.path if endpoint_config else None):+ path = probe_path(schema_name) if schema_name else None+ if validate_campfire_credentials(config.api_key, path=path):return True, Nonereturn False, "Invalid Campfire API key"@@ -128,4 +128,5 @@ Create an API user and key on the [API keys page](https://app.meetcampfire.com/vdb_incremental_field_last_value=inputs.db_incremental_field_last_valueif inputs.should_use_incremental_fieldelse None,+ incremental_field=inputs.incremental_field,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/campfire/tests/test_campfire.py b/products/warehouse_sources/backend/temporal/data_imports/sources/campfire/tests/test_campfire.pyindex d917c63fe7fe..68977f3a7cc3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/campfire/tests/test_campfire.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/campfire/tests/test_campfire.py@@ -14,6 +14,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.campfire.cCampfireResumeConfig,CampfireTokenAuth,_format_incremental_value,+ _incremental_config,_validate_next_url,campfire_source,validate_credentials,@@ -244,10 +245,19 @@ class TestRetries:class TestCampfireSourceResponse:def test_every_endpoint_builds_a_source_response(self) -> None:+ # Catches a catalog entry whose wiring can't be built at all -- a fan-out naming a parent+ # that isn't in the catalog raises here rather than mid-sync.for endpoint in ENDPOINTS:response = campfire_source("key", endpoint, team_id=1, job_id="j", resumable_source_manager=_make_manager())assert response.name == endpoint- assert response.primary_keys == ["id"]++ def test_fanout_rows_are_keyed_by_contract_and_id(self) -> None:+ # Subscription ids are only documented as unique within their contract, and the fan-out+ # pools every contract's rows into one table.+ response = campfire_source(+ "key", "contract_subscriptions", team_id=1, job_id="j", resumable_source_manager=_make_manager()+ )+ assert response.primary_keys == ["contract", "id"]def test_payment_sync_endpoints_are_ascending(self) -> None:# Campfire documents (last_modified_at, id) ascending order on the payment sync endpoints,@@ -295,3 +305,113 @@ class TestValidateCredentials:with patch.object(campfire, "make_tracked_session", return_value=session):validate_credentials("cf_test_key", path="/rr/api/v1/contracts")assert session.get.call_args[0][0].startswith(f"{CAMPFIRE_BASE_URL}/rr/api/v1/contracts?")+++class TestUnpaginatedEndpoints:+ """Some endpoints return a bare JSON array and document no pagination params."""++ def test_bare_array_rows_are_yielded(self) -> None:+ rows, _, session = _run("chart_entities", [_response([{"id": 1}, {"id": 2}])])+ assert rows == [{"id": 1}, {"id": 2}]+ # No `next` key to follow, so the sync stops after the single response.+ assert session.send.call_count == 1++ def test_no_page_size_is_requested(self) -> None:+ # `/coa/api/entity` documents no `limit`; sending one would be an undocumented param.+ _, snapshots, _ = _run("chart_entities", [_response([])])+ assert "limit" not in snapshots[0]["params"]+++class TestIncrementalConfig:+ def test_binds_last_modified_at_to_the_server_side_filter(self) -> None:+ config = _incremental_config("last_modified_at")+ assert config is not None+ assert config["start_param"] == "last_modified_at__gte"+ assert config["cursor_path"] == "last_modified_at"++ def test_unknown_cursor_field_gets_no_request_window(self) -> None:+ # Campfire filters on `last_modified_at` and nothing else, so any other field must not+ # produce a param the API would ignore.+ assert _incremental_config("created_at") is None+++class TestFanout:+ """`contract_subscriptions` is only reachable per contract, so it walks `contracts` first."""++ def _responses(self) -> list[requests.Response]:+ return [+ _response({"count": 2, "next": None, "results": [{"id": 11}, {"id": 22}]}),+ _response([{"id": 1, "contract": 11}]),+ _response([{"id": 2, "contract": 22}]),+ ]++ def test_fetches_each_contracts_subscriptions(self) -> None:+ rows, snapshots, _ = _run("contract_subscriptions", self._responses())++ assert rows == [{"id": 1, "contract": 11}, {"id": 2, "contract": 22}]+ assert snapshots[0]["url"] == f"{CAMPFIRE_BASE_URL}/rr/api/v1/contracts"+ assert [s["url"] for s in snapshots[1:]] == [+ f"{CAMPFIRE_BASE_URL}/rr/api/v1/contracts/11/subscriptions",+ f"{CAMPFIRE_BASE_URL}/rr/api/v1/contracts/22/subscriptions",+ ]++ def test_only_the_parent_listing_requests_a_page_size(self) -> None:+ # The child endpoint documents no `limit`; the parent needs one to page past its default.+ _, snapshots, _ = _run("contract_subscriptions", self._responses())+ assert snapshots[0]["params"]["limit"] == CAMPFIRE_ENDPOINTS["contracts"].page_size+ assert all("limit" not in s["params"] for s in snapshots[1:])++ def test_child_requests_carry_the_watermark(self) -> None:+ _, snapshots, _ = _run(+ "contract_subscriptions",+ self._responses(),+ should_use_incremental_field=True,+ incremental_field="last_modified_at",+ db_incremental_field_last_value=datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC),+ )+ assert [s["params"].get("last_modified_at__gte") for s in snapshots[1:]] == [+ "2026-01-02T03:04:05Z",+ "2026-01-02T03:04:05Z",+ ]+ # The parent walk is unfiltered: a subscription can change without its contract changing.+ assert "last_modified_at__gte" not in snapshots[0]["params"]++ def test_first_incremental_sync_sends_an_epoch_floor(self) -> None:+ # The framework sends the start param on every request, so with no stored watermark it+ # must still be a timestamp that selects everything.+ _, snapshots, _ = _run(+ "contract_subscriptions",+ self._responses(),+ should_use_incremental_field=True,+ incremental_field="last_modified_at",+ db_incremental_field_last_value=None,+ )+ assert snapshots[1]["params"]["last_modified_at__gte"] == "1970-01-01T00:00:00Z"++ def test_full_refresh_sends_no_watermark(self) -> None:+ _, snapshots, _ = _run("contract_subscriptions", self._responses())+ assert all("last_modified_at__gte" not in s["params"] for s in snapshots)++ def test_checkpoints_each_finished_contract(self) -> None:+ manager = _make_manager()+ _run("contract_subscriptions", self._responses(), manager=manager)+ assert [s.completed for s in manager.saved][-1] == [+ "/rr/api/v1/contracts/11/subscriptions",+ "/rr/api/v1/contracts/22/subscriptions",+ ]++ def test_resumes_past_contracts_already_synced(self) -> None:+ manager = _make_manager(+ CampfireResumeConfig(completed=["/rr/api/v1/contracts/11/subscriptions"], current=None, child_state=None)+ )+ rows, snapshots, _ = _run(+ "contract_subscriptions",+ [+ _response({"count": 2, "next": None, "results": [{"id": 11}, {"id": 22}]}),+ _response([{"id": 2, "contract": 22}]),+ ],+ manager=manager,+ )++ assert rows == [{"id": 2, "contract": 22}]+ assert [s["url"] for s in snapshots[1:]] == [f"{CAMPFIRE_BASE_URL}/rr/api/v1/contracts/22/subscriptions"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/campfire/tests/test_campfire_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/campfire/tests/test_campfire_source.pyindex 67f54bf0d987..8dee53aab14f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/campfire/tests/test_campfire_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/campfire/tests/test_campfire_source.py@@ -61,6 +61,15 @@ class TestCampfireSource:self.source.validate_credentials(CampfireSourceConfig(api_key="k"), team_id=1, schema_name="contracts")mock.assert_called_once_with("k", path="/rr/api/v1/contracts")+ def test_validate_credentials_probes_the_parent_of_a_fanout_schema(self) -> None:+ # A fan-out child's path still holds its parent placeholder, so probing it verbatim would+ # request a nonexistent contract.+ with patch.object(source_module, "validate_campfire_credentials", return_value=True) as mock:+ self.source.validate_credentials(+ CampfireSourceConfig(api_key="k"), team_id=1, schema_name="contract_subscriptions"+ )+ mock.assert_called_once_with("k", path="/rr/api/v1/contracts")+@parameterized.expand([("incremental", True, "2026-01-01"),