Call History
Query, filter, inspect, and export call history with the React SDK.
The call-history hooks load paginated calls, fetch an individual call, and resolve short-lived recording URLs. For the prebuilt searchable list and detail UI, see Components.
List calls
Import
import { useCallHistory } from "@scalereal/sr-voice-engine-react-sdk/hooks";Usage
useCallHistory returns a TanStack Query result whose data is a paginated response. It refetches when the project or filter parameters change.
import { useCallHistory } from "@scalereal/sr-voice-engine-react-sdk/hooks";
export function RecentCalls() {
const { data, isPending, isError } = useCallHistory({
page: 1,
size: 20,
sort_by: "-connected_at",
});
if (isPending) return <p>Loading calls…</p>;
if (isError) return <p>Could not load calls.</p>;
return (
<section>
<p>{data.total} calls</p>
<ul>
{data.items.map((call) => (
<li key={call.id}>
{call.from_number ?? "Unknown caller"} — {call.current_status}
</li>
))}
</ul>
<p>
Page {data.page} of {data.pages}
</p>
</section>
);
}The response includes items, total, page, size, and pages. Each item is a CallHistory object.
Parameters
useCallHistory(params?: ListCallHistoryParams) accepts these optional filters:
| Parameter | Description |
|---|---|
page | 1-based page number. |
size | Number of calls per page. |
search | Text search across call numbers and summary. |
current_status | Filter by initiated, ringing, in_progress, completed, failed, missed, or ongoing. |
direction | inbound or outbound. |
provider | Telephony provider name. |
call_type | Call type, such as a campaign call or manual call. |
start_date | Include calls connected on or after yyyy-MM-dd. |
end_date | Include calls connected on or before yyyy-MM-dd. |
agent_id | Restrict results to an agent. |
agent_family | Include every version of the selected agent's family. |
batch_id | Restrict results to a batch. |
campaign_id | Restrict results to a campaign. |
sort_by | Sort by created_at, connected_at, ended_at, or call_durations; prefix the field with - for descending order. |
custom_attributes | Array of CustomAttributeFilter conditions on the call's custom_attributes JSON column, combined with AND. |
Empty values are removed before the request. The default page, size, and sort behavior is determined by the service unless you provide values.
Filter by custom attributes
Calls can store arbitrary JSON metadata in their custom_attributes column (for example, customer tier, CRM record IDs, or cart contents). The call-sessions endpoint supports deep filtering on this column.
When sent to the API, each filter becomes a flat query parameter:
- Dotted paths become
custom_attributes.<path>__<op>=<value>(e.g.custom_attributes.plan__eq=pro). - Root column filters become
custom_attributes__<op>=<value>(e.g.custom_attributes__isnull=false).
Path segments support nested keys (user.address.city), numeric array indexes (orders.0.sku), and * wildcards matching any array element (tags.*).
The SDK provides two ways to build these filters: the attr helper object and the chainable customAttributeQuery() builder.
Using the attr helper
The attr object provides typed helper functions for every supported operator:
import { attr } from "@scalereal/sr-voice-engine-react-sdk";
import { useCallHistory } from "@scalereal/sr-voice-engine-react-sdk/hooks";
export function HighValueCalls() {
const { data, isPending, isError } = useCallHistory({
page: 1,
size: 20,
custom_attributes: [
attr.eq("plan", "enterprise"),
attr.gte("customer.lifetime_value", 5000),
attr.contains("tags", ["vip", "priority"]),
attr.rootIsNull(false),
],
});
if (isPending) return <p>Loading enterprise calls…</p>;
if (isError) return <p>Failed to load calls.</p>;
return (
<ul>
{data.items.map((call) => (
<li key={call.id}>
{call.from_number} — Plan: {String(call.custom_attributes?.plan ?? "none")}
</li>
))}
</ul>
);
}Using customAttributeQuery() builder
When constructing filters dynamically or passing them across functions, use customAttributeQuery():
import { customAttributeQuery } from "@scalereal/sr-voice-engine-react-sdk";
import { useCallHistory } from "@scalereal/sr-voice-engine-react-sdk/hooks";
export function FilteredCallsView({ minScore }: { minScore: number }) {
const query = customAttributeQuery()
.eq("verified", true)
.gte("qualification_score", minScore)
.like("account.region", "US")
.rootExists(true);
const { data } = useCallHistory({
page: 1,
size: 20,
custom_attributes: query.toFilters(),
});
return <p>{data?.total ?? 0} qualified calls</p>;
}Supported operators
All operators are type-checked against their operand value:
| Operator | Helper | Matches | Operand type |
|---|---|---|---|
eq | attr.eq(path, value) | Exact match; arrays match when containing the value | string | number | boolean |
neq | attr.neq(path, value) | Value differs; never matches missing keys or null | string | number | boolean |
gt | attr.gt(path, value) | Greater than (numeric or ISO date comparison) | number | string | Date |
lt | attr.lt(path, value) | Less than (numeric or ISO date comparison) | number | string | Date |
gte | attr.gte(path, value) | Greater than or equal to | number | string | Date |
lte | attr.lte(path, value) | Less than or equal to | number | string | Date |
btw | attr.btw(path, min, max) | Inclusive range [min, max] | [Comparable, Comparable] |
nbtw | attr.nbtw(path, min, max) | Outside inclusive range | [Comparable, Comparable] |
like | attr.like(path, text) | Substring, case-sensitive | string |
ilike | attr.ilike(path, text) | Substring, case-insensitive | string |
nlike | attr.nlike(path, text) | Does not contain substring, case-sensitive | string |
nilike | attr.nilike(path, text) | Does not contain substring, case-insensitive | string |
startswith | attr.startswith(path, prefix) | Prefix match | string |
endswith | attr.endswith(path, suffix) | Suffix match | string |
in | attr.in(path, values) | Value (or any array element) is in the list | (string | number)[] |
nin | attr.nin(path, values) | Value is not in the list | (string | number)[] |
contains | attr.contains(path, values) | Array contains every listed value | (string | number)[] |
exists | attr.exists(path, bool?) | Key is present (true, default) or absent (false) | boolean |
isnull | attr.isnull(path, bool?) | Value is JSON null (true, default) or not null (false) | boolean |
len | attr.len(path, length) | Array length equals value | number |
len_gt | attr.len_gt(path, length) | Array length greater than value | number |
len_gte | attr.len_gte(path, length) | Array length greater than or equal to | number |
len_lt | attr.len_lt(path, length) | Array length less than value | number |
len_lte | attr.len_lte(path, length) | Array length less than or equal to | number |
Root isnull | attr.rootIsNull(bool?) | Whole custom_attributes column is NULL | boolean |
Root exists | attr.rootExists(bool?) | Whole custom_attributes column has attributes | boolean |
Fetch call details
Import
import { useCallDetails } from "@scalereal/sr-voice-engine-react-sdk/hooks";Usage
import { useCallDetails } from "@scalereal/sr-voice-engine-react-sdk/hooks";
export function CallSummary({ callSessionId }: { callSessionId: string }) {
const { data, isPending, isError } = useCallDetails(callSessionId);
if (isPending) return <p>Loading call…</p>;
if (isError) return <p>Could not load this call.</p>;
if (!data) return null;
return (
<article>
<h2>{data.agent_name}</h2>
<p>{data.summary ?? "No summary available."}</p>
<p>Status: {data.current_status}</p>
</article>
);
}Parameters
callSessionId
callSessionId: stringCall session identifier. An empty or whitespace-only ID keeps the query disabled.
enabled
enabled: boolean | undefinedSet to false to pause fetching while retaining cached data. It defaults to true; fetching also requires a non-empty callSessionId.
The result data is a CallDetailsResponse, including call metadata, transcript, recording fields, summary, structured output, custom_attributes (arbitrary JSON set during the call or by the agent), and post-call processing state when available.
Read custom attributes on a call
Use getCustomAttribute to safely traverse nested properties in custom_attributes using dotted paths without manual null checks:
import { getCustomAttribute } from "@scalereal/sr-voice-engine-react-sdk";
import { useCallDetails } from "@scalereal/sr-voice-engine-react-sdk/hooks";
export function CallMetadata({ callSessionId }: { callSessionId: string }) {
const { data } = useCallDetails(callSessionId);
if (!data) return null;
const userCity = getCustomAttribute(data.custom_attributes, "user.address.city");
const accountTier = getCustomAttribute(data.custom_attributes, "account.tier");
return (
<div>
<p>City: {String(userCity ?? "Unknown")}</p>
<p>Tier: {String(accountTier ?? "Standard")}</p>
</div>
);
}Resolve a recording URL
Import
import { useCallRecordingUrl } from "@scalereal/sr-voice-engine-react-sdk/hooks";Usage
Call mutate or mutateAsync with a session ID and an action. The response contains a short-lived audio_url.
import { useState } from "react";
import { useCallRecordingUrl } from "@scalereal/sr-voice-engine-react-sdk/hooks";
export function RecordingLink({ callSessionId }: { callSessionId: string }) {
const recording = useCallRecordingUrl();
const [audioUrl, setAudioUrl] = useState<string | null>(null);
async function openRecording() {
const result = await recording.mutateAsync({
callSessionId,
action: "play",
});
setAudioUrl(result.audio_url);
}
return (
<div>
<button type="button" onClick={openRecording} disabled={recording.isPending}>
{recording.isPending ? "Preparing recording…" : "Prepare recording"}
</button>
{audioUrl && <audio controls src={audioUrl} />}
</div>
);
}action is either play or download. Request a fresh URL when needed; do not persist it as a permanent recording link.
Parameters
callSessionId
callSessionId: stringCall session whose recording URL to resolve.
action
action: "play" | "download"Choose a playback or download URL. The mutation resolves to CallRecordingUrlResponse (call_session_id and audio_url).
Manage list filters
useCallHistoryFilters holds common search, status, direction, date, paging, and sorting state and projects it into ListCallHistoryParams. Pair its params with useCallHistory:
import {
useCallHistory,
useCallHistoryFilters,
} from "@scalereal/sr-voice-engine-react-sdk/hooks";
export function FilteredCalls() {
const filters = useCallHistoryFilters({ debounceMs: 300 });
const calls = useCallHistory(filters.params);
return (
<section>
<label>
Search calls
<input
value={filters.searchInput}
onChange={(event) => filters.setSearchInput(event.target.value)}
/>
</label>
{calls.isPending ? <p>Loading calls…</p> : <p>{calls.data?.total ?? 0} calls</p>}
</section>
);
}Search is trimmed and debounced (300 ms by default). Changing status, direction, dates, page size, or sort resets the page to 1. initialParams can seed the search, status, dates, page, size, custom-attribute conditions (custom_attributes), and agent, batch, or campaign scope.
useCallHistoryFilters return values
| Value | Purpose |
|---|---|
searchInput, setSearchInput | Raw search field value and setter. |
search | Trimmed, debounced search term. |
status, setStatus | Status filter; "" means all statuses. |
direction, setDirection | Direction filter; "" means both directions. |
startDate, setStartDate | Inclusive start date in yyyy-MM-dd format. |
endDate, setEndDate | Inclusive end date in yyyy-MM-dd format. |
page, setPage | Current 1-based page and setter. |
size, setSize | Page size and setter. |
sortField, sortDirection | Current sort field and asc/desc direction. |
handleSort(field) | Toggle direction for the selected field; a new field starts descending. |
params | Current filters projected to ListCallHistoryParams. |
The hook accepts initialParams and debounceMs (default 300 ms).
Export calls
useCallExport provides browser-side CSV and PDF export handlers. By default, CSV exports the rows passed in calls, and PDF exports the call passed in. You can provide onExportCSV or onExportPDF to replace either exporter.
import { useCallExport } from "@scalereal/sr-voice-engine-react-sdk/hooks";
import type { CallHistory } from "@scalereal/sr-voice-engine-react-sdk/types";
export function ExportCurrentPage({ calls }: { calls: CallHistory[] }) {
const { exportCsv, exportingCsv } = useCallExport({ calls });
return (
<button type="button" onClick={exportCsv} disabled={exportingCsv || calls.length === 0}>
{exportingCsv ? "Exporting…" : "Export CSV"}
</button>
);
}Parameters
calls
calls: CallHistory[] | undefinedRows to include in the default CSV export. The SDK exports the rows passed here, which are typically the current filtered page. An empty array makes exportCsv a no-op.
call
call: CallHistory | CallDetailsResponse | null | undefinedCall to include in the default PDF report. When omitted or null, exportPdf is a no-op.
onExportCSV
onExportCSV: ((calls: CallHistory[]) => void | Promise<void>) | undefinedReplace the default CSV generation and browser download with a custom exporter.
onExportPDF
onExportPDF: ((call: CallHistory | CallDetailsResponse) => void | Promise<void>) | undefinedReplace the default PDF generation and browser download with a custom exporter.
onError
onError: ((message: string) => void) | undefinedReceive a human-readable message if CSV or PDF export fails. The default error messages are Failed to export CSV. and Failed to generate PDF.
useCallExport returns exportCsv, exportPdf, exportingCsv, and exportingPdf. Both default exporters run in the browser.
Cache keys
callSessionKeys is the query-key factory for call-history and detail queries. Use its all key to target all SDK call-session data when invalidating your shared QueryClient:
import { useQueryClient } from "@tanstack/react-query";
import { callSessionKeys } from "@scalereal/sr-voice-engine-react-sdk/hooks";
function useRefreshCallHistory() {
const queryClient = useQueryClient();
return () => queryClient.invalidateQueries({ queryKey: callSessionKeys.all });
}Related pages
- Provider & Setup Configure the required provider and query client.
- Components Use the managed call list, details panel, and audio player.
- Realtime Subscribe to transcript and post-call updates.
- Types Browse the call-history models and shared types.