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(warehouse-sources): add acculynx history, amendment and estimate item tables (#116122)

Tom Owers5c2c5297b556
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 7ce0f3de38de..08dda1f1d43f 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
@@ -102,10 +102,10 @@ Today (10): `calendar_appointments`, `calendars`, `contacts`, `estimates`, `fina
Diffed against: <https://apidocs.acculynx.com/llms.txt>
-- [ ] `Financial amendments (GET /api/v2/financials/{financialsId}/amendments)` — resolve amendment IDs linked from financials and explain changes to contract value (high)
-- [ ] `Estimate section items (GET /api/v2/estimates/{estimateId}/sections/{estimateSectionId}/items)` — analyze estimated quantities, material costs, labor costs, and item prices beyond estimate totals (high)
-- [ ] `Job milestone history (GET /api/v2/jobs/{jobId}/milestone-history)` — measure conversion between milestones and time spent in each stage of a job (high)
-- [ ] `Job change history (GET /api/v2/jobs/{jobId}/history)` — analyze job activity, changes, and responsible users over time (medium)
+- [x] `Financial amendments (GET /api/v2/financials/{financialsId}/amendments)` — resolve amendment IDs linked from financials and explain changes to contract value (high)
+- [x] `Estimate section items (GET /api/v2/estimates/{estimateId}/sections/{estimateSectionId}/items)` — analyze estimated quantities, material costs, labor costs, and item prices beyond estimate totals (high)
+- [x] `Job milestone history (GET /api/v2/jobs/{jobId}/milestone-history)` — measure conversion between milestones and time spent in each stage of a job (high)
+- [x] `Job change history (GET /api/v2/jobs/{jobId}/history)` — analyze job activity, changes, and responsible users over time (medium)
- [ ] `Supplements and supplement items (GET /api/v2/supplements; GET /api/v2/supplements/{supplementId}/items)` — analyze supplemental work and item costs beyond aggregated financial totals (medium)
- [ ] `Job contacts (GET /api/v2/jobs/{jobId}/contacts)` — connect each job to additional contacts beyond the primary contact included in jobs (medium)
- [ ] `Job custom fields and definitions (GET /api/v2/jobs/{jobId}/custom-fields; GET /api/v2/company-settings/custom-fields)` — analyze custom job attributes using their field definitions (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/acculynx/acculynx.py b/products/warehouse_sources/backend/temporal/data_imports/sources/acculynx/acculynx.py
index c19374a4643f..16f94df47b34 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/acculynx/acculynx.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/acculynx/acculynx.py
@@ -198,6 +198,13 @@ def _payment_rows(row: dict[str, Any]) -> list[dict[str, Any]]:
return rows
+def _fanout_chain(name: str) -> list[str]:
+ chain = [name]
+ while (fanout := PARENT_ENDPOINTS[chain[0]].fanout) is not None:
+ chain.insert(0, fanout.parent_name)
+ return chain
+
+
def _fanout_resource(
name: str,
client: ClientConfig,
@@ -206,36 +213,48 @@ def _fanout_resource(
checkpoint: Callable[[dict[str, Any] | None], None],
initial_state: dict[str, Any] | None,
) -> Resource:
- config = ENDPOINTS[name]
- fanout = config.fanout
+ resources: list[str | EndpointResource] = []
+ for level in _fanout_chain(name):
+ config = PARENT_ENDPOINTS[level]
+ fanout = config.fanout
+ if fanout is None:
+ parent = _resource(level, _endpoint(config))
+ if level == "jobs":
+ # Job date windows must also apply to the parent walk, or child tables hit the same offset cap.
+ parent["data_iterator"] = lambda: _job_pages(client, inputs)
+ resources.append(parent)
+ continue
+ endpoint = _endpoint(
+ config,
+ {
+ **(params if level == name else {}),
+ **fanout.child_params,
+ fanout.resolve_param: {
+ "type": "resolve",
+ "resource": fanout.parent_name,
+ "field": fanout.resolve_field,
+ },
+ },
+ )
+ # A job can have no financial record, and a listed parent can be deleted before its child is fetched.
+ endpoint["response_actions"] = [
+ *(endpoint.get("response_actions") or []),
+ {"status_code": 404, "action": "ignore"},
+ ]
+ child = _resource(level, endpoint)
+ child["include_from_parent"] = fanout.include_from_parent
+ resources.append(child)
+ fanout = ENDPOINTS[name].fanout
assert fanout is not None
- parent = _resource(fanout.parent_name, _endpoint(PARENT_ENDPOINTS[fanout.parent_name]))
- if fanout.parent_name == "jobs":
- # Job date windows must also apply to the parent walk, or child tables hit the same offset cap.
- parent["data_iterator"] = lambda: _job_pages(client, inputs)
- child_endpoint = _endpoint(
- config,
- {
- **params,
- fanout.resolve_param: {"type": "resolve", "resource": fanout.parent_name, "field": fanout.resolve_field},
- },
- )
- # A job can have no financial record, and a listed parent can be deleted before its child is fetched.
- child_endpoint["response_actions"] = [
- *(child_endpoint.get("response_actions") or []),
- {"status_code": 404, "action": "ignore"},
- ]
- child = _resource(name, child_endpoint)
- child["include_from_parent"] = fanout.include_from_parent
- resources = rest_api_resources(
- {"client": client, "resources": [parent, child]},
+ built = rest_api_resources(
+ {"client": client, "resources": resources},
inputs.team_id,
inputs.job_id,
None,
resume_hook=checkpoint,
initial_paginator_state=initial_state,
)
- resource = next(r for r in resources if r.name == name)
+ resource = next(r for r in built if r.name == name)
resource.add_map(rename_parent_fields(fanout.parent_name, fanout.parent_field_renames))
return resource.add_map(_payment_rows) if name == "payments" else resource
@@ -310,6 +329,12 @@ def acculynx_source(
)
+def _bind_path(path: str, bindings: dict[str, str]) -> str:
+ for param, value in bindings.items():
+ path = path.replace("{" + param + "}", value)
+ return path
+
+
def validate_credentials(
api_key: str,
api_version: str,
@@ -330,20 +355,27 @@ def validate_credentials(
path = config.path
params: dict[str, Any] = {**config.params, "pageSize": 1}
if config.fanout:
- parent = PARENT_ENDPOINTS[config.fanout.parent_name]
- parents = next(
- client.paginate(
- path=parent.path,
- params={"pageSize": 1},
- paginator=SinglePagePaginator(),
- data_selector="items",
- data_selector_required=True,
- ),
- [],
- )
- if not parents:
- return True, None
- path = path.replace("{" + config.fanout.resolve_param + "}", parents[0][config.fanout.resolve_field])
+ # Bind each level's path parameters from the first row of the level above it.
+ bindings: dict[str, str] = {}
+ chain = _fanout_chain(schema_name or "jobs")
+ for parent_name, child_name in zip(chain, chain[1:]):
+ parent = PARENT_ENDPOINTS[parent_name]
+ child_fanout = PARENT_ENDPOINTS[child_name].fanout
+ assert child_fanout is not None
+ parents = next(
+ client.paginate(
+ path=_bind_path(parent.path, bindings),
+ params={"pageSize": 1},
+ paginator=SinglePagePaginator(),
+ data_selector=parent.data_selector,
+ data_selector_required=True,
+ ),
+ [],
+ )
+ if not parents:
+ return True, None
+ bindings[child_fanout.resolve_param] = parents[0][child_fanout.resolve_field]
+ path = _bind_path(path, bindings)
if schema_name == "calendar_appointments":
params.update(
startDate=appointments.start.isoformat(),
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/acculynx/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/acculynx/canonical_descriptions.py
index 839811bab922..69d36280d514 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/acculynx/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/acculynx/canonical_descriptions.py
@@ -57,6 +57,53 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"amount": "Amount of the payment or expense.",
},
},
+ "job_milestone_history": {
+ "description": "Milestones each job has moved through, with the date it entered each one.",
+ "docs_url": "https://apidocs.acculynx.com/reference/getmilestonesforjob",
+ "columns": {
+ "job_id": "Identifier of the job whose milestone history was requested.",
+ "name": "Name of the milestone.",
+ "date": "Date and time the job was set to this milestone, in UTC.",
+ },
+ },
+ "job_history": {
+ "description": "Actions performed on each job, with the action type and the user who performed it.",
+ "docs_url": "https://apidocs.acculynx.com/reference/getjobhistory",
+ "columns": {
+ "job_id": "Identifier of the job whose history was requested.",
+ "action": "Description of the action performed on the job.",
+ "type": "Type of action, such as Job, Estimate, Payments, or Appointment.",
+ "date": "Date and time the action happened, in UTC.",
+ "createdBy": "User who performed the action.",
+ },
+ },
+ "financial_amendments": {
+ "description": "Amendments to job financials, with their state, title, total price, and worksheet sections.",
+ "docs_url": "https://apidocs.acculynx.com/reference/getworksheetamendmentsbyid",
+ "columns": {
+ "id": "Unique amendment identifier.",
+ "financials_id": "Identifier of the financial record whose amendments were requested.",
+ "jobId": "Identifier of the job the amendment belongs to.",
+ "currentState": "Current state of the amendment.",
+ "totalPrice": "Total price of the amendment.",
+ "createdDate": "Date and time the amendment was created, in UTC.",
+ "modifiedDate": "Date and time the amendment was last modified, in UTC.",
+ },
+ },
+ "estimate_section_items": {
+ "description": "Line items in each estimate section, with quantities, units, material and labor costs, and prices.",
+ "docs_url": "https://apidocs.acculynx.com/reference/getestimatesectionitems",
+ "columns": {
+ "id": "Unique estimate item identifier.",
+ "estimate_id": "Identifier of the estimate that contains the section.",
+ "estimate_section_id": "Identifier of the estimate section that contains the item.",
+ "materialCost": "Material cost of the item.",
+ "laborCost": "Labor cost of the item.",
+ "quantity": "Quantity of the item.",
+ "price": "Price of the item.",
+ "totalPrice": "Total price of the item.",
+ },
+ },
"calendars": {
"description": "Calendars available for the connected AccuLynx location.",
"docs_url": "https://apidocs.acculynx.com/reference/getcalendars",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/acculynx/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/acculynx/settings.py
index d30bc4e05fa9..998810446303 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/acculynx/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/acculynx/settings.py
@@ -90,6 +90,60 @@ ENDPOINTS: dict[str, AcculynxEndpoint] = {
parent_field_renames={"id": "job_id"},
),
),
+ "job_milestone_history": AcculynxEndpoint(
+ path="jobs/{jobId}/milestone-history",
+ offset_param=None,
+ primary_keys=("job_id", "name", "date"),
+ partition_key="date",
+ fanout=DependentEndpointConfig(
+ parent_name="jobs",
+ resolve_param="jobId",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "job_id"},
+ ),
+ ),
+ # History rows have no identifier, so every documented field is part of the key.
+ "job_history": AcculynxEndpoint(
+ path="jobs/{jobId}/history",
+ primary_keys=("job_id", "date", "type", "action"),
+ partition_key="date",
+ fanout=DependentEndpointConfig(
+ parent_name="jobs",
+ resolve_param="jobId",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "job_id"},
+ ),
+ ),
+ "financial_amendments": AcculynxEndpoint(
+ path="financials/{financialsId}/amendments",
+ offset_param="pageStartIndex",
+ primary_keys=("financials_id", "id"),
+ partition_key="createdDate",
+ fanout=DependentEndpointConfig(
+ parent_name="financials",
+ resolve_param="financialsId",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "financials_id"},
+ ),
+ ),
+ "estimate_section_items": AcculynxEndpoint(
+ path="estimates/{estimateId}/sections/{estimateSectionId}/items",
+ offset_param=None,
+ primary_keys=("estimate_id", "estimate_section_id", "id"),
+ fanout=DependentEndpointConfig(
+ parent_name="estimate_sections",
+ resolve_param="estimateSectionId",
+ resolve_field="id",
+ include_from_parent=["id", "_estimate_index_id"],
+ parent_field_renames={"id": "estimate_section_id", "_estimate_index_id": "estimate_id"},
+ child_params={
+ "estimateId": {"type": "resolve", "resource": "estimate_sections", "field": "_estimate_index_id"}
+ },
+ ),
+ ),
"calendars": AcculynxEndpoint(path="calendars"),
"calendar_appointments": AcculynxEndpoint(
path="calendars/{calendarId}/appointments",
@@ -113,6 +167,16 @@ ENDPOINTS: dict[str, AcculynxEndpoint] = {
PARENT_ENDPOINTS = {
**ENDPOINTS,
"estimate_index": AcculynxEndpoint(path="estimates", offset_param="pageStartIndex"),
+ "estimate_sections": AcculynxEndpoint(
+ path="estimates/{estimateId}/sections",
+ offset_param=None,
+ fanout=DependentEndpointConfig(
+ parent_name="estimate_index",
+ resolve_param="estimateId",
+ resolve_field="id",
+ include_from_parent=["id"],
+ ),
+ ),
}
# ModifiedDate filtering needs account-level verification before incremental sync can be enabled.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/acculynx/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/acculynx/source.py
index a813140929d3..5ac66c726b32 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/acculynx/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/acculynx/source.py
@@ -103,8 +103,16 @@ class AcculynxSource(ResumableSource[AcculynxSourceConfig, AcculynxResumeConfig]
ENDPOINTS,
INCREMENTAL_FIELDS,
names,
- should_sync_default={"calendar_appointments": False},
- descriptions={"calendar_appointments": "Appointments within the configured date range."},
+ should_sync_default={
+ "calendar_appointments": False,
+ "financial_amendments": False,
+ "estimate_section_items": False,
+ },
+ descriptions={
+ "calendar_appointments": "Appointments within the configured date range.",
+ "financial_amendments": "Off by default because it makes extra requests for every job.",
+ "estimate_section_items": "Off by default because it makes extra requests for every estimate.",
+ },
)
def validate_credentials(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/acculynx/tests/test_acculynx.py b/products/warehouse_sources/backend/temporal/data_imports/sources/acculynx/tests/test_acculynx.py
index 69c52030a5be..724f1d9a2d73 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/acculynx/tests/test_acculynx.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/acculynx/tests/test_acculynx.py
@@ -271,3 +271,72 @@ def test_optional_appointment_range_has_a_future_horizon() -> None:
window = appointment_range(None, None)
assert window.start == date(2000, 1, 1)
assert window.end == date(2025, 4, 1)
+
+
+def _page(items: list[dict[str, Any]]) -> dict[str, Any]:
+ return {"count": len(items), "pageSize": 25, "pageStartIndex": 0, "items": items}
+
+
+TWO_LEVEL_ROUTES: dict[str, dict[str, Any]] = {
+ "/api/v2/estimates": _page([{"id": "est-1"}, {"id": "est-2"}]),
+ "/api/v2/estimates/est-1/sections": {"items": [{"id": "sec-1"}, {"id": "sec-2"}]},
+ "/api/v2/estimates/est-2/sections": {"items": [{"id": "sec-1"}]},
+ "/api/v2/estimates/est-1/sections/sec-1/items": {"items": [{"id": "item-1"}]},
+ "/api/v2/estimates/est-1/sections/sec-2/items": {"items": [{"id": "item-1"}]},
+ "/api/v2/estimates/est-2/sections/sec-1/items": {"items": [{"id": "item-1"}]},
+ "/api/v2/jobs": _page([{"id": f"job-{i}", "createdDate": "2025-01-01T00:00:00Z"} for i in range(3)]),
+ "/api/v2/jobs/job-1/financials": {"id": "fin-1"},
+ "/api/v2/jobs/job-2/financials": {"id": "fin-2"},
+ "/api/v2/financials/fin-1/amendments": _page([{"id": "amend-1", "jobId": "job-1"}]),
+ "/api/v2/financials/fin-2/amendments": _page([{"id": "amend-2", "jobId": "job-2"}]),
+}
+
+
+ "name, expected, probe",
+ [
+ (
+ "estimate_section_items",
+ [
+ {"id": "item-1", "estimate_id": "est-1", "estimate_section_id": "sec-1"},
+ {"id": "item-1", "estimate_id": "est-1", "estimate_section_id": "sec-2"},
+ {"id": "item-1", "estimate_id": "est-2", "estimate_section_id": "sec-1"},
+ ],
+ "/api/v2/estimates/est-1/sections/sec-1/items",
+ ),
+ (
+ "financial_amendments",
+ [
+ {"id": "amend-1", "jobId": "job-1", "financials_id": "fin-1"},
+ {"id": "amend-2", "jobId": "job-2", "financials_id": "fin-2"},
+ ],
+ # The first job has no financials, which validation treats as an accessible table.
+ "/api/v2/jobs/job-0/financials",
+ ),
+ ],
+)
+def test_two_level_fanouts_bind_every_ancestor_and_skip_missing_parents(
+ name: str,
+ expected: list[dict[str, Any]],
+ probe: str,
+ pipeline: Callable[..., SyncSourceResponse],
+ http_send: MagicMock,
+ response: Callable[..., Response],
+) -> None:
+ def send(request: PreparedRequest, **_: Any) -> Response:
+ path = urlsplit(request.url or "").path
+ return response(request, TWO_LEVEL_ROUTES[path]) if path in TWO_LEVEL_ROUTES else response(request, {}, 404)
+
+ http_send.side_effect = send
+ resource = pipeline(name)
+ rows = [row for page in resource.items() for row in page]
+ assert sorted(rows, key=lambda row: sorted(row.items())) == expected
+ assert resource.primary_keys
+ assert len({tuple(row[key] for key in resource.primary_keys) for row in rows}) == len(rows)
+
+ http_send.reset_mock()
+ assert validate_credentials("fake-key", "v2", name, DateWindow(start=date(2025, 1, 1), end=date(2025, 1, 2))) == (
+ True,
+ None,
+ )
+ assert urlsplit(http_send.call_args.args[0].url).path == probe