import { useState } from 'react' import { Archive, ArrowLeft, Plus, RefreshCw, Save } from 'lucide-react' import { useApi } from '../../api/ApiProvider' import { useApiQuery } from '../../api/useApiQuery' import { canImportData } from '../../api/permissions' import './model-workspace.css' const statusLabel = status => (status ?? 'unknown').replaceAll('_', ' ') export function ModelWorkspace({ model, onNotify, onCreateProjection, onBack }) { const { request, user } = useApi() const canEdit = canImportData(user?.roles ?? []) const modelId = model?.id const detailQuery = useApiQuery(modelId ? `/v1/models/${encodeURIComponent(modelId)}` : null) const versionsQuery = useApiQuery(modelId ? `/v1/models/${encodeURIComponent(modelId)}/versions` : null) const detail = detailQuery.data const versions = versionsQuery.data?.versions ?? detail?.versions ?? [] const [selectedVersionId, setSelectedVersionId] = useState('') const selectedVersion = versions.find(version => version.id === selectedVersionId) ?? versions.find(version => version.is_current) ?? detail?.current_version ?? null const versionId = selectedVersion?.id const structureQuery = useApiQuery(versionId ? `/v1/model-versions/${encodeURIComponent(versionId)}/structure` : null) const variablesQuery = useApiQuery(versionId ? `/v1/model-versions/${encodeURIComponent(versionId)}/variables` : null) const [versionLabel, setVersionLabel] = useState('') const [changeSummary, setChangeSummary] = useState('') const [basis, setBasis] = useState('') const [createBusy, setCreateBusy] = useState(false) const [createError, setCreateError] = useState('') const [editingNotes, setEditingNotes] = useState(false) const [notesByVersion, setNotesByVersion] = useState({}) const [saveBusy, setSaveBusy] = useState(false) const [actionError, setActionError] = useState('') const notes = selectedVersion ? notesByVersion[selectedVersion.id] ?? selectedVersion.notes ?? '' : '' const createDraftVersion = async () => { if (!canEdit || !modelId || createBusy) return setCreateBusy(true) setCreateError('') try { const created = await request(`/v1/models/${encodeURIComponent(modelId)}/versions`, { method: 'POST', body: JSON.stringify({ ...(versionLabel.trim() ? { version_label: versionLabel.trim() } : {}), ...(selectedVersion?.id ? { parent_version_id: selectedVersion.id } : {}), ...((selectedVersion?.basis ?? basis.trim()) ? { basis: selectedVersion?.basis ?? basis.trim() } : {}), change_summary: changeSummary.trim() || null, }), }) setVersionLabel('') setChangeSummary('') setSelectedVersionId(created.id) versionsQuery.refetch() detailQuery.refetch() onNotify(`Draft ${created.version_label} created. It is not runnable until the backend provides a validation or approval workflow.`) } catch (error) { setCreateError(error instanceof Error ? error.message : 'Could not create a model draft.') } finally { setCreateBusy(false) } } const saveNotes = async () => { if (!canEdit || !selectedVersion || selectedVersion.status !== 'draft' || saveBusy) return setSaveBusy(true) setActionError('') try { await request(`/v1/model-versions/${encodeURIComponent(selectedVersion.id)}`, { method: 'PATCH', body: JSON.stringify({ notes }), }) setNotesByVersion(current => ({ ...current, [selectedVersion.id]: notes })) versionsQuery.refetch() detailQuery.refetch() setEditingNotes(false) onNotify('Draft version notes saved.') } catch (error) { setActionError(error instanceof Error ? error.message : 'Could not save the draft notes.') } finally { setSaveBusy(false) } } const archiveDraft = async () => { if (!canEdit || !selectedVersion || selectedVersion.status !== 'draft' || saveBusy) return if (!window.confirm(`Archive draft ${selectedVersion.version_label}? This draft will disappear from the version list.`)) return setSaveBusy(true) setActionError('') try { await request(`/v1/model-versions/${encodeURIComponent(selectedVersion.id)}`, { method: 'DELETE' }) setSelectedVersionId('') versionsQuery.refetch() detailQuery.refetch() onNotify(`Draft ${selectedVersion.version_label} archived.`) } catch (error) { setActionError(error instanceof Error ? error.message : 'Could not archive the draft.') } finally { setSaveBusy(false) } } const structure = structureQuery.data const variables = variablesQuery.data?.variables ?? [] const formulaGroups = structure?.formula_groups ?? [] return (
Model detail · {detail?.product_code ?? model?.product ?? '—'}

{detail?.name ?? model?.name ?? 'Model'}

{detail?.description || 'No description'} · Model ID {detail?.id ?? modelId}

{onBack && }
{detailQuery.error &&

Could not load model detail: {detailQuery.error.message}

}

Versions

Draft versions are not runnable yet. Formulas are not editable from the UI.

{versions.length} versions
{versionsQuery.loading &&

Loading model versions…

} {versionsQuery.error &&

Could not load versions: {versionsQuery.error.message}

}
{versions.map(version => ( ))}{!versionsQuery.loading && !versionsQuery.error && !versions.length &&

No versions are listed for this model.

}

Version structure

{selectedVersion ? `${selectedVersion.version_label} · ${statusLabel(selectedVersion.status)}` : 'Select a model version'}

{structureQuery.loading &&

Loading model structure…

} {structureQuery.error &&

Could not load structure: {structureQuery.error.message}

} {structure &&
{selectedVersion?.status === 'draft' &&

This draft is not runnable yet. The backend does not expose model-version approval or validation.

}
{Object.entries(structure.facts ?? {}).map(([label, value]) =>
{label.replaceAll('_', ' ')}{value}
)}

Hierarchy

{(structure.hierarchy ?? []).map((item, index) =>
{item.label}{item.level} · {item.meta}
)}

Formula groups

{formulaGroups.map(group =>
{group.name}

{group.formula_count} formulas · {group.version_label} · {group.lineage_state}

{group.description}
)}{!formulaGroups.length &&

No formula groups reported.

}
{structure.validation &&
Validation · {structure.validation.status}
{JSON.stringify(structure.validation, null, 2)}
}
}

Variables ({variablesQuery.data?.total ?? variables.length})

Definitions used by this model version.

{variablesQuery.loading &&

Loading variables…

} {variablesQuery.error &&

Could not load variables: {variablesQuery.error.message}

}
{variables.map(variable => )}
VariableKind / typeUnitRequiredSource
{variable.display_name}{variable.variable_name} · {variable.description}{variable.kind} / {variable.data_type}{variable.unit ?? '—'}{variable.required ? 'Yes' : 'No'}{variable.source?.type ?? '—'}