SQL CookbookGenesys & IVR

SQL COOKBOOK · GENESYS & IVR

Genesys & IVR

Twelve columns, three indexes, and nothing in the repo that fills them. Here is what to query instead.

"Response" carries twelve denormalised Genesys columns, all snake_case, all nullable. Three indexes exist for exactly this reporting. And no code path at hivecfm-core@origin/development writes any of the twelve — the only file that reads them by name is the Superset view script. Read the two sections below before you write a query against them, because a report shaped for the columns will return zero rows on a stock instance while the data you want sits in Response.meta.

Every recipe on this page carries an explicit tenant predicate, and every SQL block was planned against devhub_ref (the zero-row schema mirror of origin/development). The exception is the bare EXPLAIN snippets in The three indexes below, which deliberately drop the join so the plan shows one index choice and nothing else — read those as plan-shape demonstrations, not as recipes to copy. Where a query was also run against real rows, the page says so. The tenant rule itself is in Read this first — do not rely on RLS.

Twelve columns, not thirteen

genesys_conversation_id      text
genesys_agent_id             text
genesys_agent_name           text
genesys_queue_id             text
genesys_queue_name           text
genesys_handle_time          integer
genesys_wrap_code            text
genesys_direction            text
genesys_ani                  text
genesys_dnis                 text
genesys_conversation_start   timestamp without time zone
genesys_conversation_end     timestamp without time zone

The two timestamps are declared TIMESTAMP(3) in the migration; information_schema reports the base type without the precision. Counted from the catalog, not from memory:

echo "select column_name, data_type from information_schema.columns
      where table_schema='public' and table_name='Response'
        and column_name like 'genesys%' order by ordinal_position;" \
| docker exec -i hivecfm-postgres-t3060 psql -U postgres -d devhub_ref

Twelve rows. The number is easy to get wrong because two more columns sit in the same block of the schema and the same migration:

ColumnWritten by app code?Where
the twelve genesys_* aboveNonowhere at this ref
survey_delivery_channelYesapps/web/lib/response/service.ts:886 (caller-supplied), :944 (hard-coded "email")
survey_delivered_atYessame two call sites

Keep those two groups apart in your head. They arrived together in packages/database/migration/20260114220000_add_genesys_context_fields/migration.sql, which adds all fourteen columns and the three indexes in one file, but only the delivery pair has a writer.

⚠️

The columns are defined, indexed, documented — and unpopulated. Three greps at origin/development, all over *.ts *.tsx *.js *.cjs *.mjs *.sql *.json *.go:

  • all twelve camelCase Prisma field names → five files, and every hit in the four application files is meta.genesysConversationId (a JSON key) or the bot connector’s request field, never an assignment to a column;
  • the eleven names other than genesysConversationId → one file, packages/database/zod/responses.ts, the type declaration itself;
  • all twelve snake_case column names → two files, the migration that created them and scripts/superset/create-views.sql that reads them.

No route, service, or job assigns any of the twelve. The bot connector says so in a comment — apps/web/app/api/v1/management/bot-connector/turn/route.ts:515-518: the conversation id “lives in the response’s meta JSON … the genesysConversationId column is not written by this flow.” Confirmed against real rows too: the migration-era hivecfm database has 1498 Response rows and 0 with genesys_conversation_id or genesys_agent_id set.

Whether the API hands them to you depends on the API version, and that is a v1-vs-v2 difference rather than a bug. responseSelection in apps/web/app/api/v1/management/responses/lib/response.ts:24-43 — the field list every v1 management response read uses — omits all twelve, so a v1 read cannot return them at all. The v2 management list endpoint takes the opposite approach: prisma.response.findMany(query) at apps/web/modules/api/v2/management/responses/lib/response.ts:33 passes a query built by getResponsesQuery that sets only where, take, skip and orderBy — no select — so Prisma returns every scalar column and the twelve come back on the wire. That is why docs/api-v2-reference/openapi.yml:4612-4623 lists all twelve under required on the response schema and is not contradicted by the code. At this ref they arrive as null every time.

The claim is scoped to the ref on purpose. Unrestricted — no path filter, every file type — git grep -ln 'genesys_agent_id\|genesysAgentId' origin/development returns exactly seven files: schema.prisma, zod/responses.ts, the migration, scripts/superset/create-views.sql, docs/api-v2-reference/openapi.yml, and two under docs/technical/. Widening the pattern to all eleven names other than genesysConversationId, in both casings, returns the same seven files and no others. Not one code file, in any language, anywhere in the tree.

That still bounds the tree, not your database. Out-of-ref writers demonstrably touch these rows: 1497 of the 1498 carry meta.source = 'ist-old', a value git grep -ln 'ist-old' origin/development finds nowhere. So treat “nothing writes these columns” as ref-scoped, not universal — something outside hivecfm-core@origin/development has written to this table before, and it is the same class of thing that would fill the Genesys columns.

So the recipes in the first half of this page are correct SQL for a database whose Genesys columns somebody fills — an operator ETL, a Superset feed job, a manual backfill — and they return nothing on a HiveCFM instance running unmodified origin/development. The second half gives the equivalents that work today.

What the Genesys paths actually write

Three server-side code paths create a Response for a Genesys interaction. None of them touches a genesys_* column; all of them put the conversation id somewhere else.

IVR opens the row on the metadata GET, not on the first answer. .../ivr/[surveyId]/route.ts stores the Genesys conversationId in "Response"."singleUseId" (line 218) precisely so the later answer POST finds it: the comment at lines 155-159 says “Store conversationId as singleUseId so the answers POST (which looks up by singleUseId = callId) updates THIS session instead of creating a second row — the Architect flow must send callId = conversationId.” The POST then does findFirst({ where: { surveyId, singleUseId: callId } }) (responses/route.ts:203-205) and merges: { ...existingResponse.data, ...data } at line 220. One POST per answer, one row per call, keyed by singleUseId. The mechanism is drawn out in IVR Webhook Flow; the Genesys-side wiring is in Genesys IVR Setup.

There are two IVR creators with different markers. If the Architect flow skips the metadata GET, the answer POST creates the row itself (responses/route.ts:267-285) with meta.source = meta?.source || "ivr" and a synthetic meta.userAgent of { browser: "IVR", device: "phone", os: "telephony" }. The GET-created row has meta.source = "genesys_ivr" and no userAgent at all.

⚠️

Do not take meta.source = "ivr" as the IVR marker. IVR Webhook Flow documents the answer-POST handler and says that handler attaches meta.source = "ivr" on a create — correct for that handler, and that page claims nothing more. But it is the half that fires less often: the normal Architect flow fetches metadata first, so the row already exists, created by route.ts:221 with source = "genesys_ivr", and the POST takes the merge branch instead. An identifier query has to accept both marker sets. A third writer, apps/web/app/api/v1/management/surveys/[surveyId]/route.ts:172, also writes "genesys_ivr".

Row-level discriminators, and who sets them

MarkerValueSet byTrustworthy?
meta.sourcegenesys_ivrivr/[surveyId]/route.ts:221, management/surveys/[surveyId]/route.ts:172Yes — hard-coded server-side
meta.sourcegenesys_bot_connectorbot-connector/turn/route.ts:588Yes — hard-coded server-side
meta.sourceivrivr/.../responses/route.ts:277No — a fallback, so the request body can override it
meta.sourceanythingclient/[environmentId]/responses/route.ts:196No — copied straight from the browser payload
meta.sourcesms_campaignlib/campaign/send-campaign.ts:321Yes — hard-coded server-side
meta.userAgent.browserIVRivr/.../responses/route.ts:280-282Yes — hard-coded server-side
meta.userAgent.*real browser/device/OSclient/[environmentId]/responses/route.ts:198-202Yes — parsed from the request UA header
meta.genesysConversationIdGenesys conversation idivr/[surveyId]/route.ts:222, turn/route.ts:590Yes, when present
singleUseIdGenesys conversation idivr/[surveyId]/route.ts:218, responses/route.ts:273Yes, for the IVR path only

meta.source is a hint, never an authorization boundary — on the web client route and on the IVR answer POST the caller picks the value.

The three indexes, and the query shape they reward

Response_genesys_conversation_id_idx      btree (genesys_conversation_id)
Response_genesys_agent_id_created_at_idx  btree (genesys_agent_id, created_at)
Response_genesys_queue_id_created_at_idx  btree (genesys_queue_id, created_at)

Declared at packages/database/schema.prisma:262-264 with the intent written on the line — “for looking up responses by Genesys conversation”, “for agent performance reports”, “for queue performance reports” — and created in migration/20260114220000_add_genesys_context_fields/migration.sql:17-24. Verified present:

echo "select indexname, indexdef from pg_indexes where tablename='Response' order by indexname;" \
| docker exec -i hivecfm-postgres-t3060 psql -U postgres -d devhub_ref

Name the agent or the queue, or the composite index does nothing for you. Four plans from devhub_ref, all with enable_seqscan at its default:

PredicatePlanWhat the index gave you
genesys_agent_id = $1 AND created_at >= $2 AND created_at < $3Index Scan using Response_genesys_agent_id_created_at_idx, all three as Index CondBoth columns are scan boundaries — one contiguous range
genesys_agent_id IS NOT NULL AND created_at >= $1 AND created_at < $2Index Scan using Response_created_at_idx, Filter: (genesys_agent_id IS NOT NULL)Nothing. The composite is not chosen at all
created_at >= $1 AND created_at < $2Index Scan using Response_created_at_idxThe date range, from a different index
genesys_conversation_id = $1Index Scan using Response_genesys_conversation_id_idxA point lookup

Two corrections to the folklore fall out of that table.

  1. A created_at-only filter is not unindexed. Response_created_at_idx exists (schema.prisma:258) and the planner uses it. The problem with a date-only report is not the absence of an index, it is the absence of locality: Response_created_at_idx hands you every response in the window across every survey, every tenant, and every channel, and the agent grouping happens afterwards.
  2. IS NOT NULL on the leading column does not open the composite index. The whole-environment “report on all agents” shape falls back to the date index with genesys_agent_id as a row filter. If you want the composite index, pass an agent id — which means driving a per-agent report from a loop or an IN list of agents, not from one un-parameterised query.
# reproduce the two agent plans
cat <<'SQL' | docker exec -i hivecfm-postgres-t3060 psql -U postgres -d devhub_ref
EXPLAIN SELECT r.id FROM "Response" r
 WHERE r.genesys_agent_id = 'agent-1'
   AND r.created_at >= '2026-08-01' AND r.created_at < '2026-09-01';
EXPLAIN SELECT r.id FROM "Response" r
 WHERE r.genesys_agent_id IS NOT NULL
   AND r.created_at >= '2026-08-01' AND r.created_at < '2026-09-01';
SQL

What a clean plan on devhub_ref proves. The database has zero rows, so a plan proves the query parses, every column and cast resolves, and the predicate shape is eligible for the index the plan names. It does not prove the planner would choose that index at production row counts, and it says nothing about runtime. No number on this page is a benchmark.

Recipes

Recipes below use the psql variables :'environment_id' and :'survey_id', the same convention as the rest of this section — \set environment_id '<cuid>' once and the recipes paste unedited. The quoted form is required; bare :environment_id interpolates a raw token and Postgres reads it as a column name. environmentId is the practical tenant boundary; the predicate lives on "Survey" because "Response" has no environment column of its own.

1. Per-agent CSAT/NPS over a date range

The hard part is not the agent column, it is that Response.data is keyed by per-survey element cuids — there is no nps_score column. The resolution primitive and why it looks like that are in Responses & answers; here it is one CTE, and the tenant predicate lives inside it so the join to "Response" is already tenant-bounded.

WITH env_nps_element AS (
  SELECT s.id AS survey_id, e->>'id' AS element_id
  FROM "Survey" s,
       unnest(s.blocks) AS b,
       jsonb_array_elements(b->'elements') AS e
  WHERE s."environmentId" = :'environment_id'          -- tenant predicate
    AND e->>'type' = 'nps'
), scored AS (
  SELECT r.genesys_agent_id,
         r.genesys_agent_name,
         (r.data ->> n.element_id)::numeric AS score
  FROM "Response" r
  JOIN env_nps_element n ON n.survey_id = r."surveyId"
  WHERE r.genesys_agent_id IS NOT NULL
    AND r.created_at >= '2026-08-01' AND r.created_at < '2026-09-01'
    AND r.answered_questions_count > 0        -- exclude invitations
    AND jsonb_typeof(r.data -> n.element_id) = 'number'
)
SELECT genesys_agent_id,
       max(genesys_agent_name)                       AS agent_name,
       count(*)                                      AS scored_responses,
       round(avg(score), 2)                          AS avg_score,
       count(*) FILTER (WHERE score >= 9)            AS promoters,
       count(*) FILTER (WHERE score BETWEEN 7 AND 8) AS passives,
       count(*) FILTER (WHERE score <= 6)            AS detractors,
       round(100.0 * (count(*) FILTER (WHERE score >= 9)
                    - count(*) FILTER (WHERE score <= 6)) / count(*), 1) AS nps
FROM scored
GROUP BY genesys_agent_id
ORDER BY nps;

Three things earn their place. answered_questions_count > 0 is the invitation filter — a session with zero answered questions is an invitation, not a response, and counting it drags the denominator. jsonb_typeof(...) = 'number' stops the ::numeric cast from erroring on a survey where an element id collides with a string-valued hidden field. And max(genesys_agent_name) rather than grouping by the name: the name is a denormalised label that can change between calls while the id does not.

For CSAT swap e->>'type' = 'nps' for 'rating' and replace the promoter/detractor arithmetic with count(*) FILTER (WHERE score >= 4) over the scale you configured — rating scales are per-element, so verify the range in the element JSON before hard-coding a threshold.

This plans as a nested loop driven by Response_created_at_idx; naming a single agent instead of IS NOT NULL moves it onto Response_genesys_agent_id_created_at_idx.

2. Per-queue volume and average handle time

SELECT r.genesys_queue_id,
       max(r.genesys_queue_name)                    AS queue_name,
       count(*)                                     AS responses,
       count(*) FILTER (WHERE r.finished)           AS completed,
       count(r.genesys_handle_time)                 AS rows_with_handle_time,
       round(avg(r.genesys_handle_time), 1)         AS avg_handle_time_raw,
       percentile_cont(0.5) WITHIN GROUP (ORDER BY r.genesys_handle_time)
                                                    AS p50_handle_time_raw,
       round(avg(EXTRACT(epoch FROM (r.genesys_conversation_end
                                   - r.genesys_conversation_start))), 1)
                                                    AS avg_conversation_seconds
FROM "Response" r
JOIN "Survey" s ON s.id = r."surveyId"
WHERE s."environmentId" = :'environment_id'
  AND r.genesys_queue_id IS NOT NULL
  AND r.created_at >= '2026-08-01' AND r.created_at < '2026-09-01'
  AND r.answered_questions_count > 0
GROUP BY r.genesys_queue_id
ORDER BY responses DESC;

count(r.genesys_handle_time) is not decoration: count(<column>) skips NULLs, so putting it nextNext.jsReact framework used by HiveCFM Core. Handles routing, server rendering, and API routes in one bundle. to count(*) tells you what fraction of the group the average was computed over. An AHT built from three of four hundred rows is a number you should not publish.

⚠️

The unit of genesys_handle_time is declared, not observed. The column is INTEGER. Three places in the repo call it seconds — packages/database/zod/responses.ts:127-129 ("Total handle time in seconds"), the schema doc comment at packages/database/schema.prisma:182, and scripts/superset/create-views.sql:23, which aliases it handle_time_seconds. But there is no writer, so nothing in the repo has ever put a value in it, and no test asserts a unit. If your database has values in this column, whatever fills it decides the unit. Sanity-check against avg_conversation_seconds in the query above, which is derived from the two timestamps and therefore self-describing; if the two disagree by roughly 1000× you are looking at milliseconds. That is why the column above is named ..._raw.

Naming one queue moves this onto Response_genesys_queue_id_created_at_idx; the IS NOT NULL form above plans on Response_created_at_idx with a row filter, per the table in the previous section. It is an Index Scan with heap fetches, not an Index Only Scan — genesys_queue_name, finished, genesys_handle_time and the two timestamps are not in that index, so every matching row still costs a heap visit.

3. Inbound vs outbound — group, never filter

SELECT coalesce(r.genesys_direction, '(null)') AS direction_raw,
       count(*)                                AS responses,
       count(*) FILTER (WHERE r.finished)      AS completed
FROM "Response" r
JOIN "Survey" s ON s.id = r."surveyId"
WHERE s."environmentId" = :'environment_id'
  AND r.created_at >= '2026-08-01' AND r.created_at < '2026-09-01'
GROUP BY 1
ORDER BY responses DESC;

WHERE r.genesys_direction = 'inbound' is a guess, and this is the one recipe where guessing is expensive: a wrong literal returns zero rows silently and looks like “we had no inbound calls”.

The column is TEXT. Its only description in the repo is packages/database/zod/responses.ts:133-135, "Call direction (inbound/outbound)" — a prose description on a zod schema, not a constraint and not an enum. git grep finds no comparison against any direction literal anywhere at origin/development; the Superset view only passes the raw value through as call_direction (scripts/superset/create-views.sql:20). With no writer and no comparison, the value set is entirely defined by whatever fills the column, and HiveCFM neither constrains nor normalises it. For Genesys Cloud’s own naming, look the conversation resource up in the Genesys Cloud API Explorer rather than trusting a literal repeated in a HiveCFM doc — and then check what your writer actually stored, because the two can differ in case, in field choice, and in whether the value is a direction at all.

So: run the GROUP BY first, read the actual value set out of your database, then and only then write a WHERE or a CASE. If you must classify in one pass, fold case and match loosely — lower(trim(r.genesys_direction)) LIKE 'in%' — and keep a bucket for everything else.

4. Wrap-up code distribution

SELECT r.genesys_wrap_code,
       count(*)                                             AS responses,
       count(*) FILTER (WHERE r.is_negative_response)        AS negative,
       round(100.0 * count(*) FILTER (WHERE r.is_negative_response)
             / count(*), 1)                                  AS pct_negative
FROM "Response" r
JOIN "Survey" s ON s.id = r."surveyId"
WHERE s."environmentId" = :'environment_id'
  AND r.genesys_wrap_code IS NOT NULL
  AND r.created_at >= '2026-08-01' AND r.created_at < '2026-09-01'
  AND r.answered_questions_count > 0
GROUP BY r.genesys_wrap_code
ORDER BY responses DESC;

is_negative_response is genuinely populated by HiveCFM, unlike everything else on the left of this query. It is computed on create in both response modules — apps/web/app/api/v1/client/[environmentId]/responses/lib/response.ts:109 (persisted at :135) and apps/web/app/api/v1/management/responses/lib/response.ts:121 (persisted at :147) — and recomputed on update in apps/web/lib/response/service.ts:582-586 (persisted at :610). IVR and bot rows are covered because every one of those paths goes through one of these two modules: the IVR call-start GET and the bot connector import createResponseWithQuotaEvaluation from the management module, the IVR answer POST from the client module. The schema comment at packages/database/schema.prisma:239 gives the rule: “true when the response matches one of the survey’s negative-answer rules”. So this is the one Genesys-column recipe with a real HiveCFM measure on the other axis. It answers “which wrap-up codes correlate with an unhappy customer”, which is the question wrap codes are usually pulled for.

⚠️

is_negative_response is only ever evaluated on a finished row. All three sites are gated the same way — finished && survey ? evaluateIsNegativeResponse(...) : false on create, and on update the current value is carried forward unchanged unless the incoming write sets finished. An unfinished row therefore reads false because nobody looked, not because the answers were positive. The query above does not filter finished, so its pct_negative is diluted by every abandoned call in the group. Add AND r.finished to both the numerator and the population, or report count(*) FILTER (WHERE r.finished) alongside it, before you put a percentage in front of anyone.

Wrap codes are Genesys ids or names depending on what the ETL wrote; there is no lookup table in HiveCFM to resolve them. Expect raw ids, and join them to your Genesys configuration outside the database.

5. Find the survey response for a known conversation

The indexed form:

SELECT r.id, r.created_at, r.finished, r.answered_questions_count,
       r.genesys_agent_name, r.genesys_queue_name, r.data
FROM "Response" r
JOIN "Survey" s ON s.id = r."surveyId"
WHERE s."environmentId" = :'environment_id'
  AND r.genesys_conversation_id = '00000000-0000-0000-0000-000000000000';

Response_genesys_conversation_id_idx serves this as a point lookup — verified: Index Scan using "Response_genesys_conversation_id_idx", Index Cond: (genesys_conversation_id = '00000000-0000-0000-0000-000000000000'::text). It is the reason that index exists, and on a stock instance it returns nothing.

The form that works today, because it reads where the IVR and bot paths actually write:

SELECT r.id, r.created_at, r.finished, r.answered_questions_count, r.meta
FROM "Response" r
JOIN "Survey" s ON s.id = r."surveyId"
WHERE s."environmentId" = :'environment_id'
  AND (
        r."singleUseId" = '00000000-0000-0000-0000-000000000000'
     OR r.meta ->> 'genesysConversationId' = '00000000-0000-0000-0000-000000000000'
  );
⚠️

The indexed column is the one nothing writes, and the written location is never a scan boundary. r.meta ->> 'genesysConversationId' = $1 cannot restrict a scan: there is no index on that expression and no GIN index on meta at origin/development. On its own — SELECT r.id FROM "Response" r WHERE r.meta ->> 'genesysConversationId' = 'c-1' — it plans as a Seq Scan on "Response", and stays one even with SET enable_seqscan = off, because there is nothing to fall back to.

In the tenant-joined form published above it does not seq-scan, and that is worse than it looks: the plan is a nested loop that drives Index Scan using "Response_surveyId_singleUseId_key" off each matching "Survey" row with Index Cond: ("surveyId" = s.id), and the whole OR — both the singleUseId test and the JSON path — lands in Filter:. Every response row of every survey in the environment is still visited. The join bought you tenant scoping, not selectivity.

singleUseId is better but not indexed the way you would hope. The only index containing it is Response_surveyId_singleUseId_key, a unique btree on ("surveyId", "singleUseId"). With singleUseId alone the planner still names that index and still prints Index Cond, but with no value for the leading column it has to walk the whole index rather than descend to a range. Pass the survey id too and it becomes a real point lookup — both columns in Index Cond:

WHERE s."environmentId" = :'environment_id'
  AND r."surveyId"    = :'survey_id'
  AND r."singleUseId" = '00000000-0000-0000-0000-000000000000'

If conversation-id lookup is a hot path in your deployment, the cheap fix is a functional index — CREATE INDEX ON "Response" ((meta ->> 'genesysConversationId')) — not a rewrite. Raise it as a schema change; do not add it to production by hand.

6. Partially completed IVR calls

A caller who answered two of five questions and hung up leaves a row with finished = false and answered_questions_count > 0. That is the abandonment report.

SELECT r.id,
       r."singleUseId"                                  AS conversation_id,
       r.created_at,
       r.updated_at,
       r.answered_questions_count,
       (SELECT count(*) FROM jsonb_object_keys(r.data)) AS data_keys,
       r.language,
       r.meta ->> 'source'                              AS meta_source,
       r.expiry_source
FROM "Response" r
JOIN "Survey" s ON s.id = r."surveyId"
WHERE s."environmentId" = :'environment_id'
  AND r.finished = false
  AND r.answered_questions_count > 0
  AND (r.meta ->> 'source' IN ('genesys_ivr', 'ivr')
       OR r.meta -> 'userAgent' ->> 'browser' = 'IVR')
  AND r.created_at >= '2026-08-01' AND r.created_at < '2026-09-01'
ORDER BY r.created_at DESC;

answered_questions_count and data_keys are deliberately both selected. data also holds hidden fields threaded in from the Architect flow — conversationId, agentId, channel — so data_keys is never the smaller number: countAnsweredQuestions is literally Object.keys(data).filter((key) => elementIds.has(key)).length (apps/web/lib/response/utils.ts:64), a subset of the key set, so at write time the gap between the two columns is exactly the non-element key count — the hidden fields, zero if the flow threaded none. One caveat keeps this a comparison rather than an invariant: answered_questions_count is a stored column, computed against the survey’s element ids as they stood on the last write and never recomputed afterwards. Edit the survey’s blocks and old rows keep their old count while jsonb_object_keys(r.data) still reflects the data, so a widened or inverted gap on historical rows means the survey changed under them, not that a caller did something strange. The invitation-vs-response rule is codified in the same file as ANSWERED_RESPONSE_WHERE and INVITATION_WHERE (utils.ts:37-42), and the schema comment at packages/database/schema.prisma:242-246 states it in prose. updated_at is when the last answer landed, so updated_at - created_at is how long the caller stayed.

expiry_source tells you whether a stalled row was killed by the survey-expiration window (invitation) or the session timeout (session) rather than by the caller hanging up — the IVR metadata route answers an aged session with HTTP 410 and details.code = "SURVEY_SESSION_EXPIRED" (ivr/[surveyId]/route.ts:187-204, via goneResponse at apps/web/app/lib/api/response.ts:34-56), so an expired row is not an abandonment.

Identifying IVR responses at all. The OR in that query is the whole answer, and it is uglier than it should be:

  • meta.source IN ('genesys_ivr', 'ivr') covers both creators (route.ts:221 and responses/route.ts:277).
  • meta.userAgent.browser = 'IVR' is the server-derived marker on rows the answer POST created, and the only one the caller cannot set.
  • Survey.type = 'voice' is not a reliable filter. Neither IVR route inspects survey.type. git grep '"voice"' across apps/web/app/api/v1/client/[environmentId]/ivr/ returns exactly one hit, lib/ivr.ts:350, and that reads channels.config.type — a jsonb key inside the channel config, used to pick voice prompt settings, not to gate the endpoint. Any survey type can be driven over IVR. Add s.type = 'voice' if it matches your deployment’s discipline, but it is a convention, not an invariant.
  • survey_delivery_channel is not a channel taxonomy. See the next recipe.

7. Bot vs IVR vs web from the row alone

SELECT CASE
         WHEN r.meta ->> 'source' = 'genesys_bot_connector'  THEN 'bot connector'
         WHEN r.meta -> 'userAgent' ->> 'browser' = 'IVR'     THEN 'ivr (answer POST)'
         WHEN r.meta ->> 'source' = 'genesys_ivr'             THEN 'ivr (call-start GET)'
         WHEN r.meta ->> 'source' = 'ivr'                     THEN 'ivr (source only)'
         WHEN r.meta ->> 'source' = 'sms_campaign'            THEN 'sms campaign'
         WHEN r.survey_delivery_channel IS NOT NULL
              THEN 'delivered as ' || lower(r.survey_delivery_channel)
         WHEN r.meta -> 'userAgent' ->> 'browser' IS NOT NULL THEN 'browser session'
         ELSE 'unattributed'
       END                                                    AS row_level_channel,
       s.type                                                 AS survey_type,
       ch.type                                                AS channel_type,
       count(*)                                               AS response_count,
       count(*) FILTER (WHERE r.answered_questions_count = 0)  AS invitations
FROM "Response" r
JOIN "Survey"  s  ON s.id = r."surveyId"
LEFT JOIN channels ch ON ch.id = s.channel_id
WHERE s."environmentId" = :'environment_id'
  AND r.created_at >= '2026-08-01' AND r.created_at < '2026-09-01'
GROUP BY 1, 2, 3
ORDER BY response_count DESC;

Clause order matters and is not arbitrary. The bot marker is hard-coded server-side, so it goes first. The userAgent.browser = 'IVR' test comes before the source tests because the answer POST lets the request override meta.source (meta?.source || "ivr") while it cannot override the synthetic user agent. survey_delivery_channel comes near the bottom because of what the nextNext.jsReact framework used by HiveCFM Core. Handles routing, server rendering, and API routes in one bundle. callout says. Note channels.environment_id is snake_case while "Survey"."environmentId" is camelCase — and the tenant predicate belongs on "Survey", not on channels, which has no RLS at all.

🚫

Bot, IVR and browser rows separate cleanly. Web, mobile and link rows do not — they are genuinely indistinguishable from one another on a Response row. All three go through the same POST /api/v1/client/[environmentId]/responses handler, which builds meta from the request (route.ts:195-205): source copied from the client payload, url, a parsed userAgent, country. Nothing on the row records which SDK sent it. The channel identity lives on the survey — "Survey".type (link | app | voice) and "Survey".channel_id → channels.type (web | mobile | link | voice | whatsapp | sms | email) — which is why the query above selects both and why the app’s own classifier, resolveResponseLabel in apps/web/app/api/v1/management/license-reports/lib/channel-groups.ts:73-79, has exactly this precedence: per-response delivery channel, then the survey’s channel, then the survey’s legacy type. If you need per-response web/mobile/link attribution, the row cannot give it to you and no join will invent it.

⚠️

Do not classify on survey_delivery_channel. The app’s own comment calls it “a free-form string” (channel-groups.ts:47-48), and the alias table at channel-groups.ts:49-62 maps twelve known spellings to a label and returns NULL for everything else. On the real migration-era hivecfm database the column holds 67 distinct values and 0 of 1498 rows match any alias:

echo "SELECT count(DISTINCT r.survey_delivery_channel) AS distinct_values,
             count(*) FILTER (WHERE lower(trim(r.survey_delivery_channel)) IN
               ('web','app','mobile','chat','webchat','voice','ivr','call','link','whatsapp','sms','email')) AS alias_matched,
             count(*) AS total
        FROM \"Response\" r JOIN \"Survey\" s ON s.id = r.\"surveyId\"
        WHERE s.\"environmentId\" = 'cmr0o5ivu000clc01glv55m4p';" \
| docker exec -i hivecfm-postgres-t3060 psql -U postgres -d hivecfm

67 | 0 | 1498. The values are legacy channel names, in whatever case someone typed — the five most common are General (401 rows), MobileSDKReact (138), CC Email (98), TRY (63), Email001 (56), and the tail runs to My Kiosk, Test20, Retest-02. Case is not what defeats the aliases: deliveryChannelToLabel lowercases and trims before it looks up (channel-groups.ts:66), so General is tested as general and still misses, because general is not one of the twelve keys. That is a migrated database, not one written by origin/development code, and the writers that exist (lib/response/service.ts:886, fed from parameters.channel on the survey-link route at management/survey/survey-link/route.ts:137) pass a caller-supplied string straight through, so free-form is the design and not a migration artefact. Read it as a label; never GROUP BY it and call the result a channel breakdown.

The classifier above was run against real rows on the hivecfm database and returned 71 groups, so the CASE shape holds on real data. Three things had to come out of it first, and none of them are optional if you want to reproduce that number: the channels join and the invitations column, neither of which exists in that older schema, and the created_at range — hivecfm rows stop at 2026-06-30, so the published window matches nothing there. The 71 is a whole-table figure, not a monthly one.

8. Data-quality check: a conversation id with no agent and no queue

SELECT date_trunc('day', r.created_at)                            AS day,
       count(*)                                                   AS with_conversation_id,
       count(*) FILTER (WHERE r.genesys_agent_id IS NULL)          AS missing_agent,
       count(*) FILTER (WHERE r.genesys_queue_id IS NULL)          AS missing_queue,
       count(*) FILTER (WHERE r.genesys_conversation_start IS NULL) AS missing_start
FROM "Response" r
JOIN "Survey" s ON s.id = r."surveyId"
WHERE s."environmentId" = :'environment_id'
  AND r.genesys_conversation_id IS NOT NULL
  AND r.created_at >= '2026-08-01' AND r.created_at < '2026-09-01'
GROUP BY 1
ORDER BY 1;

At origin/development this returns zero rows by construction: nothing writes genesys_conversation_id, so the IS NOT NULL predicate matches nothing and there is no population left to find gaps in. That is the point of running it: a non-empty result tells you an out-of-repo writer exists, and the gaps tell you where its join coverage breaks.

Read the columns as a diagnosis of the ETL, not of a HiveCFM flow:

  • missing_agent high, missing_queue low — the enrichment resolved the conversation to a queue but not to a participant. Typical of a conversation that was abandoned in queue, or of an ETL reading the conversation summary without walking participants[].
  • both high — the conversation id landed but no identity did. The conversation id is the one value a Genesys Architect flow already holds at survey time (it is threaded through as a hidden field on both HiveCFM paths), while agent and queue have to be fetched back from Genesys afterwards. A writer that stamps the id inline and enriches identity in a second, later step will produce exactly this shape whenever the second step is behind, failing, or never ran. Check the timing of your enrichment job against created_at before concluding anything about the calls themselves.
  • missing_start high while agent and queue are populated — two writers, one filling identity and another filling timings, and the second one is failing. The self-describing check is genesys_conversation_end - genesys_conversation_start, so a NULL start also silently voids avg_conversation_seconds in recipe 2.

The one in-repo consumer of these columns has a defect worth knowing about. scripts/superset/create-views.sql defines v_agent_performance over "Response" filtered to genesys_agent_id IS NOT NULL (line 33), then attaches the tenant id with LEFT JOIN "Organization" o ON o.name = v.organization_name (line 34) — a join on the organization name, not the foreign key. The file defines 15 views and all 15 attach the tenant id the same way (grep -c 'o.name = v.organization_name' returns 15, grep -c 'CREATE OR REPLACE VIEW' returns 15). Two organizations with the same name fan every row out into duplicates, and a renamed organization drops out entirely. Do not build on v_agent_performance."organizationId"; that is also why every recipe on this page carries its own "Survey"."environmentId" predicate rather than leaning on a view.

Where to look in the code

  • hivecfm-core/packages/database/schema.prisma:191-265 — the Response model: the twelve genesys_* columns at 222-233, the delivery pair at 236-237, the three Genesys indexes at 262-264.
  • hivecfm-core/packages/database/migration/20260114220000_add_genesys_context_fields/migration.sql — the one migration that added all fourteen columns and the three indexes.
  • hivecfm-core/packages/database/zod/responses.ts:112-154 — the columns’ intended semantics as OpenAPI descriptions, including the “in seconds” claim for genesys_handle_time and the “inbound/outbound” claim for genesys_direction. The same sentences appear as Prisma doc comments at schema.prisma:177-190; those two blocks are the whole of the written intent.
  • hivecfm-core/apps/web/app/api/v1/client/[environmentId]/ivr/[surveyId]/route.ts:155-256 (275 lines) — the IVR call-start route: singleUseId = conversationId, meta.source = "genesys_ivr", session reuse and the 410 expiry path.
  • hivecfm-core/apps/web/app/api/v1/client/[environmentId]/ivr/[surveyId]/responses/route.ts:200-290 — the per-answer POST: lookup by (surveyId, singleUseId), the { ...existing, ...new } merge, meta.source = meta?.source || "ivr", and the synthetic IVR user agent.
  • hivecfm-core/apps/web/app/api/v1/client/[environmentId]/ivr/[surveyId]/lib/ivr.ts:347-359 — linearizeSurveyForIvr reading voice settings from channels.config.type, the only "voice" comparison in the IVR tree.
  • hivecfm-core/apps/web/app/api/v1/management/bot-connector/turn/route.ts:513-592 — the comment that states the genesysConversationId column is not written by that flow, and the meta.source = "genesys_bot_connector" create.
  • hivecfm-core/apps/web/app/api/v1/client/[environmentId]/responses/route.ts:195-205 — the shared web/mobile/link handler, and the client-supplied meta.source.
  • hivecfm-core/apps/web/lib/response/utils.ts:37-65 — ANSWERED_RESPONSE_WHERE / INVITATION_WHERE and countAnsweredQuestions, the definition behind every answered_questions_count predicate on this page.
  • hivecfm-core/apps/web/app/api/v1/management/responses/lib/response.ts:24-43 — responseSelection: the v1 management read field list, which omits all twelve Genesys columns; :121/:147 for the isNegativeResponse computation, and :109/:135 in the client-side sibling.
  • hivecfm-core/apps/web/modules/api/v2/management/responses/lib/response.ts:33 and lib/utils.ts — the v2 list endpoint’s findMany with no select, which is why v2 does return the twelve.
  • hivecfm-core/docs/api-v2-reference/openapi.yml:4612-4623 — the same twelve listed under required on the v2 response schema, which the v2 code honours.
  • hivecfm-core/apps/web/app/api/v1/management/license-reports/lib/channel-groups.ts:47-79 — DELIVERY_CHANNEL_ALIASES and resolveResponseLabel, the app’s own channel-attribution precedence.
  • hivecfm-core/apps/web/lib/response/service.ts:834-960 — the only writers of survey_delivery_channel and survey_delivered_at.
  • hivecfm-core/scripts/superset/create-views.sql — the only file in the repo that reads the Genesys columns by name: 46 of its 1003 lines mention one, spread across six of its fifteen views (v_agent_performance, v_csat_nps_responses, v_daily_summary, v_kpi_dashboard, v_raw_data_survey_report, v_raw_data_survey_report_agg). v_agent_performance is lines 1-34, including the o.name = v.organization_name defect at line 34.
  • Responses & answers — the element-id resolution primitive recipe 1 leans on, and the invitation-vs-response rule.
  • Channels & campaigns — the channels table, ChannelType, and why channel identity is a survey property.
  • IVR Webhook Flow — the per-answer merge mechanism end to end.
  • Genesys IVR Setup — the Genesys-side Architect flow and Data Action configuration, including the callId = conversationId requirement recipe 5 depends on.
  • Genesys Bot Connector — the chat-channel surface, its session store, and its intents.

HiveCFM Developer Hub — internal team guide