Skip to content

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

feat(data-warehouse): add gorgias custom fields, voice calls, and ticket join tables (#109925)

Tom Owers4dac678ed5ae
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 2791efb93276..a5ab475d276f 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
@@ -3772,10 +3772,10 @@ Today (9): `customers`, `macros`, `messages`, `satisfaction_surveys`, `tags`, `t
Diffed against: <https://developers.gorgias.com/llms.txt>
- [ ] `events (/api/events)` — the account-wide event stream, including ticket state transitions and assignment changes - the only way to do time-in-status or SLA analysis (high)
-- [ ] `ticket_tags (/api/tickets/{id}/tags)` — the ticket-to-tag join; we sync tags and tickets but not the mapping between them (high)
-- [ ] `voice_calls` — phone channel fact table, entirely absent today (high)
-- [ ] `custom_fields` — lookup resolving the custom field IDs used on tickets and customers (high)
-- [ ] `ticket_field_values (/api/tickets/{id}/custom-fields)` — per-ticket custom field values, including system fields like AI Intent and AI Agent Outcome (high)
+- [x] `ticket_tags (/api/tickets/{id}/tags)` — the ticket-to-tag join; we sync tags and tickets but not the mapping between them (high)
+- [x] `voice_calls` — phone channel fact table, entirely absent today (high)
+- [x] `custom_fields` — lookup resolving the custom field IDs used on tickets and customers (high)
+- [x] `ticket_field_values (/api/tickets/{id}/custom-fields)` — per-ticket custom field values, including system fields like AI Intent and AI Agent Outcome (high)
- [ ] `customer_field_values (/api/customers/{id}/custom-fields)` — per-customer custom field values (medium)
- [ ] `voice_call_events` — per-call state transitions (ringing, answered, transferred) for phone queue analysis (medium)
- [ ] `voice_call_recordings` — recording metadata joined to voice calls (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gorgias/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gorgias/canonical_descriptions.py
index bf585f7194d7..fc7a6f7a0ae7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gorgias/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gorgias/canonical_descriptions.py
@@ -133,4 +133,55 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
decoration="Color or styling of the team.",
),
},
+ "custom_fields": {
+ "description": "A custom field definition that can be set on tickets or customers.",
+ "docs_url": "https://developers.gorgias.com/reference/the-customfield-object",
+ "columns": _columns(
+ object_type="Type of object the field applies to (Ticket or Customer).",
+ label="Name of the field shown to agents.",
+ description="Description of the field.",
+ priority="Display order of the field.",
+ required="Whether a value is required.",
+ managed_type="Set when Gorgias manages the field (e.g. AI Intent), otherwise null.",
+ definition="Data type and input settings of the field, such as dropdown choices.",
+ external_id="ID of the field in a foreign system.",
+ deactivated_datetime="Time at which the field was archived, if applicable.",
+ ),
+ },
+ "voice_calls": {
+ "description": "A phone call handled through a Gorgias voice integration.",
+ "docs_url": "https://developers.gorgias.com/reference/the-voicecall-object",
+ "columns": _columns(
+ ticket_id="ID of the ticket the call is attached to.",
+ customer_id="ID of the customer on the call.",
+ integration_id="ID of the phone integration that handled the call.",
+ direction="Direction of the call (inbound or outbound).",
+ status="Status of the call.",
+ duration="Duration of the call in seconds.",
+ started_datetime="Time at which the call started.",
+ ),
+ },
+ "ticket_tags": {
+ "description": "One row per tag applied to a ticket, linking tickets to tags.",
+ "docs_url": "https://developers.gorgias.com/reference/list-ticket-tags",
+ "columns": {
+ "ticket_id": "ID of the ticket.",
+ "ticket_created_datetime": "Time at which the ticket was created.",
+ "id": "ID of the tag. Joins to the tags table.",
+ "name": "Name of the tag.",
+ "decoration": "Color or styling of the tag.",
+ },
+ },
+ "ticket_field_values": {
+ "description": "One row per custom field value set on a ticket, including Gorgias-managed fields.",
+ "docs_url": "https://developers.gorgias.com/reference/list-ticket-custom-fields",
+ "columns": {
+ "ticket_id": "ID of the ticket.",
+ "ticket_created_datetime": "Time at which the ticket was created.",
+ "field_id": "ID of the custom field. Joins to the custom_fields table.",
+ "field": "Definition of the custom field.",
+ "value": "Value of the field on the ticket, as text.",
+ "prediction": "Value predicted by Gorgias for the field, if any.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gorgias/gorgias.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gorgias/gorgias.py
index a99c3a531910..ebc6faaae3b7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gorgias/gorgias.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gorgias/gorgias.py
@@ -1,4 +1,5 @@
import re
+import json
import base64
import dataclasses
from collections.abc import Iterator
@@ -33,11 +34,13 @@ class GorgiasRetryableError(Exception):
pass
[email protected](frozen=True)
class GorgiasResumeConfig:
# Opaque, short-lived cursor token returned in `meta.next_cursor`. We only persist
# it for the duration of a single sync (Redis TTL is 24h) — never longer-term.
- cursor: str
+ cursor: str | None
+ # Index into the endpoint's `param_variants` the cursor belongs to.
+ variant: int = 0
def normalize_domain(domain: str) -> str:
@@ -99,6 +102,37 @@ def _incremental_sort_field(
return None
+def _flatten_ticket_child(tickets: list[Any], child: str) -> list[dict[str, Any]]:
+ rows: list[dict[str, Any]] = []
+ for ticket in tickets:
+ if not isinstance(ticket, dict):
+ continue
+ parent = {"ticket_id": ticket.get("id"), "ticket_created_datetime": ticket.get("created_datetime")}
+ if child == "tags":
+ for tag in ticket.get("tags") or []:
+ if isinstance(tag, dict) and tag.get("id") is not None:
+ rows.append({**tag, **parent})
+ elif child == "custom_fields":
+ # Keyed by custom field id: {"<field_id>": {"id", "field", "value", "prediction"}}.
+ for field_id, field_value in (ticket.get("custom_fields") or {}).items():
+ if not isinstance(field_value, dict):
+ continue
+ value = field_value.get("value")
+ rows.append(
+ {
+ **field_value,
+ **parent,
+ "field_id": int(field_id) if str(field_id).isdigit() else field_id,
+ # Values are text, number, or boolean depending on the field, so keep the
+ # column one type rather than mixing them across rows.
+ "value": value if value is None or isinstance(value, str) else json.dumps(value),
+ }
+ )
+ else:
+ raise ValueError(f"Unknown Gorgias ticket child collection: {child}")
+ return rows
+
+
def _get_auth_header(email: str, api_key: str) -> str:
token = base64.b64encode(f"{email}:{api_key}".encode()).decode()
return f"Basic {token}"
@@ -159,7 +193,8 @@ def get_rows(
resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
cursor = resume_config.cursor if resume_config else None
- if cursor:
+ start_variant = resume_config.variant if resume_config else 0
+ if resume_config:
logger.debug(f"Gorgias: resuming {endpoint} from saved cursor")
@retry(
@@ -170,13 +205,15 @@ def get_rows(
wait=wait_exponential_jitter(initial=1, max=30),
reraise=True,
)
- def fetch_page(request_cursor: str | None) -> dict[str, Any]:
+ def fetch_page(request_cursor: str | None, variant_params: dict[str, str]) -> Any:
# `cursor` is documented as "position in the list of resources" — the list is
# defined by `order_by`/`limit`, so we re-send them on every page to keep the
# sort stable. The docs list `cursor` and `order_by` as coexisting params (no
# mutual exclusion); dropping order_by on follow-up pages could reset to the
# endpoint default and corrupt the newest-first order incremental relies on.
- params: dict[str, Any] = {"limit": PAGE_SIZE, "order_by": order_by}
+ params: dict[str, Any] = {"limit": PAGE_SIZE, **variant_params}
+ if order_by:
+ params["order_by"] = order_by
if request_cursor:
params["cursor"] = request_cursor
@@ -192,28 +229,37 @@ def get_rows(
response.raise_for_status()
return response.json()
- while True:
- data = fetch_page(cursor)
-
- items = data.get("data", [])
- if items:
- yield items
-
- # Rows arrive newest-first under incremental sort; once an entire page predates the
- # watermark, everything further back is already synced, so stop.
- if watermark is not None and sort_field is not None and items:
- page_newest = _page_newest(items, sort_field)
- if page_newest is not None and page_newest < watermark:
+ for variant_index in range(start_variant, len(config.param_variants)):
+ variant_params = config.param_variants[variant_index]
+ while True:
+ data = fetch_page(cursor, variant_params)
+
+ items = data.get("data", [])
+ next_cursor = (data.get("meta") or {}).get("next_cursor")
+
+ # Rows arrive newest-first under incremental sort; once an entire page predates the
+ # watermark, everything further back is already synced, so stop.
+ reached_watermark = False
+ if watermark is not None and sort_field is not None and items:
+ page_newest = _page_newest(items, sort_field)
+ reached_watermark = page_newest is not None and page_newest < watermark
+
+ # Stage the position after this page before yielding it. A resumed full refresh
+ # appends, so a cursor that lags one page behind would write that page twice. The
+ # final page stages a variant past the end, so a resume after it reads nothing.
+ if next_cursor and not reached_watermark:
+ resumable_source_manager.save_state(GorgiasResumeConfig(cursor=next_cursor, variant=variant_index))
+ else:
+ resumable_source_manager.save_state(GorgiasResumeConfig(cursor=None, variant=variant_index + 1))
+
+ if items:
+ yield _flatten_ticket_child(items, config.ticket_child) if config.ticket_child else items
+
+ if not next_cursor or reached_watermark:
break
+ cursor = next_cursor
- next_cursor = (data.get("meta") or {}).get("next_cursor")
- if not next_cursor:
- break
-
- cursor = next_cursor
- # Save AFTER yielding so a crash re-yields the last batch (merge dedupes on the
- # primary key) instead of skipping it.
- resumable_source_manager.save_state(GorgiasResumeConfig(cursor=cursor))
+ cursor = None
def gorgias_source(
@@ -243,7 +289,7 @@ def gorgias_source(
incremental_field=incremental_field,
db_incremental_field_last_value=db_incremental_field_last_value,
),
- primary_keys=["id"],
+ primary_keys=list(config.primary_keys),
partition_count=1,
partition_size=1,
partition_mode="datetime",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gorgias/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gorgias/settings.py
index 289468286ff7..790b2ff0ea1d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gorgias/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gorgias/settings.py
@@ -16,7 +16,7 @@ CREATED = "created_datetime"
UPDATED = "updated_datetime"
-@dataclass
+@dataclass(frozen=True)
class GorgiasEndpointConfig:
name: str
path: str
@@ -26,8 +26,9 @@ class GorgiasEndpointConfig:
partition_key: str = CREATED
# Explicit ascending sort on the stable creation field keeps page boundaries
# stable across a full-refresh sync even if rows are inserted while we paginate.
- # Every list endpoint accepts `created_datetime:asc` (verified against the docs).
- order_by: str = f"{CREATED}:asc"
+ # Most list endpoints accept `created_datetime:asc` (verified against the docs).
+ # None for endpoints that accept no `order_by` at all (voice calls).
+ order_by: str | None = f"{CREATED}:asc"
# Datetime attributes this endpoint actually accepts in `order_by` — verified
# per-endpoint against the Gorgias docs, because they differ: `users` exposes no
# `updated_datetime` (only name/email/role), `messages` is created-only, etc.
@@ -46,6 +47,14 @@ class GorgiasEndpointConfig:
# Cursor fields offered to the user. Only advertise a field whose desc-sort yields
# correct incremental semantics for this resource (must be in sortable_datetime_fields).
incremental_fields: list[IncrementalField] = field(default_factory=list)
+ primary_keys: tuple[str, ...] = ("id",)
+ # One full pagination pass per entry, merged into a single table. `custom-fields`
+ # requires `object_type`, so it is listed once per type.
+ param_variants: tuple[dict[str, str], ...] = ({},)
+ # Name of a nested collection on each ticket to flatten into one row per item. The
+ # ticket list already embeds `tags` and `custom_fields`, so this avoids one request per
+ # ticket against the per-ticket `/tickets/{id}/tags` and `/tickets/{id}/custom-fields`.
+ ticket_child: str | None = None
GORGIAS_ENDPOINTS: dict[str, GorgiasEndpointConfig] = {
@@ -109,6 +118,37 @@ GORGIAS_ENDPOINTS: dict[str, GorgiasEndpointConfig] = {
path="/teams",
sortable_datetime_fields=frozenset({CREATED}),
),
+ "custom_fields": GorgiasEndpointConfig(
+ name="custom_fields",
+ path="/custom-fields",
+ order_by="priority:asc",
+ sortable_datetime_fields=frozenset(),
+ param_variants=({"object_type": "Ticket"}, {"object_type": "Customer"}),
+ ),
+ "voice_calls": GorgiasEndpointConfig(
+ name="voice_calls",
+ path="/phone/voice-calls",
+ order_by=None,
+ sortable_datetime_fields=frozenset(),
+ ),
+ # Derived from the ticket list, so they stay full refresh: a removed tag or cleared field
+ # value has no ticket-level row left to delete it on merge.
+ "ticket_tags": GorgiasEndpointConfig(
+ name="ticket_tags",
+ path="/tickets",
+ partition_key=f"ticket_{CREATED}",
+ sortable_datetime_fields=frozenset({CREATED, UPDATED}),
+ primary_keys=("ticket_id", "id"),
+ ticket_child="tags",
+ ),
+ "ticket_field_values": GorgiasEndpointConfig(
+ name="ticket_field_values",
+ path="/tickets",
+ partition_key=f"ticket_{CREATED}",
+ sortable_datetime_fields=frozenset({CREATED, UPDATED}),
+ primary_keys=("ticket_id", "field_id"),
+ ticket_child="custom_fields",
+ ),
}
ENDPOINTS = tuple(GORGIAS_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gorgias/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gorgias/source.py
index e23e5edd34f5..7624656ae396 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gorgias/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gorgias/source.py
@@ -123,7 +123,7 @@ class GorgiasSource(ResumableSource[GorgiasSourceConfig, GorgiasResumeConfig]):
Create an API key in your Gorgias account under **Settings → REST API**. Use the email of the account that owns the key together with the key itself.
-This source authenticates with HTTP Basic Auth (email + API key) and requires read access to the endpoints you want to sync (tickets, messages, customers, users, satisfaction surveys, tags, views, teams, macros).""",
+This source authenticates with HTTP Basic Auth (email + API key) and requires read access to the endpoints you want to sync (tickets, messages, customers, users, satisfaction surveys, tags, views, teams, macros, custom fields, voice calls).""",
iconPath="/static/services/gorgias.png",
docsUrl="https://posthog.com/docs/cdp/sources/gorgias",
releaseStatus=ReleaseStatus.GA,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gorgias/tests/test_gorgias.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gorgias/tests/test_gorgias.py
index db663fe79edd..03959b2db3d6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gorgias/tests/test_gorgias.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gorgias/tests/test_gorgias.py
@@ -27,15 +27,18 @@ GORGIAS_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sourc
class _FakeManager(ResumableSourceManager[GorgiasResumeConfig]):
"""Minimal stand-in for ResumableSourceManager that records saved state in memory."""
- def __init__(self, resume_cursor: str | None = None) -> None:
+ def __init__(self, resume_cursor: str | None = None, resume_variant: int = 0) -> None:
self._resume_cursor = resume_cursor
+ self._resume_variant = resume_variant
self.saved: list[GorgiasResumeConfig] = []
def can_resume(self) -> bool:
return self._resume_cursor is not None
def load_state(self) -> GorgiasResumeConfig | None:
- return GorgiasResumeConfig(cursor=self._resume_cursor) if self._resume_cursor else None
+ if not self._resume_cursor:
+ return None
+ return GorgiasResumeConfig(cursor=self._resume_cursor, variant=self._resume_variant)
def save_state(self, data: GorgiasResumeConfig) -> None:
self.saved.append(data)
@@ -148,7 +151,7 @@ class TestGetRows:
assert batches == [[{"id": 1}], [{"id": 2}]]
assert session.get.call_count == 2
- def test_saves_cursor_after_yielding_each_batch(self) -> None:
+ def test_stages_next_position_before_yielding_each_batch(self) -> None:
session = MagicMock()
session.get.side_effect = [
_response(json_body={"data": [{"id": 1}], "meta": {"next_cursor": "c2"}}),
@@ -156,10 +159,13 @@ class TestGetRows:
]
manager = _FakeManager()
with patch(f"{GORGIAS_MODULE}.make_tracked_session", return_value=session):
- list(get_rows("acme", "[email protected]", "key", "tickets", MagicMock(), manager))
-
- # Only the page that has a following cursor triggers a save.
- assert [c.cursor for c in manager.saved] == ["c2"]
+ rows = get_rows("acme", "[email protected]", "key", "tickets", MagicMock(), manager)
+ assert next(rows) == [{"id": 1}]
+ assert manager.saved[-1] == GorgiasResumeConfig(cursor="c2", variant=0)
+ assert next(rows) == [{"id": 2}]
+ # The last page stages a position past the only variant, so a resume reads nothing.
+ assert manager.saved[-1] == GorgiasResumeConfig(cursor=None, variant=1)
+ assert list(rows) == []
def test_resumes_from_saved_cursor(self) -> None:
session = MagicMock()
@@ -191,7 +197,104 @@ class TestGetRows:
batches = list(get_rows("acme", "[email protected]", "key", "tickets", MagicMock(), manager))
assert batches == []
- assert manager.saved == []
+
+
+class TestParamVariants:
+ def test_custom_fields_paginates_each_object_type_from_a_fresh_cursor(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = [
+ _response(json_body={"data": [{"id": 1}], "meta": {"next_cursor": "t2"}}),
+ _response(json_body={"data": [{"id": 2}], "meta": {"next_cursor": None}}),
+ _response(json_body={"data": [{"id": 3}], "meta": {"next_cursor": None}}),
+ ]
+ manager = _FakeManager()
+ with patch(f"{GORGIAS_MODULE}.make_tracked_session", return_value=session):
+ batches = list(get_rows("acme", "[email protected]", "key", "custom_fields", MagicMock(), manager))
+
+ assert batches == [[{"id": 1}], [{"id": 2}], [{"id": 3}]]
+ params = [c.kwargs["params"] for c in session.get.call_args_list]
+ assert [(p["object_type"], p.get("cursor")) for p in params] == [
+ ("Ticket", None),
+ ("Ticket", "t2"),
+ ("Customer", None),
+ ]
+ assert all(p["order_by"] == "priority:asc" for p in params)
+ assert [(c.variant, c.cursor) for c in manager.saved] == [(0, "t2"), (1, None), (2, None)]
+
+ def test_resumes_into_saved_variant(self) -> None:
+ session = MagicMock()
+ session.get.return_value = _response(json_body={"data": [], "meta": {"next_cursor": None}})
+ manager = _FakeManager(resume_cursor="c9", resume_variant=1)
+ with patch(f"{GORGIAS_MODULE}.make_tracked_session", return_value=session):
+ list(get_rows("acme", "[email protected]", "key", "custom_fields", MagicMock(), manager))
+
+ assert session.get.call_count == 1
+ params = session.get.call_args.kwargs["params"]
+ assert params["object_type"] == "Customer"
+ assert params["cursor"] == "c9"
+
+ def test_voice_calls_sends_no_order_by(self) -> None:
+ session = MagicMock()
+ session.get.return_value = _response(json_body={"data": [], "meta": {"next_cursor": None}})
+ with patch(f"{GORGIAS_MODULE}.make_tracked_session", return_value=session):
+ list(get_rows("acme", "[email protected]", "key", "voice_calls", MagicMock(), _FakeManager()))
+
+ url = session.get.call_args.args[0]
+ assert url == "https://acme.gorgias.com/api/phone/voice-calls"
+ assert "order_by" not in session.get.call_args.kwargs["params"]
+
+
+class TestTicketChildTables:
+ def _rows(self, endpoint: str, tickets: list[dict]) -> list[dict]:
+ session = MagicMock()
+ session.get.return_value = _response(json_body={"data": tickets, "meta": {"next_cursor": None}})
+ with patch(f"{GORGIAS_MODULE}.make_tracked_session", return_value=session):
+ batches = list(get_rows("acme", "[email protected]", "key", endpoint, MagicMock(), _FakeManager()))
+ assert session.get.call_args.args[0] == "https://acme.gorgias.com/api/tickets"
+ return [row for batch in batches for row in batch]
+
+ def test_ticket_tags_flattens_one_row_per_tag(self) -> None:
+ rows = self._rows(
+ "ticket_tags",
+ [
+ {
+ "id": 10,
+ "created_datetime": "2024-01-01T00:00:00+00:00",
+ "tags": [{"id": 1, "name": "urgent"}, {"name": "no-id"}],
+ },
+ {"id": 11, "created_datetime": "2024-02-01T00:00:00+00:00", "tags": []},
+ ],
+ )
+
+ assert rows == [
+ {"id": 1, "name": "urgent", "ticket_id": 10, "ticket_created_datetime": "2024-01-01T00:00:00+00:00"}
+ ]
+
+ def test_ticket_field_values_keys_by_field_and_keeps_value_one_type(self) -> None:
+ rows = self._rows(
+ "ticket_field_values",
+ [
+ {
+ "id": 10,
+ "created_datetime": "2024-01-01T00:00:00+00:00",
+ "custom_fields": {
+ "5": {"id": 5, "value": "Order::Status", "prediction": None},
+ "6": {"id": 6, "value": 3},
+ "7": {"id": 7, "value": True},
+ "8": {"id": 8, "value": None},
+ },
+ },
+ {"id": 11, "created_datetime": "2024-02-01T00:00:00+00:00", "custom_fields": None},
+ ],
+ )
+
+ assert [(r["ticket_id"], r["field_id"], r["value"]) for r in rows] == [
+ (10, 5, "Order::Status"),
+ (10, 6, "3"),
+ (10, 7, "true"),
+ (10, 8, None),
+ ]
+ assert all(r["ticket_created_datetime"] == "2024-01-01T00:00:00+00:00" for r in rows)
class TestIncrementalSync:
@@ -359,6 +462,13 @@ DOCUMENTED_ORDER_BY_DATETIME_FIELDS: dict[str, set[str]] = {
"tags": {"created_datetime"},
"views": {"created_datetime"},
"teams": {"created_datetime"},
+ "custom_fields": set(), # only priority:asc/desc
+ "voice_calls": set(), # accepts no order_by
+ "ticket_tags": {"created_datetime", "updated_datetime"},
+ "ticket_field_values": {"created_datetime", "updated_datetime"},
+}
+DOCUMENTED_NON_DATETIME_ORDER_BY: dict[str, set[str]] = {
+ "custom_fields": {"priority:asc", "priority:desc"},
}
@@ -373,9 +483,15 @@ class TestApiContract:
@parameterized.expand([(name,) for name in ENDPOINTS])
def test_full_refresh_order_by_is_accepted_by_endpoint(self, endpoint: str) -> None:
config = GORGIAS_ENDPOINTS[endpoint]
- field, _, direction = config.order_by.partition(":")
- assert field in DOCUMENTED_ORDER_BY_DATETIME_FIELDS[endpoint]
- assert direction in {"asc", "desc"}
+ accepted = {
+ f"{field}:{direction}"
+ for field in DOCUMENTED_ORDER_BY_DATETIME_FIELDS[endpoint]
+ for direction in ("asc", "desc")
+ } | DOCUMENTED_NON_DATETIME_ORDER_BY.get(endpoint, set())
+ if accepted:
+ assert config.order_by in accepted
+ else:
+ assert config.order_by is None
@parameterized.expand([(name,) for name in ENDPOINTS])
def test_advertised_incremental_fields_are_sortable(self, endpoint: str) -> None:
@@ -409,7 +525,7 @@ class TestGorgiasSource:
def test_source_response_shape(self, endpoint: str) -> None:
response = gorgias_source("acme", "[email protected]", "key", endpoint, MagicMock(), _FakeManager())
assert response.name == endpoint
- assert response.primary_keys == ["id"]
+ assert response.primary_keys == list(GORGIAS_ENDPOINTS[endpoint].primary_keys)
assert response.partition_mode == "datetime"
assert response.partition_keys == [GORGIAS_ENDPOINTS[endpoint].partition_key]
assert response.sort_mode == "asc"
@@ -436,5 +552,5 @@ class TestGorgiasSource:
def test_every_endpoint_partitions_on_created_datetime(self) -> None:
for config in GORGIAS_ENDPOINTS.values():
- assert config.partition_key == "created_datetime"
+ assert config.partition_key in ("created_datetime", "ticket_created_datetime")
assert "updated" not in config.partition_key