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(concord): sync per-agreement activities, members, fields and clauses (#103456)

Tom Owersa79fc22bf284
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 1c724c757794..a1e309ba68d5 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
@@ -1925,16 +1925,16 @@ Note: The full OpenAPI (292 paths) is published at commercetools/commercetools-a
## Concord — gaps
-Today (10): `agreements`, `approvals`, `clauses`, `events`, `folders`, `groups`, `members`, `organizations`, `reports`, `tags`
+Today (15): `agreement_activities`, `agreement_clauses`, `agreement_endclauses`, `agreement_fields`, `agreement_members`, `agreements`, `approvals`, `clauses`, `events`, `folders`, `groups`, `members`, `organizations`, `reports`, `tags`
Diffed against: <https://api.doc.concordnow.com/concord-openapi-bundled.yaml>
-- [ ] `GET /organizations/{organizationId}/agreements/{agreementUid}/members` — agreement<->user junction: who has access, their permission and signer role (high)
-- [ ] `GET /organizations/{organizationId}/agreements/{agreementUid}/summary/fields` — smart fields (contract value, renewal date, term) - the analytical dimensions of a contract (high)
+- [x] `GET /organizations/{organizationId}/agreements/{agreementUid}/members` — agreement<->user junction: who has access, their permission and signer role (high)
+- [x] `GET /organizations/{organizationId}/agreements/{agreementUid}/summary/fields` — smart fields (contract value, renewal date, term) - the analytical dimensions of a contract (high)
- [ ] `GET /organizations/{organizationId}/agreements/{agreementUid}/signature` — signature state and signer slots per agreement; drives time-to-signature (high)
- [ ] `GET /organizations/{organizationId}/agreements/{agreementUid}/approval` — per-agreement approval state, joins the approvals table we already sync to its contract (high)
-- [ ] `GET /organizations/{organizationId}/agreements/{agreementUid}/activities` — per-agreement activity timeline (sent, viewed, signed) at finer grain than the org events feed (high)
-- [ ] `GET /organizations/{organizationId}/agreements/{agreementUid}/summary/clauses (and /summary/endclauses)` — clause instances per agreement - the junction to the clauses lookup table already synced (high)
+- [x] `GET /organizations/{organizationId}/agreements/{agreementUid}/activities` — per-agreement activity timeline (sent, viewed, signed) at finer grain than the org events feed (high)
+- [x] `GET /organizations/{organizationId}/agreements/{agreementUid}/summary` — clause instances per agreement - the junction to the clauses lookup table already synced (high). The listed `/summary/clauses` and `/summary/endclauses` paths are POST-only; the clause and end-clause arrays are only readable from `GET /summary`, which is what the `agreement_clauses` and `agreement_endclauses` tables sync.
- [ ] `GET /organizations/{organizationId}/agreements/{agreementUid}/versions` — contract version history for redline/negotiation-cycle analysis (medium)
- [ ] `GET /organizations/{organizationId}/agreements/{agreementUid}/metadata` — structured metadata fields beyond the agreement record (medium)
- [ ] `GET /organizations/{organizationId}/agreements/{agreementUid}/comments` — negotiation comment thread per agreement (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/concord/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/concord/canonical_descriptions.py
index 8ba2d883c442..4a56f400ed02 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/concord/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/concord/canonical_descriptions.py
@@ -109,4 +109,87 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"event": "The object the event relates to (e.g. the agreement).",
},
},
+ "agreement_activities": {
+ "description": "Audit timeline of actions on each agreement, such as viewed, signed, approved or downloaded.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "agreement_uuid": "UID of the agreement the activity belongs to. Joins to agreements.uuid.",
+ "id": "Identifier of the activity within its agreement.",
+ "createdAt": "When the action happened, as a Unix timestamp in milliseconds.",
+ "action": "The action recorded (e.g. AGREEMENT_VIEW, AGREEMENT_SIGNATURE_FINALIZE, VALIDATION_ACCEPT).",
+ "status": "Lifecycle stage the agreement was in when the action happened.",
+ "params": "Action-specific detail supplied by Concord.",
+ "userOrganization": "The user and organization that performed the action.",
+ "visibility": "Who can see the activity (ALL, COMPANY or ME).",
+ "organization": "Organization the activity was recorded under.",
+ },
+ },
+ "agreement_members": {
+ "description": "Who has access to each agreement, covering active users, pending invitations and delayed invitations.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "agreement_uuid": "UID of the agreement. Joins to agreements.uuid.",
+ "member_id": "Identifier of the member within the agreement: the invitation id for invited members, otherwise the user id.",
+ "status": "Membership state: ACTIVE for a user, INVITED or DELAYED for an invitation.",
+ "permission": "Negotiation permission granted on the agreement.",
+ "relation": "Relationship to the account holder (YOU, COLLEAGUE or THIRD_PARTY).",
+ "userSignStatus": "Signature state for this member (e.g. WAITING_RESPONSE, SIGNED).",
+ "lastAccessAt": "When the member last opened the agreement, as a Unix timestamp in milliseconds.",
+ "user": "The user account, when the member has one.",
+ "invitation": "The invitation record, for invited and delayed members.",
+ },
+ },
+ "agreement_fields": {
+ "description": "Smart fields captured on each agreement, such as contract value, renewal date or term.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "agreement_uuid": "UID of the agreement. Joins to agreements.uuid.",
+ "id": "Identifier of the field within the agreement.",
+ "name": "Field name, for example price or country.",
+ "value": "Field value as entered on the agreement.",
+ },
+ },
+ "agreement_clauses": {
+ "description": "Clause instances recorded on each agreement's summary, with their deadlines and periods.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "agreement_uuid": "UID of the agreement. Joins to agreements.uuid.",
+ "id": "Identifier of the clause within the agreement.",
+ "title": "Clause title.",
+ "eventDuration": "How the clause duration is anchored (e.g. DATE_SPECIFIED).",
+ "deadline": "Clause deadline as a Unix timestamp in milliseconds.",
+ "lengthValue": "Length of the clause period.",
+ "lengthUnit": "Unit the length is expressed in (e.g. WEEK, MONTH).",
+ "periodType": "How the clause period is derived (e.g. CONTRACT_START_CONTRACT_END).",
+ "periodCustomStart": "Custom period start as a Unix timestamp in milliseconds.",
+ "periodCustomEnd": "Custom period end as a Unix timestamp in milliseconds.",
+ "periodValue": "Length of the recurring period.",
+ "periodUnit": "Unit the period is expressed in.",
+ "financialData": "Monetary detail attached to the clause.",
+ },
+ },
+ "agreement_endclauses": {
+ "description": "Renewal and termination clauses on each agreement, with notice periods and auto-renewal terms.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "agreement_uuid": "UID of the agreement. Joins to agreements.uuid.",
+ "id": "Identifier of the end clause within the agreement.",
+ "title": "End clause title.",
+ "deadline": "End clause deadline as a Unix timestamp in milliseconds.",
+ "contractRenewalType": "How the contract renews at the end of the term.",
+ "renewalCountRemaining": "Number of renewals still available.",
+ "autoGenerated": "Whether Concord generated the clause from a renewal.",
+ "afterRenewalAutoGenerate": "Whether the next renewal generates another end clause automatically.",
+ "afterRenewalDurationValue": "Length of the term created by the next renewal.",
+ "afterRenewalDurationUnit": "Unit the post-renewal term is expressed in.",
+ "noticePeriodValue": "Length of the notice period before the end date.",
+ "noticePeriodUnit": "Unit the notice period is expressed in.",
+ "earlyTerminationNoticePeriodValue": "Length of the notice period for early termination.",
+ "earlyTerminationNoticePeriodUnit": "Unit the early-termination notice period is expressed in.",
+ "startDate": "Term start as a Unix timestamp in milliseconds.",
+ "customStartDate": "Custom term start as a Unix timestamp in milliseconds.",
+ "previousEndClauseId": "Id of the end clause this one replaced.",
+ "nextEndClauseId": "Id of the end clause that replaced this one.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/concord/concord.posthog.com.md b/products/warehouse_sources/backend/temporal/data_imports/sources/concord/concord.posthog.com.md
index 594ef9aa96c3..8f532bf48700 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/concord/concord.posthog.com.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/concord/concord.posthog.com.md
@@ -17,7 +17,8 @@ import AlphaRelease from "../\_snippets/alpha-release.mdx"
[Concord](https://www.concord.app/) is a contract lifecycle management (CLM) platform for
e-signatures, contract storage, negotiation, and approvals. This source syncs your agreements,
folders, clauses, tags, reports, organization members, and audit events into the PostHog data
-warehouse so you can join contract data with your product and revenue data.
+warehouse so you can join contract data with your product and revenue data. It also syncs
+per-agreement detail: smart fields, clauses, members, and the activity timeline.
## Prerequisites
@@ -49,6 +50,14 @@ Agreements expose Concord's server-side `modifiedAt`/`createdAt` timestamp filte
Every other table is **full refresh** only, since Concord does not expose a server-side change
filter for them.
+### Per-agreement tables
+
+The `agreement_activities`, `agreement_clauses`, `agreement_endclauses`, `agreement_fields`, and
+`agreement_members` tables describe one agreement at a time. Concord has no bulk endpoint for them,
+so syncing one makes a request per agreement on every sync. They are **deselected by default** —
+turn on the ones you need. If an agreement is deleted or your API key can't read it, that agreement
+is skipped and the rest of the table still syncs.
+
## Configuration
<SourceParameters />
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/concord/concord.py b/products/warehouse_sources/backend/temporal/data_imports/sources/concord/concord.py
index 9792be293cad..cac25d51ed55 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/concord/concord.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/concord/concord.py
@@ -33,7 +33,7 @@ class ConcordRetryableError(Exception):
pass
[email protected](frozen=False)
class ConcordResumeConfig:
# Page index to fetch on resume (page-number pagination). 0-based, matching Concord.
page: Optional[int] = None
@@ -44,6 +44,10 @@ class ConcordResumeConfig:
row_offset: Optional[int] = None
# Start of the next audit-log window as a Unix ms timestamp (events_window pagination).
window_start_ms: Optional[int] = None
+ # Position in the agreements walk a fan-out endpoint resumes at: the parent page, and the index
+ # of the agreement within it whose children were in flight.
+ parent_page: Optional[int] = None
+ parent_index: Optional[int] = None
def base_url_for_environment(environment: str | None) -> str:
@@ -153,6 +157,41 @@ def _select_rows(
return rows or []
+def _select_child_rows(
+ payload: Any, selector: str | None, logger: FilteringBoundLogger | None = None
+) -> list[dict[str, Any]]:
+ """Select the rows of a per-agreement child response.
+
+ `/members` answers with a bare JSON array; every other child endpoint wraps its rows in a key.
+ """
+ if selector is None:
+ return payload if isinstance(payload, list) else []
+ return _select_rows(payload, selector, logger)
+
+
+def _member_id(row: dict[str, Any]) -> Any:
+ """Return the id a member row is keyed on within its agreement.
+
+ `/members` mixes active users, invitations and delayed invitations. Only the invitation shapes
+ carry an `invitation` object, so preferring it keeps each `status` on a single id space — user
+ ids and invitation ids are separate sequences and would otherwise collide in the primary key.
+ """
+ invitation = row.get("invitation")
+ if isinstance(invitation, dict) and invitation.get("id") is not None:
+ return invitation["id"]
+ user = row.get("user")
+ if isinstance(user, dict):
+ return user.get("id")
+ return None
+
+
+def _normalize_child_row(endpoint: str, row: dict[str, Any], agreement_uuid: str) -> dict[str, Any]:
+ normalized = {**row, "agreement_uuid": agreement_uuid}
+ if endpoint == "agreement_members":
+ normalized["member_id"] = _member_id(row)
+ return normalized
+
+
def _scope_organizations_to_org(rows: list[dict[str, Any]], configured_org_id: str | None) -> list[dict[str, Any]]:
"""Restrict the organizations listing to the single org this source syncs.
@@ -320,6 +359,90 @@ def _iter_events_windows(
window_start = next_start
+def _fetch_child_rows(
+ session: requests.Session,
+ base_url: str,
+ child_path: str,
+ headers: dict[str, str],
+ config: ConcordEndpointConfig,
+ logger: FilteringBoundLogger,
+ agreement_uuid: str,
+) -> list[dict[str, Any]]:
+ """Fetch one agreement's child rows, or none when that agreement is out of reach.
+
+ A key that can list agreements is not guaranteed access to every one of them, and an agreement
+ can be deleted while we walk the list. Either would fail the whole table for one bad parent, so
+ skip the agreement and keep going.
+ """
+ try:
+ payload = _fetch(session, _build_url(base_url, child_path, config.fanout_params), headers, logger)
+ except requests.HTTPError as error:
+ status = error.response.status_code if error.response is not None else None
+ if status in (403, 404):
+ logger.warning(
+ f"Skipping Concord agreement for '{config.name}': status={status}, agreement={agreement_uuid}"
+ )
+ return []
+ raise
+ return [
+ _normalize_child_row(config.name, row, agreement_uuid)
+ for row in _select_child_rows(payload, config.data_selector, logger)
+ ]
+
+
+def _iter_agreement_fanout(
+ session: requests.Session,
+ base_url: str,
+ org_id: str,
+ child_template: str,
+ headers: dict[str, str],
+ config: ConcordEndpointConfig,
+ logger: FilteringBoundLogger,
+ batcher: Batcher,
+ manager: ResumableSourceManager[ConcordResumeConfig],
+ start_page: int,
+ start_index: int = 0,
+) -> Iterator[Any]:
+ """Walk the agreements list and fetch `child_template` once per agreement.
+
+ None of the per-agreement endpoints paginate or expose a change filter, so every sync re-reads
+ each agreement's children and merge dedupes on the composite primary key.
+ """
+ parent_config = CONCORD_ENDPOINTS["agreements"]
+ parent_path = parent_config.path.replace("{organization_id}", org_id)
+
+ page = start_page
+ # Agreements of the first page whose children a prior run already finished.
+ skip = start_index
+ while True:
+ parent_params: dict[str, Any] = {
+ "statuses": AGREEMENT_STATUSES,
+ "page": page,
+ "numberOfItemsByPage": parent_config.page_size,
+ }
+ parent_payload = _fetch(session, _build_url(base_url, parent_path, parent_params), headers, logger)
+ agreements = _select_rows(parent_payload, parent_config.data_selector, logger)
+ for local_index, agreement in enumerate(agreements):
+ if local_index < skip:
+ continue
+ agreement_uuid = agreement.get("uuid")
+ if not agreement_uuid:
+ continue
+ child_path = child_template.replace("{agreement_uid}", str(agreement_uuid))
+ for row in _fetch_child_rows(session, base_url, child_path, headers, config, logger, str(agreement_uuid)):
+ batcher.batch(row)
+ if batcher.should_yield():
+ yield batcher.get_table()
+ # Checkpoint the agreement still in flight rather than the next one: its rows
+ # may be split across this flush and the next, so a resume has to redo it whole.
+ # Merge dedupes the replayed rows on the composite primary key.
+ manager.save_state(ConcordResumeConfig(parent_page=page, parent_index=local_index))
+ skip = 0
+ if len(agreements) < parent_config.page_size:
+ break
+ page += 1
+
+
def get_rows(
api_key: str,
environment: str | None,
@@ -340,7 +463,8 @@ def get_rows(
batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)
org_id = resolve_organization_id(session, base_url, api_key, organization_id, logger) if config.org_scoped else None
- path = config.path.format(organization_id=org_id) if org_id else config.path
+ # `.replace` not `.format`: fan-out paths still carry an unresolved `{agreement_uid}`.
+ path = config.path.replace("{organization_id}", org_id) if org_id else config.path
base_params: dict[str, Any] = {}
if config.org_in_query and org_id:
@@ -418,6 +542,14 @@ def get_rows(
session, base_url, path, headers, config, logger, batcher, manager, start_ms, start_row_offset
)
+ elif config.pagination == "agreement_fanout":
+ assert org_id is not None
+ start_page = resume.parent_page if resume and resume.parent_page is not None else 0
+ start_index = resume.parent_index if resume and resume.parent_index is not None else 0
+ yield from _iter_agreement_fanout(
+ session, base_url, org_id, path, headers, config, logger, batcher, manager, start_page, start_index
+ )
+
if batcher.should_yield(include_incomplete_chunk=True):
yield batcher.get_table()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/concord/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/concord/settings.py
index 4d8d37c8a70f..7240c7b04aba 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/concord/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/concord/settings.py
@@ -9,7 +9,8 @@ from products.warehouse_sources.backend.types import IncrementalField, Increment
# - "single": one request, the whole collection comes back in a wrapper object.
# - "folders_tree": single request returning a nested folder tree we flatten into rows.
# - "events_window": audit log capped at 7-day windows, walked one week at a time.
-PaginationStyle = Literal["page", "offset", "single", "folders_tree", "events_window"]
+# - "agreement_fanout": one request per agreement, walking the agreements list as the parent.
+PaginationStyle = Literal["page", "offset", "single", "folders_tree", "events_window", "agreement_fanout"]
# Concord returns the full agreement list only when at least one stage filter is supplied, so we
# request every documented stage. Keeping this explicit (rather than relying on a default) means a
@@ -33,7 +34,7 @@ AGREEMENT_STATUSES = [
]
-@dataclass
+@dataclass(frozen=False)
class ConcordEndpointConfig:
name: str
path: str # may contain a `{organization_id}` placeholder
@@ -65,6 +66,9 @@ class ConcordEndpointConfig:
requires_admin: bool = False
# Limit the first sync of an unbounded append-only resource to the last N days.
default_lookback_days: Optional[int] = None
+ # Extra query params a per-agreement child request always needs (e.g. the required `type` on
+ # /activities). Only read by "agreement_fanout" endpoints.
+ fanout_params: dict[str, str] = field(default_factory=dict)
description: Optional[str] = None
@@ -186,6 +190,61 @@ CONCORD_ENDPOINTS: dict[str, ConcordEndpointConfig] = {
default_lookback_days=365,
description="Organization audit log. Requires the Administrator role. Append only.",
),
+ "agreement_activities": ConcordEndpointConfig(
+ name="agreement_activities",
+ path="/organizations/{organization_id}/agreements/{agreement_uid}/activities",
+ pagination="agreement_fanout",
+ data_selector="activities",
+ # Activity ids are only documented as unique within their agreement, so key on the parent too.
+ primary_keys=["agreement_uuid", "id"],
+ partition_key="createdAt",
+ # `type` is a required query param. AUDIT is the action timeline (viewed, signed, approved);
+ # CHAT is the negotiation message thread, which is a different resource.
+ fanout_params={"type": "AUDIT"},
+ should_sync_default=False,
+ description="Per-agreement audit timeline (viewed, signed, approved). One request per agreement, so it is off by default.",
+ ),
+ "agreement_members": ConcordEndpointConfig(
+ name="agreement_members",
+ path="/organizations/{organization_id}/agreements/{agreement_uid}/members",
+ pagination="agreement_fanout",
+ # The response body is itself the array, with no wrapper key.
+ data_selector=None,
+ # Rows mix active users with pending and delayed invitations; `status` separates the id
+ # spaces `member_id` draws from, so all three parts are needed to stay unique.
+ primary_keys=["agreement_uuid", "status", "member_id"],
+ should_sync_default=False,
+ description="Who has access to each agreement, with their permission and signer status. One request per agreement, so it is off by default.",
+ ),
+ "agreement_fields": ConcordEndpointConfig(
+ name="agreement_fields",
+ path="/organizations/{organization_id}/agreements/{agreement_uid}/summary/fields",
+ pagination="agreement_fanout",
+ data_selector="fields",
+ primary_keys=["agreement_uuid", "id"],
+ should_sync_default=False,
+ description="Smart fields captured on each agreement, such as contract value or renewal date. One request per agreement, so it is off by default.",
+ ),
+ "agreement_clauses": ConcordEndpointConfig(
+ name="agreement_clauses",
+ # Concord has no GET for /summary/clauses — the clause instances are only listed inside the
+ # agreement summary, so both clause tables read it and select a different array.
+ path="/organizations/{organization_id}/agreements/{agreement_uid}/summary",
+ pagination="agreement_fanout",
+ data_selector="clauses",
+ primary_keys=["agreement_uuid", "id"],
+ should_sync_default=False,
+ description="Clause instances on each agreement, joining agreements to the organization clause library. One request per agreement, so it is off by default.",
+ ),
+ "agreement_endclauses": ConcordEndpointConfig(
+ name="agreement_endclauses",
+ path="/organizations/{organization_id}/agreements/{agreement_uid}/summary",
+ pagination="agreement_fanout",
+ data_selector="endclauses",
+ primary_keys=["agreement_uuid", "id"],
+ should_sync_default=False,
+ description="Renewal and termination clauses on each agreement, with notice periods and auto-renewal terms. One request per agreement, so it is off by default.",
+ ),
}
ENDPOINTS = tuple(CONCORD_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/concord/tests/test_concord.py b/products/warehouse_sources/backend/temporal/data_imports/sources/concord/tests/test_concord.py
index 528bdf1a2a41..fcaae070fc16 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/concord/tests/test_concord.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/concord/tests/test_concord.py
@@ -5,6 +5,7 @@ import pytest
import time_machine
from unittest import mock
+import requests
from parameterized import parameterized
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.batcher import Batcher
@@ -14,8 +15,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.concord.co
ConcordResumeConfig,
_agreement_incremental_params,
_flatten_folder_tree,
+ _iter_agreement_fanout,
_iter_events_windows,
_iter_page,
+ _member_id,
_to_epoch_ms,
base_url_for_environment,
concord_source,
@@ -367,6 +370,156 @@ class TestEventsWindowPagination:
assert emitted == [3, 4]
+class TestMemberId:
+ @parameterized.expand(
+ [
+ ("active_user", {"status": "ACTIVE", "user": {"id": 7}}, 7),
+ ("invitation", {"status": "INVITED", "invitation": {"id": 3}}, 3),
+ # An invitation can carry the invitee's user account too; the invitation id still wins so
+ # every INVITED row is keyed on the same id space.
+ ("invitation_with_user", {"status": "INVITED", "user": {"id": 7}, "invitation": {"id": 3}}, 3),
+ ("neither", {"status": "ACTIVE"}, None),
+ ]
+ )
+ def test_member_id(self, _name, row, expected):
+ assert _member_id(row) == expected
+
+
+class TestAgreementFanout:
+ def _run(self, endpoint, *, agreements, child, manager=None):
+ """Drive get_rows for a fan-out endpoint; `child` may be a payload or a url->payload callable."""
+ urls: list[str] = []
+ manager = manager or FakeManager()
+
+ def fake_fetch(session, url, headers, logger):
+ urls.append(url)
+ if "/user/me/organizations" in url:
+ return {"items": agreements}
+ return child(url) if callable(child) else child
+
+ with mock.patch.object(concord, "_fetch", side_effect=fake_fetch):
+ rows = _collect(
+ get_rows(
+ api_key="key",
+ environment="production",
+ organization_id="42",
+ endpoint=endpoint,
+ logger=mock.MagicMock(),
+ manager=manager,
+ )
+ )
+ return rows, urls, manager
+
+ def test_fetches_each_agreement_and_injects_the_parent_uid(self):
+ rows, urls, _ = self._run(
+ "agreement_fields",
+ agreements=[{"uuid": "A"}, {"uuid": "B"}],
+ child={"fields": [{"id": 1, "name": "price", "value": "10"}]},
+ )
+ assert [(r["agreement_uuid"], r["id"]) for r in rows] == [("A", 1), ("B", 1)]
+ assert any("/agreements/A/summary/fields" in url for url in urls)
+ assert any("/agreements/B/summary/fields" in url for url in urls)
+
+ def test_activities_send_the_required_type_param(self):
+ _rows, urls, _ = self._run(
+ "agreement_activities",
+ agreements=[{"uuid": "A"}],
+ child={"activities": [{"id": "e1", "createdAt": 1700000000000}]},
+ )
+ assert "type=AUDIT" in urls[-1]
+
+ def test_members_read_a_bare_array_response(self):
+ rows, _urls, _ = self._run(
+ "agreement_members",
+ agreements=[{"uuid": "A"}],
+ child=[{"status": "ACTIVE", "user": {"id": 7}}],
+ )
+ assert [(r["agreement_uuid"], r["status"], r["member_id"]) for r in rows] == [("A", "ACTIVE", 7)]
+
+ def test_members_keep_user_and_invitation_ids_apart(self):
+ rows, _urls, _ = self._run(
+ "agreement_members",
+ agreements=[{"uuid": "A"}],
+ child=[
+ {"status": "ACTIVE", "user": {"id": 7, "email": "[email protected]"}},
+ {"status": "INVITED", "invitation": {"id": 7, "email": "[email protected]"}},
+ ],
+ )
+ # The same numeric id in two id spaces must stay two rows, or merge would collapse them.
+ assert [(r["status"], r["member_id"]) for r in rows] == [("ACTIVE", 7), ("INVITED", 7)]
+
+ def test_clause_tables_select_different_arrays_of_one_summary_response(self):
+ summary = {"clauses": [{"id": 1, "title": "term"}], "endclauses": [{"id": 9, "title": "renewal"}]}
+ clauses, clause_urls, _ = self._run("agreement_clauses", agreements=[{"uuid": "A"}], child=summary)
+ endclauses, _urls, _ = self._run("agreement_endclauses", agreements=[{"uuid": "A"}], child=summary)
+ assert [r["id"] for r in clauses] == [1]
+ assert [r["id"] for r in endclauses] == [9]
+ assert any(url.endswith("/agreements/A/summary") for url in clause_urls)
+
+ @parameterized.expand([("forbidden", 403), ("not_found", 404)])
+ def test_skips_an_agreement_the_key_cannot_read(self, _name, status_code):
+ def child(url):
+ if "/agreements/A/" in url:
+ response = requests.Response()
+ response.status_code = status_code
+ raise requests.HTTPError(response=response)
+ return {"fields": [{"id": 1}]}
+
+ rows, _urls, _ = self._run("agreement_fields", agreements=[{"uuid": "A"}, {"uuid": "B"}], child=child)
+ assert [r["agreement_uuid"] for r in rows] == ["B"]
+
+ def test_other_child_errors_fail_the_sync(self):
+ def child(url):
+ response = requests.Response()
+ response.status_code = 400
+ raise requests.HTTPError(response=response)
+
+ with pytest.raises(requests.HTTPError):
+ self._run("agreement_fields", agreements=[{"uuid": "A"}], child=child)
+
+ def test_resumes_from_the_saved_parent_position(self):
+ manager = FakeManager(ConcordResumeConfig(parent_page=3, parent_index=1))
+ rows, urls, _ = self._run(
+ "agreement_fields",
+ agreements=[{"uuid": "A"}, {"uuid": "B"}],
+ child={"fields": [{"id": 1}]},
+ manager=manager,
+ )
+ assert "page=3" in urls[0]
+ # agreement A finished last run, so only B is fetched again
+ assert [r["agreement_uuid"] for r in rows] == ["B"]
+
+ def test_mid_agreement_flush_checkpoints_the_agreement_still_in_flight(self):
+ manager = FakeManager()
+ # chunk_size=2 flushes every two rows, so each agreement's three rows straddle a flush.
+ batcher = Batcher(logger=mock.MagicMock(), chunk_size=2)
+
+ def fake_fetch(session, url, headers, logger):
+ if "/user/me/organizations" in url:
+ return {"items": [{"uuid": "A"}, {"uuid": "B"}]}
+ return {"fields": [{"id": 1}, {"id": 2}, {"id": 3}]}
+
+ with mock.patch.object(concord, "_fetch", side_effect=fake_fetch):
+ list(
+ _iter_agreement_fanout(
+ session=mock.MagicMock(),
+ base_url="https://x",
+ org_id="42",
+ child_template="/organizations/42/agreements/{agreement_uid}/summary/fields",
+ headers={},
+ config=CONCORD_ENDPOINTS["agreement_fields"],
+ logger=mock.MagicMock(),
+ batcher=batcher,
+ manager=manager,
+ start_page=0,
+ start_index=0,
+ )
+ )
+ # The checkpoint never names an agreement past the one being batched: A's third row is still
+ # buffered when the first flush fires, so a resume has to redo A rather than skip to B.
+ assert [(s.parent_page, s.parent_index) for s in manager.saved] == [(0, 0), (0, 1), (0, 1)]
+
+
class TestConcordSource:
@parameterized.expand(list(CONCORD_ENDPOINTS.keys()))
def test_source_response_shape(self, endpoint):