import { useMemo, useState } from 'react' import { AlertCircle, ArrowRight, Check, CheckCircle2, ClipboardCheck, CloudUpload, Database, FileCheck2, FileSpreadsheet, History, Info, LockKeyhole, RefreshCw, ShieldCheck, Sparkles, Upload, XCircle, } from 'lucide-react' import { ApiError, useApi } from '../../api/ApiProvider' import { canImportData, canReviewData } from '../../api/permissions' import { useApiQuery } from '../../api/useApiQuery' import { useWorkspace } from '../../api/WorkspaceContext' import './data-manager.css' type ImportKind = 'liability_inforce' | 'assumption_table' | 'factor_table' | 'scenario' type DatasetKind = 'inforce' | 'assumption' | 'factor' | 'scenario' type MappingField = { source_column: string; target_field: string } type MappingProfile = { id: string; name: string; category: ImportKind; fields: MappingField[] } type DatasetRef = { id: string; kind: DatasetKind } type Dataset = { id: string kind: DatasetKind status: string name: string version_label?: string | null version_number?: number committed_by?: string | null approved_by?: string | null rejected_by?: string | null review_reason?: string | null row_count?: number committed_at?: string | null } type VersionResponse = Dataset[] | { versions?: Dataset[]; datasets?: Dataset[]; items?: Dataset[] } type ImportSession = { id: string project_id?: string kind?: ImportKind category?: ImportKind name?: string version_label?: string | null options?: Record status?: string file_name?: string original_filename?: string | null dataset_id?: string | null dataset_kind?: DatasetKind | null datasets?: DatasetRef[] dataset_ids?: string[] mapping_fields?: MappingField[] mapping_profile_id?: string | null validation_run_id?: string | null created_at?: string updated_at?: string record_count?: number error_count?: number warning_count?: number } type PreviewColumn = { name: string source?: string target?: string required?: boolean sample_values?: unknown[] } type PreviewResponse = { columns?: PreviewColumn[] | string[] headers?: string[] rows?: Record[] sample_rows?: Record[] total_rows?: number row_count?: number mapping?: Record detected_types?: Record } type Issue = { id?: string | number row_number?: number row?: number code?: string field?: string column_name?: string | null message?: string severity?: string } type RejectedRecord = { id?: string | number row_number?: number raw_record?: Record canonical_record?: Record reasons?: Issue[] } type IssuesResponse = { issues?: Issue[] rejected_records?: RejectedRecord[] records?: RejectedRecord[] total?: number } type HistoryResponse = { import_sessions?: ImportSession[] sessions?: ImportSession[] items?: ImportSession[] total?: number } type MappingProfilesResponse = MappingProfile[] | { mapping_profiles?: MappingProfile[]; profiles?: MappingProfile[]; items?: MappingProfile[] } type ActionResponse = ImportSession & { dataset?: Dataset kind?: DatasetKind name?: string version_label?: string | null version_number?: number validation_run_id?: string dataset_ids?: string[] datasets?: DatasetRef[] dataset_id?: string status?: string } const categoryOptions: { value: ImportKind; label: string; detail: string; icon: typeof Database }[] = [ { value: 'liability_inforce', label: 'Inforce', detail: 'Policy or account-level records', icon: Database }, { value: 'assumption_table', label: 'Assumption table', detail: 'Rates, curves, or assumptions', icon: FileSpreadsheet }, { value: 'factor_table', label: 'Factor table', detail: 'Multipliers and lookup factors', icon: Sparkles }, { value: 'scenario', label: 'Scenario', detail: 'Economic or stress scenarios', icon: ShieldCheck }, ] const displayStatus = (status?: string) => (status ?? 'draft').replaceAll('_', ' ') const formatDate = (value?: string) => value ? new Date(value).toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' }) : '—' const datasetKinds: Record = { liability_inforce: 'inforce', assumption_table: 'assumption', factor_table: 'factor', scenario: 'scenario', } const datasetKindFor = (category: ImportKind): DatasetKind => datasetKinds[category] function asPreviewColumns(preview: PreviewResponse | null): PreviewColumn[] { if (!preview) return [] if (Array.isArray(preview.columns)) return preview.columns.map(column => typeof column === 'string' ? { name: column, source: column } : column) if (Array.isArray(preview.headers)) return preview.headers.map(name => ({ name, source: name })) const rows = preview.rows ?? preview.sample_rows ?? [] return rows[0] ? Object.keys(rows[0]).map(name => ({ name, source: name })) : [] } function asPreviewRows(preview: PreviewResponse | null, columns: PreviewColumn[]) { const rows = preview?.rows ?? preview?.sample_rows ?? [] return rows.slice(0, 5).map(row => columns.map(column => String(row[column.source ?? column.name] ?? '—'))) } function historyItems(history: HistoryResponse | null) { return history?.import_sessions ?? history?.sessions ?? history?.items ?? [] } export function DataManager({ initialCategory = 'liability_inforce' }: { initialCategory?: ImportKind }) { const { projectId, project } = useWorkspace() const { request, user } = useApi() const [kind, setKind] = useState(initialCategory) const [datasetName, setDatasetName] = useState('') const [versionLabel, setVersionLabel] = useState('') const [valuationDate, setValuationDate] = useState('') const [expectedRecordCount, setExpectedRecordCount] = useState('') const [lookupKeys, setLookupKeys] = useState('') const [valueColumn, setValueColumn] = useState('') const [tableType, setTableType] = useState('generic') const [scenarioModelVersionId, setScenarioModelVersionId] = useState('') const [scenarioStructuralOnly, setScenarioStructuralOnly] = useState(false) const [file, setFile] = useState(null) const [session, setSession] = useState(null) const [mapping, setMapping] = useState>({}) const [mappingProfileId, setMappingProfileId] = useState('') const [mappingProfileName, setMappingProfileName] = useState('') const [validationRunId, setValidationRunId] = useState('') const [selectedDatasetId, setSelectedDatasetId] = useState('') const [comparisonBaseId, setComparisonBaseId] = useState('') const [compareDatasetId, setCompareDatasetId] = useState('') const [datasetRecord, setDatasetRecord] = useState(null) const [rejectReason, setRejectReason] = useState('') const [busyAction, setBusyAction] = useState('') const [error, setError] = useState('') const [success, setSuccess] = useState('') const roles = user?.roles ?? [] const uploadAllowed = canImportData(roles) const reviewAllowed = canReviewData(roles) const sessionId = session?.id ?? null const category = session?.category ?? kind const previewQuery = useApiQuery(sessionId ? `/v1/import-sessions/${sessionId}/preview` : null) const issuesQuery = useApiQuery(validationRunId ? `/v1/validation-runs/${validationRunId}/issues` : null) const rejectedQuery = useApiQuery(validationRunId ? `/v1/validation-runs/${validationRunId}/rejected-records?limit=50&offset=0` : null) const mappingProfilesQuery = useApiQuery( projectId && category ? `/v1/mapping-profiles?project_id=${encodeURIComponent(projectId)}&category=${encodeURIComponent(category)}` : null, ) const historyQuery = useApiQuery(projectId ? `/v1/projects/${projectId}/import-sessions` : null) const datasets = session?.datasets?.length ? session.datasets : session?.dataset_id ? [{ id: session.dataset_id, kind: (session.dataset_kind as DatasetKind | null) ?? datasetKindFor(category) }] : [] const selectedDataset = datasets.find(dataset => dataset.id === selectedDatasetId) ?? datasets[0] const versionsQuery = useApiQuery(selectedDataset ? `/v1/datasets/${selectedDataset.kind}/${selectedDataset.id}/versions` : null) const comparisonBaseDatasetId = comparisonBaseId || selectedDataset?.id || '' const compareQuery = useApiQuery<{ changes?: { change: string; key: string[]; before?: Record; after?: Record }[]; added_count?: number; removed_count?: number; changed_count?: number }>( selectedDataset && comparisonBaseDatasetId && compareDatasetId && compareDatasetId !== comparisonBaseDatasetId ? `/v1/datasets/${selectedDataset.kind}/${encodeURIComponent(comparisonBaseDatasetId)}/compare?other_id=${encodeURIComponent(compareDatasetId)}&limit=50` : null, ) const columns = useMemo(() => asPreviewColumns(previewQuery.data), [previewQuery.data]) const rows = useMemo(() => asPreviewRows(previewQuery.data, columns), [previewQuery.data, columns]) const mappingProfiles = Array.isArray(mappingProfilesQuery.data) ? mappingProfilesQuery.data : mappingProfilesQuery.data?.mapping_profiles ?? mappingProfilesQuery.data?.profiles ?? mappingProfilesQuery.data?.items ?? [] const versions = Array.isArray(versionsQuery.data) ? versionsQuery.data : versionsQuery.data?.versions ?? versionsQuery.data?.datasets ?? versionsQuery.data?.items ?? [] const issues = issuesQuery.data?.issues ?? [] const rejectedRecords = rejectedQuery.data?.rejected_records ?? rejectedQuery.data?.records ?? [] const datasetId = selectedDataset?.id ?? session?.dataset_id ?? null const sessionKind = datasets.find(dataset => dataset.id === selectedDataset?.id)?.kind ?? session?.dataset_kind ?? datasetKindFor(category) const sessionStatus = (session?.status ?? '').toLowerCase() const sessionFileName = session?.original_filename ?? session?.file_name const step = !session ? 1 : !sessionFileName && !file ? 2 : !previewQuery.data ? 3 : sessionStatus === 'committed' ? 5 : 4 const blockingIssueCount = issues.filter(issue => issue.severity === 'error').length const currentDataset = (datasetRecord?.id === selectedDataset?.id ? datasetRecord : null) ?? versions.find(version => version.id === selectedDataset?.id) ?? null const canDecide = reviewAllowed && ['validated', 'needs_review'].includes((currentDataset?.status ?? '').toLowerCase()) const canStartSession = Boolean(projectId && datasetName.trim()) && (category !== 'scenario' || scenarioStructuralOnly || Boolean(scenarioModelVersionId.trim())) const runAction = async (label: string, action: () => Promise) => { setBusyAction(label) setError('') setSuccess('') try { await action() } catch (caught) { setError(caught instanceof Error ? caught.message : `${label} failed.`) } finally { setBusyAction('') } } const createSession = () => runAction('Creating session', async () => { if (!uploadAllowed) throw new Error('Your role cannot start an import session.') if (!projectId) throw new Error('Select a project before starting an import session.') if (!datasetName.trim()) throw new Error('Enter a name for this dataset before starting the import session.') const options: Record = {} if (category === 'liability_inforce') { if (valuationDate) options.valuation_date = valuationDate if (expectedRecordCount) options.expected_record_count = Number(expectedRecordCount) } else if (category === 'assumption_table' || category === 'factor_table') { if (lookupKeys.trim()) options.lookup_keys = lookupKeys.split(',').map(value => value.trim()).filter(Boolean) if (valueColumn.trim()) options.value_column = valueColumn.trim() if (tableType.trim()) options.table_type = tableType.trim() } else if (category === 'scenario') { if (scenarioModelVersionId.trim()) options.model_version_id = scenarioModelVersionId.trim() if (scenarioStructuralOnly) options.structural_only = true if (!scenarioModelVersionId.trim() && !scenarioStructuralOnly) throw new Error('Choose a model version for scenario validation or enable structural-only validation.') } const created = await request('/v1/import-sessions', { method: 'POST', body: JSON.stringify({ project_id: projectId, category, name: datasetName.trim(), version_label: versionLabel.trim() || null, options, }), }) setSession(created) setFile(null) setMapping({}) setValidationRunId('') setSelectedDatasetId('') setComparisonBaseId('') setCompareDatasetId('') setSuccess('Import session created. Add a source file to continue.') historyQuery.refetch() }) const uploadFile = () => runAction('Uploading file', async () => { if (!uploadAllowed) throw new Error('Your role cannot upload files.') if (!sessionId || !file) throw new Error('Choose a file before uploading.') const body = new FormData() body.append('file', file) const uploaded = await request(`/v1/import-sessions/${sessionId}/files`, { method: 'POST', body }) setSession(current => ({ ...(current ?? { id: sessionId }), ...uploaded, file_name: uploaded.file_name ?? file.name, original_filename: uploaded.original_filename ?? file.name })) setValidationRunId('') setMapping({}) setMappingProfileId('') setSuccess(`${file.name} uploaded. Preview the rows and confirm the mapping.`) previewQuery.refetch() historyQuery.refetch() }) const saveMapping = () => runAction('Saving mapping', async () => { if (!uploadAllowed) throw new Error('Your role cannot change import mappings.') if (!sessionId) throw new Error('Start an import session first.') const fields = columns.reduce((next, column) => { const source = column.source ?? column.name const value = mapping[source] ?? previewQuery.data?.mapping?.[source] if (value) next.push({ source_column: source, target_field: value }) return next }, []) const body = mappingProfileId ? { profile_id: mappingProfileId } : { fields } const updated = await request(`/v1/import-sessions/${sessionId}/mapping`, { method: 'PUT', body: JSON.stringify(body), }) setSession(current => ({ ...(current ?? { id: sessionId }), ...updated })) setSuccess('Column mapping saved. Run validation when the mapping is ready.') previewQuery.refetch() }) const saveMappingProfile = () => runAction('Saving mapping profile', async () => { if (!uploadAllowed) throw new Error('Your role cannot save mapping profiles.') if (!projectId || !mappingProfileName.trim()) throw new Error('Enter a name for the mapping profile.') const fields = columns.flatMap(column => { const source = column.source ?? column.name const target = mapping[source] ?? previewQuery.data?.mapping?.[source] return target ? [{ source_column: source, target_field: target }] : [] }) if (!fields.length) throw new Error('Map at least one source column before saving a profile.') const profile = await request('/v1/mapping-profiles', { method: 'POST', body: JSON.stringify({ project_id: projectId, category, name: mappingProfileName.trim(), fields }), }) setMappingProfileId(profile.id) setSuccess(`Mapping profile “${profile.name}” saved.`) mappingProfilesQuery.refetch() }) const validate = () => runAction('Validating import', async () => { if (!uploadAllowed) throw new Error('Your role cannot validate imports.') if (!sessionId) throw new Error('Start an import session first.') const result = await request<{ id: string; status: 'passed' | 'invalid'; error_count: number; warning_count: number; accepted_count: number; rejected_count: number }>(`/v1/import-sessions/${sessionId}/validate`, { method: 'POST' }) setValidationRunId(result.id) const status = result.status === 'invalid' ? 'invalid' : result.warning_count > 0 ? 'needs_review' : 'validated' setSession(current => current ? { ...current, status } : current) setSuccess(`Validation ${displayStatus(result.status)}: ${result.error_count} errors, ${result.warning_count} warnings, ${result.accepted_count} accepted, ${result.rejected_count} rejected.`) issuesQuery.refetch() rejectedQuery.refetch() previewQuery.refetch() historyQuery.refetch() }) const commit = () => runAction('Committing dataset', async () => { if (!uploadAllowed) throw new Error('Your role cannot commit imported data.') if (!sessionId) throw new Error('Start an import session first.') const result = await request(`/v1/import-sessions/${sessionId}/commit`, { method: 'POST' }) const refs = (result.dataset_ids ?? [result.id]).map(id => ({ id, kind: result.kind })) setSession(current => current ? { ...current, status: 'committed', dataset_id: result.id, dataset_kind: result.kind, dataset_ids: refs.map(dataset => dataset.id), datasets: refs, validation_run_id: validationRunId || current.validation_run_id, } : current) setDatasetRecord(result) setSelectedDatasetId(result.id) setComparisonBaseId(result.id) setCompareDatasetId('') setSuccess(`${refs.length} dataset${refs.length === 1 ? '' : 's'} committed. Independent review is required before approval.`) historyQuery.refetch() }) const decide = (decision: 'approve' | 'reject') => runAction(decision === 'approve' ? 'Approving dataset' : 'Rejecting dataset', async () => { if (!reviewAllowed) throw new Error('Your role cannot approve or reject imported data.') if (!datasetId) throw new Error('A committed dataset ID is required for review.') if (decision === 'reject' && !rejectReason.trim()) throw new Error('Add a reason before rejecting this dataset.') let result: Dataset try { result = await request(`/v1/datasets/${encodeURIComponent(sessionKind)}/${encodeURIComponent(datasetId)}/${decision}`, { method: 'POST', body: decision === 'reject' ? JSON.stringify({ reason: rejectReason.trim() }) : JSON.stringify({}), }) } catch (caught) { if (caught instanceof ApiError && (caught.code === 'SELF_APPROVAL_FORBIDDEN' || caught.message.includes('SELF_APPROVAL_FORBIDDEN'))) { throw new Error('You cannot review a dataset you committed. Ask another authorized reviewer to approve or reject it.') } throw caught } setDatasetRecord(result) setSession(current => current ? { ...current, status: 'committed', datasets: current.datasets?.map(dataset => dataset.id === result.id ? { id: result.id, kind: result.kind } : dataset), dataset_id: result.id, dataset_kind: result.kind, } : current) setSuccess(`Dataset ${decision === 'approve' ? 'approved' : 'rejected'} successfully.`) setRejectReason('') historyQuery.refetch() }) const resetSession = () => { setSession(null) setFile(null) setMapping({}) setValidationRunId('') setSelectedDatasetId('') setComparisonBaseId('') setCompareDatasetId('') setDatasetRecord(null) setError('') setSuccess('') } const selectHistorySession = async (item: ImportSession) => { setDatasetRecord(null) setSession(item) setKind(item.category ?? kind) setDatasetName(item.name ?? '') setVersionLabel(item.version_label ?? '') setValuationDate(String(item.options?.valuation_date ?? '')) setExpectedRecordCount(item.options?.expected_record_count === undefined ? '' : String(item.options.expected_record_count)) setLookupKeys(Array.isArray(item.options?.lookup_keys) ? item.options.lookup_keys.join(', ') : '') setValueColumn(String(item.options?.value_column ?? '')) setTableType(String(item.options?.table_type ?? 'generic')) setScenarioModelVersionId(String(item.options?.model_version_id ?? '')) setScenarioStructuralOnly(item.options?.structural_only === true) setMapping(Object.fromEntries((item.mapping_fields ?? []).map(field => [field.source_column, field.target_field]))) setValidationRunId(item.validation_run_id ?? '') setSelectedDatasetId(item.dataset_id ?? item.datasets?.[0]?.id ?? '') setComparisonBaseId(item.dataset_id ?? item.datasets?.[0]?.id ?? '') setMappingProfileId(item.mapping_profile_id ?? '') setFile(null) setError('') setSuccess('') try { const result = await request(`/v1/import-sessions/${item.id}`) setSession(result) setDatasetName(result.name ?? '') setVersionLabel(result.version_label ?? '') setValuationDate(String(result.options?.valuation_date ?? '')) setExpectedRecordCount(result.options?.expected_record_count === undefined ? '' : String(result.options.expected_record_count)) setLookupKeys(Array.isArray(result.options?.lookup_keys) ? result.options.lookup_keys.join(', ') : '') setValueColumn(String(result.options?.value_column ?? '')) setTableType(String(result.options?.table_type ?? 'generic')) setScenarioModelVersionId(String(result.options?.model_version_id ?? '')) setScenarioStructuralOnly(result.options?.structural_only === true) setMapping(Object.fromEntries((result.mapping_fields ?? []).map(field => [field.source_column, field.target_field]))) setValidationRunId(result.validation_run_id ?? '') setSelectedDatasetId(result.dataset_id ?? result.datasets?.[0]?.id ?? '') setComparisonBaseId(result.dataset_id ?? result.datasets?.[0]?.id ?? '') setMappingProfileId(result.mapping_profile_id ?? '') setDatasetRecord(null) } catch (caught) { setError(caught instanceof Error ? caught.message : 'Could not load this import session.') } } return
DATA GOVERNANCE IMPORT CONTROL

Data manager

Move source data into your project through a controlled, reviewable release workflow.

{project?.name ?? 'No project selected'} {roles.length ? roles.join(' · ') : 'Role unavailable'}
GOVERNED IMPORT{['Choose a dataset', 'Upload your source', 'Review columns', 'Validate and commit', 'Review release'][step - 1]}{session ? `${displayStatus(session.status)} · ${sessionFileName ?? 'No source file yet'}` : 'Four dataset types · validation before release'}
Workflow progress0{step} / 05
{[1, 2, 3, 4, 5].map(index => index ? 'is-done' : step === index ? 'is-active' : ''} />)}
Approval-controlled
{error &&
{error}
} {success &&
{success}
}
STEP 01

Choose the data contract

Start with the governed dataset category. This controls validation rules and approval routing.

{step}/5
{categoryOptions.map(option => { const Icon = option.icon; return })}
{!session &&
{kind === 'liability_inforce' && <> } {(kind === 'assumption_table' || kind === 'factor_table') && <> } {kind === 'scenario' && <> }
} {session ?
ACTIVE SESSION{session.id}
{displayStatus(session.status)}{uploadAllowed && }
:
Create a session to reserve an auditable import workspace.{uploadAllowed && }
} {!uploadAllowed &&

Upload and commit actions require admin, actuary, or model_developer access.

}
{session && <>
STEP 02

Upload source file

Attach the source file to {session.id}. Original files remain linked to the import session.

{uploadAllowed && }
{sessionFileName ? 'A file is already attached. Uploading again replaces the session file.' : 'No file attached yet.'}{uploadAllowed && }
STEP 03

Preview and map columns

Confirm the sample rows and map source headers to the destination schema before validating.

{previewQuery.loading &&
Loading preview…
} {previewQuery.error &&
Preview unavailable: {previewQuery.error.message}
} {!previewQuery.loading && !previewQuery.error && !columns.length &&
Upload a file to see its headers and sample records.
} {columns.length > 0 && <>
{previewQuery.data?.total_rows ?? previewQuery.data?.row_count ?? '—'} source rows{columns.length} detected columns{issues.length} current issues
{columns.map(column => )}{rows.length ? rows.map((row, rowIndex) => {row.map((value, columnIndex) => )}) : }
{column.name}
{value}
No sample rows returned by the API.

Column mapping

Use the backend schema names for destination fields.
{mappingProfilesQuery.error &&
Could not load mapping profiles: {mappingProfilesQuery.error.message}
}
{columns.map(column => { const source = column.source ?? column.name; return })}
Mapping is saved against this session and included in validation.{uploadAllowed && <>}
}
STEP 04

Validate and commit

Resolve blocking issues before making the dataset available for review.

{['validated', 'needs_review'].includes(sessionStatus) ? : }
Validation status{session.status ? displayStatus(session.status) : 'Not run yet'}
Blocking issues{blockingIssueCount ? `${blockingIssueCount} error${blockingIssueCount === 1 ? '' : 's'}` : 'None returned'}
Rejected records{rejectedRecords.length ? `${rejectedRecords.length} record${rejectedRecords.length === 1 ? '' : 's'}` : 'None returned'}
{(issuesQuery.loading || rejectedQuery.loading) &&
Loading validation findings…
} {issuesQuery.error &&
Could not load validation issues: {issuesQuery.error.message}
} {rejectedQuery.error &&
Could not load rejected records: {rejectedQuery.error.message}
} {issues.length > 0 &&

Issues

{issues.slice(0, 8).map((issue, index) =>
Row {issue.row_number ?? issue.row ?? '—'}{issue.column_name ?? issue.field ?? 'Record'}

{issue.message ?? 'Validation issue returned by the API.'}

)}
} {rejectedRecords.length > 0 &&

Rejected records

{rejectedRecords.slice(0, 5).map((record, index) =>
Row {record.row_number ?? '—'}{record.reasons?.map(reason => reason.column_name ?? reason.field ?? reason.code).filter(Boolean).join(', ') || 'Record'}

{record.reasons?.map(reason => reason.message).filter(Boolean).join('; ') || 'Rejected by validation.'}
Source: {JSON.stringify(record.raw_record ?? {})}

)}
}
Commit creates a dataset record and starts the approval gate. Warnings are allowed; errors are blocking.{uploadAllowed && }
{datasetId &&
STEP 05

Approval gate

Reviewers make the final release decision for the committed dataset. The uploader cannot approve their own upload.

{datasets.length > 1 && }
Dataset{datasetId}{displayStatus(currentDataset?.status ?? session.status ?? 'committed')}
{!reviewAllowed &&

Approval actions require admin, actuary, or reviewer access.

}{reviewAllowed && canDecide && <>
Kind: {sessionKind} · governed dataset ID: {datasetId}
}{reviewAllowed && !canDecide &&

{currentDataset?.status ? `This dataset is ${displayStatus(currentDataset.status)} and is not awaiting review.` : 'Loading the committed dataset lifecycle status…'}

}
} {datasetId &&
DATASET LIFECYCLE

Versions and comparison

Review every immutable version and compare rows between versions.

{versionsQuery.loading &&
Loading dataset versions…
} {versionsQuery.error &&
Could not load dataset versions: {versionsQuery.error.message}
} {!versionsQuery.loading && !versionsQuery.error && versions.length === 0 &&
No dataset versions were returned.
} {versions.length > 0 && <>
{versions.map(version =>
{version.name}{version.version_label ?? `Version ${version.version_number}`} · {version.row_count?.toLocaleString() ?? '—'} rows{displayStatus(version.status)}{version.committed_at ? formatDate(version.committed_at) : ''}
)}
{compareQuery.error &&
Comparison failed: {compareQuery.error.message}
} {compareQuery.loading &&
Comparing versions…
} {compareQuery.data && <>
{compareQuery.data.added_count ?? 0} added{compareQuery.data.removed_count ?? 0} removed{compareQuery.data.changed_count ?? 0} changed
{(compareQuery.data.changes ?? []).slice(0, 20).map((change, index) =>
{change.change}{change.key.join(', ')}

{change.before ? JSON.stringify(change.before) : '—'} → {change.after ? JSON.stringify(change.after) : '—'}

)}
} }
} }
} export default DataManager