feat: Variantenmanagement — Sub-Projekte mit GAP-Analyse

Backend:
- parent_project_id auf iace_projects (DB + Go Struct)
- POST/GET /variants + GET /variant-gap Endpoints
- GAP-Analyse: Differenz Hazards/Massnahmen/Kategorien

Frontend:
- VariantPanel auf Projekt-Uebersicht
- Variante erstellen Dialog
- Sidebar-Anzeige (Variantenanzahl / Basis-Link)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Benjamin Admin
2026-05-09 10:47:01 +02:00
parent 2143840ee7
commit 8682522212
8 changed files with 592 additions and 11 deletions
@@ -0,0 +1,253 @@
'use client'
import { useState, useEffect, useCallback } from 'react'
import Link from 'next/link'
interface VariantProject {
id: string
machine_name: string
description?: string
status: string
hazard_count?: number
parent_project_id?: string
}
interface VariantGapResponse {
base_project: { id: string; name: string; hazard_count: number; measure_count: number }
variant: { id: string; name: string; hazard_count: number; measure_count: number }
gap: { additional_hazards: number; additional_measures: number; categories_affected: string[] }
}
interface Props {
projectId: string
parentProjectId?: string | null
parentProjectName?: string
}
export function VariantPanel({ projectId, parentProjectId, parentProjectName }: Props) {
const [variants, setVariants] = useState<VariantProject[]>([])
const [gapMap, setGapMap] = useState<Record<string, VariantGapResponse>>({})
const [loading, setLoading] = useState(true)
const [showCreate, setShowCreate] = useState(false)
const [creating, setCreating] = useState(false)
const [name, setName] = useState('')
const [description, setDescription] = useState('')
const fetchVariants = useCallback(async () => {
try {
const res = await fetch(`/api/sdk/v1/iace/projects/${projectId}/variants`)
if (!res.ok) {
setVariants([])
return
}
const json = await res.json()
const list: VariantProject[] = json.variants || json.projects || []
setVariants(list)
// Fetch gap analysis for this project
const gapRes = await fetch(`/api/sdk/v1/iace/projects/${projectId}/variant-gap`)
if (gapRes.ok) {
const gapJson = await gapRes.json()
const gaps: Record<string, VariantGapResponse> = {}
// Could be a single gap or array — handle both
if (Array.isArray(gapJson)) {
for (const g of gapJson) {
gaps[g.variant?.id] = g
}
} else if (gapJson.variant) {
gaps[gapJson.variant.id] = gapJson
}
setGapMap(gaps)
}
} catch {
setVariants([])
} finally {
setLoading(false)
}
}, [projectId])
useEffect(() => {
fetchVariants()
}, [fetchVariants])
async function handleCreate() {
if (!name.trim()) return
setCreating(true)
try {
const res = await fetch(`/api/sdk/v1/iace/projects/${projectId}/variants`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
machine_name: name.trim(),
description: description.trim(),
}),
})
if (res.ok) {
setName('')
setDescription('')
setShowCreate(false)
fetchVariants()
}
} catch {
// silently handle
} finally {
setCreating(false)
}
}
// If this project IS a variant, show link to base project
if (parentProjectId) {
return (
<div className="bg-white dark:bg-gray-800 rounded-xl border border-purple-200 dark:border-purple-700 p-6">
<div className="flex items-center gap-3">
<div className="w-10 h-10 bg-purple-50 dark:bg-purple-900/30 rounded-lg flex items-center justify-center">
<svg className="w-5 h-5 text-purple-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 16V4m0 0L3 8m4-4l4 4m6 0v12m0 0l4-4m-4 4l-4-4" />
</svg>
</div>
<div className="flex-1">
<p className="text-sm font-semibold text-gray-900 dark:text-white">Variante</p>
<p className="text-xs text-gray-500">
Dieses Projekt ist eine Variante des Basis-Projekts
</p>
</div>
<Link
href={`/sdk/iace/${parentProjectId}`}
className="inline-flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium text-purple-700 bg-purple-50 rounded-lg hover:bg-purple-100 dark:text-purple-300 dark:bg-purple-900/30 dark:hover:bg-purple-900/50 transition-colors"
>
{parentProjectName || 'Basis-Projekt'}
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 7l5 5m0 0l-5 5m5-5H6" />
</svg>
</Link>
</div>
</div>
)
}
if (loading) return null
if (variants.length === 0 && !showCreate) {
return (
<div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-6">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<div className="w-10 h-10 bg-gray-50 dark:bg-gray-700 rounded-lg flex items-center justify-center">
<svg className="w-5 h-5 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
</svg>
</div>
<div>
<p className="text-sm font-semibold text-gray-900 dark:text-white">Keine Varianten</p>
<p className="text-xs text-gray-500">Erstellen Sie Varianten fuer verschiedene Betriebsarten</p>
</div>
</div>
<button
onClick={() => setShowCreate(true)}
className="px-3 py-1.5 text-sm font-medium text-purple-700 bg-purple-50 rounded-lg hover:bg-purple-100 dark:text-purple-300 dark:bg-purple-900/30 dark:hover:bg-purple-900/50 transition-colors"
>
+ Neue Variante
</button>
</div>
{renderCreateDialog()}
</div>
)
}
function renderCreateDialog() {
if (!showCreate) return null
return (
<div className="mt-4 p-4 border border-purple-200 dark:border-purple-700 rounded-lg bg-purple-50/50 dark:bg-purple-900/10 space-y-3">
<h3 className="text-sm font-semibold text-gray-900 dark:text-white">Neue Variante erstellen</h3>
<input
type="text"
placeholder="Variantenname (z.B. Kollaborierender Betrieb)"
value={name}
onChange={(e) => setName(e.target.value)}
className="w-full px-3 py-2 text-sm border border-gray-300 rounded-lg bg-white dark:bg-gray-800 dark:border-gray-600 dark:text-white focus:ring-2 focus:ring-purple-500 focus:border-transparent"
/>
<textarea
placeholder="Beschreibung (optional)"
value={description}
onChange={(e) => setDescription(e.target.value)}
rows={2}
className="w-full px-3 py-2 text-sm border border-gray-300 rounded-lg bg-white dark:bg-gray-800 dark:border-gray-600 dark:text-white focus:ring-2 focus:ring-purple-500 focus:border-transparent"
/>
<div className="flex gap-2 justify-end">
<button
onClick={() => { setShowCreate(false); setName(''); setDescription('') }}
className="px-3 py-1.5 text-sm text-gray-600 hover:text-gray-800 dark:text-gray-400"
>
Abbrechen
</button>
<button
onClick={handleCreate}
disabled={creating || !name.trim()}
className="px-4 py-1.5 text-sm font-medium text-white bg-purple-600 rounded-lg hover:bg-purple-700 disabled:opacity-50 transition-colors"
>
{creating ? 'Erstelle...' : 'Erstellen'}
</button>
</div>
</div>
)
}
return (
<div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-6 space-y-4">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<div className="w-10 h-10 bg-purple-50 dark:bg-purple-900/30 rounded-lg flex items-center justify-center">
<svg className="w-5 h-5 text-purple-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
</svg>
</div>
<div>
<h2 className="text-sm font-semibold text-gray-900 dark:text-white">
Varianten ({variants.length})
</h2>
<p className="text-xs text-gray-500">Betriebsart-spezifische Projektversionen</p>
</div>
</div>
<button
onClick={() => setShowCreate(true)}
className="px-3 py-1.5 text-sm font-medium text-purple-700 bg-purple-50 rounded-lg hover:bg-purple-100 dark:text-purple-300 dark:bg-purple-900/30 dark:hover:bg-purple-900/50 transition-colors"
>
+ Neue Variante
</button>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
{variants.map((v) => {
const gap = gapMap[v.id]
return (
<Link
key={v.id}
href={`/sdk/iace/${v.id}`}
className="block p-4 border border-gray-200 dark:border-gray-700 rounded-lg hover:shadow-md hover:border-purple-300 transition-all group"
>
<div className="flex items-start justify-between gap-2">
<div className="min-w-0 flex-1">
<p className="text-sm font-medium text-gray-900 dark:text-white truncate group-hover:text-purple-700 dark:group-hover:text-purple-400">
{v.machine_name}
</p>
{v.description && (
<p className="text-xs text-gray-500 mt-0.5 line-clamp-2">{v.description}</p>
)}
</div>
<svg className="w-4 h-4 text-gray-400 group-hover:text-purple-600 flex-shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 7l5 5m0 0l-5 5m5-5H6" />
</svg>
</div>
{gap && gap.gap.additional_hazards > 0 && (
<span className="inline-flex items-center mt-2 px-2 py-0.5 text-xs font-medium bg-orange-100 text-orange-800 dark:bg-orange-900/50 dark:text-orange-300 rounded-full">
+{gap.gap.additional_hazards} Gefaehrdungen
</span>
)}
</Link>
)
})}
</div>
{renderCreateDialog()}
</div>
)
}
@@ -5,6 +5,7 @@ import Link from 'next/link'
import { useParams } from 'next/navigation'
import { SuggestedNorms } from './_components/SuggestedNorms'
import { ComplianceAlerts } from './_components/ComplianceAlerts'
import { VariantPanel } from './_components/VariantPanel'
interface ProjectOverview {
id: string
@@ -15,6 +16,8 @@ interface ProjectOverview {
completeness_pct: number
created_at: string
updated_at: string
parent_project_id?: string | null
parent_project_name?: string
metadata?: { limits_form?: Record<string, unknown> }
risk_summary?: {
critical?: number
@@ -125,12 +128,26 @@ export default function ProjectOverviewPage() {
const stepsComplete = [hasLimits, hasComponents, hasHazards, hasMitigations].filter(Boolean).length
const completeness = Math.round((stepsComplete / 6) * 100)
// If this is a variant, resolve parent project name
let parentName: string | undefined
if (json.parent_project_id) {
try {
const parentRes = await fetch(`/api/sdk/v1/iace/projects/${json.parent_project_id}`)
if (parentRes.ok) {
const parentJson = await parentRes.json()
parentName = parentJson.machine_name
}
} catch { /* ignore */ }
}
setProject({
...json,
completeness_pct: completeness,
component_count: compCount,
hazard_count: hazCount,
mitigation_count: mitCount,
parent_project_id: json.parent_project_id || null,
parent_project_name: parentName,
metadata: json.metadata,
risk_summary: {
critical: rs.critical || 0,
@@ -334,6 +351,13 @@ export default function ProjectOverviewPage() {
{/* Compliance Alerts */}
<ComplianceAlerts projectId={projectId} />
{/* Variant Management */}
<VariantPanel
projectId={projectId}
parentProjectId={project.parent_project_id}
parentProjectName={project.parent_project_name}
/>
{/* Suggested Norms */}
<SuggestedNorms projectId={projectId} />
+44 -1
View File
@@ -108,12 +108,40 @@ export default function IACELayout({ children }: { children: React.ReactNode })
const params = useParams()
const projectId = params?.projectId as string | undefined
const [projectName, setProjectName] = React.useState('')
const [variantInfo, setVariantInfo] = React.useState<{
parentProjectId?: string; parentName?: string; variantCount?: number
}>({})
React.useEffect(() => {
if (!projectId) return
fetch(`/api/sdk/v1/iace/projects/${projectId}`)
.then(r => r.ok ? r.json() : null)
.then(d => { if (d?.machine_name) setProjectName(d.machine_name) })
.then(async (d) => {
if (!d?.machine_name) return
setProjectName(d.machine_name)
// Resolve variant info
if (d.parent_project_id) {
try {
const pRes = await fetch(`/api/sdk/v1/iace/projects/${d.parent_project_id}`)
if (pRes.ok) {
const pj = await pRes.json()
setVariantInfo({ parentProjectId: d.parent_project_id, parentName: pj.machine_name })
} else {
setVariantInfo({ parentProjectId: d.parent_project_id })
}
} catch { setVariantInfo({ parentProjectId: d.parent_project_id }) }
} else {
// Check if this project has variants
try {
const vRes = await fetch(`/api/sdk/v1/iace/projects/${projectId}/variants`)
if (vRes.ok) {
const vj = await vRes.json()
const list = vj.variants || vj.projects || []
if (list.length > 0) setVariantInfo({ variantCount: list.length })
}
} catch { /* no variants endpoint yet */ }
}
})
.catch(() => {})
}, [projectId])
@@ -148,6 +176,21 @@ export default function IACELayout({ children }: { children: React.ReactNode })
{projectName}
</p>
)}
{variantInfo.parentProjectId && (
<Link
href={`/sdk/iace/${variantInfo.parentProjectId}`}
className="mt-1 flex items-center gap-1 text-[10px] text-orange-600 hover:text-orange-700 dark:text-orange-400 truncate"
title={variantInfo.parentName ? `Variante von: ${variantInfo.parentName}` : 'Variante'}
>
<svg className="w-3 h-3 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 16V4m0 0L3 8m4-4l4 4" />
</svg>
Variante von: {variantInfo.parentName || 'Basis'}
</Link>
)}
{variantInfo.variantCount != null && variantInfo.variantCount > 0 && (
<p className="mt-1 text-[10px] text-gray-400">({variantInfo.variantCount} Varianten)</p>
)}
<p className="text-[10px] text-gray-400 mt-0.5">CE-Compliance</p>
<Link
href="/sdk/iace/lines"
@@ -308,3 +308,88 @@ func (h *IACEHandler) InitFromProfile(c *gin.Context) {
"regulations_triggered": triggeredRegulations,
})
}
// ============================================================================
// Variant Management
// ============================================================================
// CreateVariant handles POST /projects/:id/variants
// Creates a new variant sub-project linked to the given base project.
func (h *IACEHandler) CreateVariant(c *gin.Context) {
parentID, err := uuid.Parse(c.Param("id"))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid project ID"})
return
}
// Verify parent project exists
parent, err := h.store.GetProject(c.Request.Context(), parentID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if parent == nil {
c.JSON(http.StatusNotFound, gin.H{"error": "parent project not found"})
return
}
var req iace.CreateProjectRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// Force the parent link
req.ParentProjectID = &parentID
project, err := h.store.CreateProject(c.Request.Context(), parent.TenantID, req)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusCreated, gin.H{"project": project})
}
// ListVariants handles GET /projects/:id/variants
// Returns all variant sub-projects for a given base project.
func (h *IACEHandler) ListVariants(c *gin.Context) {
parentID, err := uuid.Parse(c.Param("id"))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid project ID"})
return
}
variants, err := h.store.ListVariants(c.Request.Context(), parentID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if variants == nil {
variants = []iace.Project{}
}
c.JSON(http.StatusOK, iace.ProjectListResponse{
Projects: variants,
Total: len(variants),
})
}
// GetVariantGap handles GET /projects/:id/variant-gap
// Returns a gap analysis comparing a variant against its base project.
func (h *IACEHandler) GetVariantGap(c *gin.Context) {
variantID, err := uuid.Parse(c.Param("id"))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid project ID"})
return
}
gap, err := h.store.GetVariantGap(c.Request.Context(), variantID)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gap)
}
+3
View File
@@ -371,6 +371,9 @@ func registerIACERoutes(v1 *gin.RouterGroup, h *handlers.IACEHandler) {
iaceRoutes.PUT("/projects/:id", h.UpdateProject)
iaceRoutes.DELETE("/projects/:id", h.ArchiveProject)
iaceRoutes.POST("/projects/:id/init-from-profile", h.InitFromProfile)
iaceRoutes.POST("/projects/:id/variants", h.CreateVariant)
iaceRoutes.GET("/projects/:id/variants", h.ListVariants)
iaceRoutes.GET("/projects/:id/variant-gap", h.GetVariantGap)
iaceRoutes.POST("/projects/:id/completeness-check", h.CheckCompleteness)
iaceRoutes.POST("/projects/:id/components", h.CreateComponent)
iaceRoutes.GET("/projects/:id/components", h.ListComponents)
@@ -12,6 +12,7 @@ import (
// CreateProjectRequest is the API request for creating a new IACE project
type CreateProjectRequest struct {
ParentProjectID *uuid.UUID `json:"parent_project_id,omitempty"`
MachineName string `json:"machine_name" binding:"required"`
MachineType string `json:"machine_type" binding:"required"`
Manufacturer string `json:"manufacturer" binding:"required"`
@@ -199,6 +200,28 @@ type ValidateMitigationHierarchyResponse struct {
Warnings []string `json:"warnings,omitempty"`
}
// VariantGap compares a variant project against its base project
type VariantGap struct {
BaseProject ProjectSummary `json:"base_project"`
Variant ProjectSummary `json:"variant"`
Gap GapDetail `json:"gap"`
}
// ProjectSummary is a lightweight project view for gap comparisons
type ProjectSummary struct {
ID uuid.UUID `json:"id"`
Name string `json:"name"`
HazardCount int `json:"hazard_count"`
MeasureCount int `json:"measure_count"`
}
// GapDetail describes the delta between variant and base project
type GapDetail struct {
AdditionalHazards int `json:"additional_hazards"`
AdditionalMeasures int `json:"additional_measures"`
CategoriesAffected []string `json:"categories_affected"`
}
// CompletenessGate represents a single gate in the project completeness checklist
type CompletenessGate struct {
ID string `json:"id"`
@@ -15,6 +15,7 @@ import (
type Project struct {
ID uuid.UUID `json:"id"`
TenantID uuid.UUID `json:"tenant_id"`
ParentProjectID *uuid.UUID `json:"parent_project_id,omitempty"`
MachineName string `json:"machine_name"`
MachineType string `json:"machine_type"`
Manufacturer string `json:"manufacturer"`
+159 -10
View File
@@ -19,6 +19,7 @@ func (s *Store) CreateProject(ctx context.Context, tenantID uuid.UUID, req Creat
project := &Project{
ID: uuid.New(),
TenantID: tenantID,
ParentProjectID: req.ParentProjectID,
MachineName: req.MachineName,
MachineType: req.MachineType,
Manufacturer: req.Manufacturer,
@@ -33,18 +34,19 @@ func (s *Store) CreateProject(ctx context.Context, tenantID uuid.UUID, req Creat
_, err := s.pool.Exec(ctx, `
INSERT INTO iace_projects (
id, tenant_id, machine_name, machine_type, manufacturer,
id, tenant_id, parent_project_id, machine_name, machine_type, manufacturer,
description, narrative_text, status, ce_marking_target,
completeness_score, risk_summary, triggered_regulations, metadata,
created_at, updated_at, archived_at
) VALUES (
$1, $2, $3, $4, $5,
$6, $7, $8, $9,
$10, $11, $12, $13,
$14, $15, $16
$1, $2, $3, $4, $5, $6,
$7, $8, $9, $10,
$11, $12, $13, $14,
$15, $16, $17
)
`,
project.ID, project.TenantID, project.MachineName, project.MachineType, project.Manufacturer,
project.ID, project.TenantID, project.ParentProjectID,
project.MachineName, project.MachineType, project.Manufacturer,
project.Description, project.NarrativeText, string(project.Status), project.CEMarkingTarget,
project.CompletenessScore, nil, project.TriggeredRegulations, project.Metadata,
project.CreatedAt, project.UpdatedAt, project.ArchivedAt,
@@ -64,13 +66,13 @@ func (s *Store) GetProject(ctx context.Context, id uuid.UUID) (*Project, error)
err := s.pool.QueryRow(ctx, `
SELECT
id, tenant_id, machine_name, machine_type, manufacturer,
id, tenant_id, parent_project_id, machine_name, machine_type, manufacturer,
description, narrative_text, status, ce_marking_target,
completeness_score, risk_summary, triggered_regulations, metadata,
created_at, updated_at, archived_at
FROM iace_projects WHERE id = $1
`, id).Scan(
&p.ID, &p.TenantID, &p.MachineName, &p.MachineType, &p.Manufacturer,
&p.ID, &p.TenantID, &p.ParentProjectID, &p.MachineName, &p.MachineType, &p.Manufacturer,
&p.Description, &p.NarrativeText, &status, &p.CEMarkingTarget,
&p.CompletenessScore, &riskSummary, &triggeredRegulations, &metadata,
&p.CreatedAt, &p.UpdatedAt, &p.ArchivedAt,
@@ -94,7 +96,7 @@ func (s *Store) GetProject(ctx context.Context, id uuid.UUID) (*Project, error)
func (s *Store) ListProjects(ctx context.Context, tenantID uuid.UUID) ([]Project, error) {
rows, err := s.pool.Query(ctx, `
SELECT
id, tenant_id, machine_name, machine_type, manufacturer,
id, tenant_id, parent_project_id, machine_name, machine_type, manufacturer,
description, narrative_text, status, ce_marking_target,
completeness_score, risk_summary, triggered_regulations, metadata,
created_at, updated_at, archived_at
@@ -113,7 +115,7 @@ func (s *Store) ListProjects(ctx context.Context, tenantID uuid.UUID) ([]Project
var riskSummary, triggeredRegulations, metadata []byte
err := rows.Scan(
&p.ID, &p.TenantID, &p.MachineName, &p.MachineType, &p.Manufacturer,
&p.ID, &p.TenantID, &p.ParentProjectID, &p.MachineName, &p.MachineType, &p.Manufacturer,
&p.Description, &p.NarrativeText, &status, &p.CEMarkingTarget,
&p.CompletenessScore, &riskSummary, &triggeredRegulations, &metadata,
&p.CreatedAt, &p.UpdatedAt, &p.ArchivedAt,
@@ -231,3 +233,150 @@ func (s *Store) UpdateProjectCompleteness(ctx context.Context, id uuid.UUID, sco
return nil
}
// ListVariants returns all variant sub-projects for a given parent project
func (s *Store) ListVariants(ctx context.Context, parentID uuid.UUID) ([]Project, error) {
rows, err := s.pool.Query(ctx, `
SELECT
id, tenant_id, parent_project_id, machine_name, machine_type, manufacturer,
description, narrative_text, status, ce_marking_target,
completeness_score, risk_summary, triggered_regulations, metadata,
created_at, updated_at, archived_at
FROM iace_projects WHERE parent_project_id = $1
ORDER BY created_at DESC
`, parentID)
if err != nil {
return nil, fmt.Errorf("list variants: %w", err)
}
defer rows.Close()
var variants []Project
for rows.Next() {
var p Project
var status string
var riskSummary, triggeredRegulations, metadata []byte
err := rows.Scan(
&p.ID, &p.TenantID, &p.ParentProjectID, &p.MachineName, &p.MachineType, &p.Manufacturer,
&p.Description, &p.NarrativeText, &status, &p.CEMarkingTarget,
&p.CompletenessScore, &riskSummary, &triggeredRegulations, &metadata,
&p.CreatedAt, &p.UpdatedAt, &p.ArchivedAt,
)
if err != nil {
return nil, fmt.Errorf("list variants scan: %w", err)
}
p.Status = ProjectStatus(status)
json.Unmarshal(riskSummary, &p.RiskSummary)
json.Unmarshal(triggeredRegulations, &p.TriggeredRegulations)
json.Unmarshal(metadata, &p.Metadata)
variants = append(variants, p)
}
return variants, nil
}
// GetVariantGap computes the gap analysis between a variant and its base project.
// It counts hazards and measures in each, and returns the categories affected.
func (s *Store) GetVariantGap(ctx context.Context, variantID uuid.UUID) (*VariantGap, error) {
variant, err := s.GetProject(ctx, variantID)
if err != nil {
return nil, fmt.Errorf("get variant: %w", err)
}
if variant == nil {
return nil, fmt.Errorf("variant project not found")
}
if variant.ParentProjectID == nil {
return nil, fmt.Errorf("project is not a variant (no parent_project_id)")
}
parent, err := s.GetProject(ctx, *variant.ParentProjectID)
if err != nil {
return nil, fmt.Errorf("get parent: %w", err)
}
if parent == nil {
return nil, fmt.Errorf("parent project not found")
}
// Count hazards and measures for both projects
parentHazards, parentMeasures, err := s.countHazardsAndMeasures(ctx, parent.ID)
if err != nil {
return nil, fmt.Errorf("count parent stats: %w", err)
}
variantHazards, variantMeasures, err := s.countHazardsAndMeasures(ctx, variant.ID)
if err != nil {
return nil, fmt.Errorf("count variant stats: %w", err)
}
// Get unique hazard categories in the variant
categories, err := s.getVariantHazardCategories(ctx, variant.ID)
if err != nil {
return nil, fmt.Errorf("get variant categories: %w", err)
}
return &VariantGap{
BaseProject: ProjectSummary{
ID: parent.ID,
Name: parent.MachineName,
HazardCount: parentHazards,
MeasureCount: parentMeasures,
},
Variant: ProjectSummary{
ID: variant.ID,
Name: variant.MachineName,
HazardCount: variantHazards,
MeasureCount: variantMeasures,
},
Gap: GapDetail{
AdditionalHazards: variantHazards,
AdditionalMeasures: variantMeasures,
CategoriesAffected: categories,
},
}, nil
}
// countHazardsAndMeasures returns (hazardCount, measureCount) for a project
func (s *Store) countHazardsAndMeasures(ctx context.Context, projectID uuid.UUID) (int, int, error) {
var hazardCount int
err := s.pool.QueryRow(ctx,
`SELECT COUNT(*) FROM iace_hazards WHERE project_id = $1`, projectID,
).Scan(&hazardCount)
if err != nil {
return 0, 0, err
}
var measureCount int
err = s.pool.QueryRow(ctx, `
SELECT COUNT(*) FROM iace_mitigations m
JOIN iace_hazards h ON m.hazard_id = h.id
WHERE h.project_id = $1
`, projectID).Scan(&measureCount)
if err != nil {
return 0, 0, err
}
return hazardCount, measureCount, nil
}
// getVariantHazardCategories returns distinct hazard categories for a project
func (s *Store) getVariantHazardCategories(ctx context.Context, projectID uuid.UUID) ([]string, error) {
rows, err := s.pool.Query(ctx,
`SELECT DISTINCT category FROM iace_hazards WHERE project_id = $1 ORDER BY category`,
projectID,
)
if err != nil {
return nil, err
}
defer rows.Close()
var categories []string
for rows.Next() {
var cat string
if err := rows.Scan(&cat); err != nil {
return nil, err
}
categories = append(categories, cat)
}
return categories, nil
}