import { useEffect, useMemo, useState } from 'react'
import {
ArrowRight,
CalendarDays,
Check,
ChevronDown,
Database,
FileText,
Filter,
Lightbulb,
LineChart,
Plus,
Search,
Settings2,
SlidersHorizontal,
Workflow,
X,
} from 'lucide-react'
import { useApiQuery } from '../../api/useApiQuery'
import { useWorkspace } from '../../api/WorkspaceContext'
import { canImportData, canSubmitRuns } from '../../api/permissions'
import { useApi } from '../../api/ApiProvider'
import { RunSetSubmissionDialog } from '../run-set-workflow/RunSetWorkflow'
import { ProjectionSetCreateDialog } from './ProjectionSetCreateDialog'
import './projection-sets.css'
const EMPTY_PROJECTION_SETS = []
export function ProjectionSetsLibrary({ onNotify, startCreate = false, onCreateOpened, onSetupStarted, onSetupFinished, onNavigateToInput, onNavigateToScenario }) {
const { projectId } = useWorkspace()
const { user } = useApi()
const canCreateProjectionSet = canImportData(user?.roles ?? [])
const canCreateRunSet = canSubmitRuns(user?.roles ?? [])
const projectionQuery = useApiQuery(projectId ? `/v1/projects/${projectId}/projection-sets` : null)
const consumersQuery = useApiQuery(projectId ? `/v1/projects/${projectId}/run-sets` : null, 10000)
const apiSets = projectionQuery.data?.projection_sets ?? EMPTY_PROJECTION_SETS
const [sets, setSets] = useState([])
const [query, setQuery] = useState('')
const [statusFilter, setStatusFilter] = useState('All statuses')
const [filterOpen, setFilterOpen] = useState(false)
const [view, setView] = useState('list')
const [createOpen, setCreateOpen] = useState(startCreate && canCreateProjectionSet)
const [runSetDialogOpen, setRunSetDialogOpen] = useState(false)
const [selectedSet, setSelectedSet] = useState(null)
const [manageOpen, setManageOpen] = useState(false)
const [preferredSetId, setPreferredSetId] = useState('')
useEffect(() => {
const mapped = apiSets.map((item) => ({
id: item.id,
projectId: item.project_id,
savedScenarioIds: (item.scenarios ?? []).map(scenario => scenario.id),
validation: Object.fromEntries((item.validation?.checks ?? []).map(check => [check.code, check.status === 'pass'])),
name: item.name,
version: item.version_label || '—',
scenario: (item.scenarios ?? []).map(scenario => scenario.name).filter(Boolean).join(', ') || 'No scenarios attached',
horizon: `${item.valuation_date || '—'} · ${item.horizon_months ?? '—'} months`,
inputs: `${item.counts?.input_count ?? 0} inputs`,
formulas: `${item.counts?.formula_count ?? 0} formulas`,
description: item.description || '—',
status: item.status === 'validated' ? 'Ready' : item.status === 'needs_review' ? 'Needs review' : 'Draft',
capture: item.validation?.status === 'validated' ? 'Backend validation passed' : 'Validation required',
captureDetail: (item.validation?.checks ?? []).filter(check => check.status !== 'pass').map(check => check.message).filter(Boolean).join(' · ') || `${item.counts?.policy_count ?? 0} policies · ${item.output_variables?.length ?? 0} captured outputs`,
preview: (item.validation?.checks ?? []).some(check => check.status !== 'pass') ? 'lines' : 'bars',
product: item.model_version?.product_code || '—',
modelName: item.model_version?.model_name || '—',
modelVersion: item.model_version?.version_label || '—',
raw: item,
}))
setSets(mapped)
setSelectedSet(current => mapped.find(item => item.id === (preferredSetId || current?.id)) ?? mapped[0] ?? null)
if (preferredSetId && mapped.some(item => item.id === preferredSetId)) setPreferredSetId('')
}, [apiSets, preferredSetId])
useEffect(() => {
if (!startCreate || !canCreateProjectionSet) return
onCreateOpened?.()
}, [startCreate, canCreateProjectionSet, onCreateOpened])
const visibleSets = useMemo(() => {
const normalizedQuery = query.trim().toLowerCase()
return sets.filter((set) => {
const matchesStatus = statusFilter === 'All statuses' || set.status === statusFilter
const searchable = `${set.name} ${set.scenario} ${set.description} ${set.product}`.toLowerCase()
return matchesStatus && searchable.includes(normalizedQuery)
})
}, [query, sets, statusFilter])
const readyCount = sets.filter(set => set.status === 'Ready').length
const reviewCount = sets.filter(set => set.status === 'Needs review').length
const consumingIds = new Set((consumersQuery.data?.run_sets ?? []).flatMap(item => (item.projection_sets ?? item.projection_set_ids ?? []).map(set => typeof set === 'string' ? set : set.id).filter(Boolean)))
return (
Projection Sets Reusable configurations that define exactly what the model calculates before a Run Set is created.
Versioned and validated
Aligned to model and scenario
Ready for projection runs
} value={readyCount} label="Ready to run" detail="Fully validated and ready for Run Sets" tone="ready" onClick={() => setStatusFilter('Ready')} />
} value={reviewCount} label="Needs review" detail="Backend validation requires attention" tone="warning" onClick={() => setStatusFilter('Needs review')} />
} value={consumingIds.size} label="Active consumers" detail="Run Sets using these Projection Sets" tone="consumers" onClick={() => onNotify(`${consumingIds.size} Projection Sets are referenced by submitted Run Sets`)} />
{filterOpen && (
Status setStatusFilter(event.target.value)} value={statusFilter}>All statuses Ready Needs review Draft
setStatusFilter('All statuses')}>Clear filters
)}
Projection Set Library ({visibleSets.length})
onNotify('Sorting by last updated is not available yet; showing the backend order.')}>Sort by Last updated
{projectionQuery.loading &&
Loading Projection Sets from the backend…
}
{projectionQuery.error &&
Could not load Projection Sets: {projectionQuery.error.message}
}
{visibleSets.map((set) => (
setSelectedSet(set)}
onNotify={onNotify}
onViewDetails={() => { setSelectedSet(set); setManageOpen(true) }}
/>
))}
{!projectionQuery.loading && !projectionQuery.error && visibleSets.length === 0 && No Projection Sets are saved for this project yet.
}
{ if (!canCreateProjectionSet) return; if (onSetupStarted) onSetupStarted(); setCreateOpen(true) }}
onCreateRun={() => { if (!canCreateRunSet) return; if (selectedSet) setRunSetDialogOpen(true); else onNotify('Create a Projection Set before creating a Run Set.') }}
onManage={() => { if (selectedSet) setManageOpen(true) }}
onNotify={onNotify}
canCreateProjectionSet={canCreateProjectionSet}
canCreateRunSet={canCreateRunSet}
/>
{createOpen && canCreateProjectionSet &&
{ setCreateOpen(false); onSetupFinished?.() }} onCreated={(message) => { projectionQuery.refetch(); setCreateOpen(false); onSetupFinished?.(); onNotify(message) }} onNavigateToInput={onNavigateToInput} onNavigateToScenario={onNavigateToScenario} />}
{runSetDialogOpen && selectedSet && setRunSetDialogOpen(false)} />}
{manageOpen && selectedSet && setManageOpen(false)}
onUpdated={(message, newId) => { projectionQuery.refetch(); if (newId) setPreferredSetId(newId); onNotify(message) }}
/>}
)
}
function ProjectionSummary({ icon, value, label, detail, tone, onClick }) {
return (
{icon}
{value}
{label} {detail}
)
}
function ProjectionSetCard({ set, selected, view, onSelect, onNotify, onViewDetails }) {
const isGrid = view === 'grid'
return (
{set.name}
{set.version} · {set.scenario}
{set.horizon} {set.inputs} {set.formulas}
{set.description}
{set.product} Model {set.modelVersion || 'version'} {set.scenario}
{set.capture}
{set.captureDetail || 'No additional validation detail was returned by the backend.'}
onNotify(set.captureDetail ? `${set.name}: ${set.captureDetail}` : `No additional validation detail is available for ${set.name}.`)}>View validation details
View Projection Set details
)
}
function ProjectionPreview({ type }) {
if (type === 'lines') {
return (
Output Preview
Reserves Net earnings
)
}
return (
Output Preview
{[16, 22, 29, 36, 45, 54, 64, 75, 88].map((height, index) => )}
Liability reserves
)
}
function ProjectionActionsRail({ selectedSet, selectedModel, onCreate, onCreateRun, onManage, onNotify, canCreateProjectionSet, canCreateRunSet }) {
return (
{canCreateProjectionSet && Create Projection Set }
{selectedSet && View / manage selected set }
{canCreateRunSet && ▷ Create Run Set }
Helpful resources
} title="Projection set guide" detail="Learn best practices" onClick={() => onNotify('Projection Set guide content is not available in this workspace yet.')} />
} title="Validation rules" detail="Understand checks" onClick={() => onNotify('Validation rule documentation is not available in this workspace yet.')} />
} title="Output mappings" detail="See available outputs" onClick={() => onNotify('Output mapping documentation is not available in this workspace yet.')} />
Model context
Model{selectedModel ? `${selectedModel.name} ${selectedModel.version}` : 'Not selected'}
Scenario{selectedSet?.scenario ?? 'Not selected'}
Projection horizon{selectedSet?.horizon ?? 'Not selected'}
Input library{selectedSet?.inputs ?? 'Not selected'}
onNotify('Projection documentation is not available in this workspace yet.')}>Need help? Open documentation
)
}
function ActivityIcon() {
return
}
function ResourceLink({ icon, title, detail, onClick }) {
return {icon} {title} {detail}
}
function ProjectionSetDetails({ projectionSet, canEdit, onClose, onUpdated }) {
const { projectId } = useWorkspace()
const { request } = useApi()
const detailQuery = useApiQuery(projectionSet?.id ? `/v1/projection-sets/${projectionSet.id}` : null)
const scenarioQuery = useApiQuery(projectId ? `/v1/projects/${projectId}/scenario-sets` : null)
const detail = detailQuery.data ?? projectionSet
const scenarios = (scenarioQuery.data?.scenario_sets ?? []).flatMap(group => group.scenarios ?? [])
const attachedScenarioIds = new Set((detail?.scenarios ?? []).map(scenario => scenario.id))
const [editing, setEditing] = useState(false)
const [name, setName] = useState(detail?.name ?? '')
const [description, setDescription] = useState(detail?.description ?? '')
const [valuationDate, setValuationDate] = useState(detail?.valuation_date ?? '')
const [horizon, setHorizon] = useState(detail?.horizon_months ?? 12)
const [traceMode, setTraceMode] = useState(detail?.trace_scope?.mode ?? 'none')
const [tracePolicyIds, setTracePolicyIds] = useState((detail?.trace_scope?.policy_ids ?? []).join(', '))
const [scenarioId, setScenarioId] = useState('')
const [versionLabel, setVersionLabel] = useState('')
const [busy, setBusy] = useState(false)
const [error, setError] = useState('')
useEffect(() => {
setName(detail?.name ?? '')
setDescription(detail?.description ?? '')
setValuationDate(detail?.valuation_date ?? '')
setHorizon(detail?.horizon_months ?? 12)
setTraceMode(detail?.trace_scope?.mode ?? 'none')
setTracePolicyIds((detail?.trace_scope?.policy_ids ?? []).join(', '))
}, [detail])
const refreshDetail = (result, message) => {
detailQuery.refetch()
onUpdated(message, result?.id)
}
const edit = async () => {
if (!canEdit || busy || !detail?.id) return
setBusy(true)
setError('')
try {
const patch = {
name: name.trim(),
description: description.trim(),
valuation_date: valuationDate,
horizon_months: Number(horizon),
trace_scope: {
mode: traceMode,
policy_ids: traceMode === 'selected_policies'
? tracePolicyIds.split(',').map(value => value.trim()).filter(Boolean)
: [],
},
}
const updated = await request(`/v1/projection-sets/${detail.id}`, { method: 'PATCH', body: JSON.stringify(patch) })
const validated = await request(`/v1/projection-sets/${detail.id}/validate`, { method: 'POST' })
refreshDetail(validated ?? updated, `Projection Set updated and revalidated (${validated?.status ?? 'validation status unavailable'}).`)
setEditing(false)
} catch (caught) {
setError(caught instanceof Error ? caught.message : 'Could not update the Projection Set.')
} finally {
setBusy(false)
}
}
const attachScenario = async () => {
if (!canEdit || busy || !detail?.id || !scenarioId) return
setBusy(true)
setError('')
try {
const updated = await request(`/v1/projection-sets/${detail.id}/scenarios`, {
method: 'POST',
body: JSON.stringify({ scenario_id: scenarioId }),
})
const validated = await request(`/v1/projection-sets/${detail.id}/validate`, { method: 'POST' })
refreshDetail(validated ?? updated, `Scenario attached; Projection Set revalidated (${validated?.status ?? 'validation status unavailable'}).`)
setScenarioId('')
} catch (caught) {
setError(caught instanceof Error ? caught.message : 'Could not attach the scenario.')
} finally {
setBusy(false)
}
}
const duplicate = async () => {
if (!canEdit || busy || !detail?.id) return
setBusy(true)
setError('')
try {
const copy = await request(`/v1/projection-sets/${detail.id}/duplicate`, {
method: 'POST',
body: JSON.stringify(versionLabel.trim() ? { version_label: versionLabel.trim() } : {}),
})
onUpdated(`Created draft duplicate ${copy.name ?? copy.id}.`, copy.id)
onClose()
} catch (caught) {
setError(caught instanceof Error ? caught.message : 'Could not duplicate the Projection Set.')
} finally {
setBusy(false)
}
}
return (
)
}