feat(sdk): Audit-Dashboard + RBAC-Admin Frontends, UCCA/Go Cleanup
Some checks failed
CI / go-lint (push) Has been skipped
CI / python-lint (push) Has been skipped
CI / nodejs-lint (push) Has been skipped
CI / test-go-ai-compliance (push) Failing after 33s
CI / test-python-backend-compliance (push) Successful in 32s
CI / test-python-document-crawler (push) Successful in 18s
CI / test-python-dsms-gateway (push) Successful in 16s
Some checks failed
CI / go-lint (push) Has been skipped
CI / python-lint (push) Has been skipped
CI / nodejs-lint (push) Has been skipped
CI / test-go-ai-compliance (push) Failing after 33s
CI / test-python-backend-compliance (push) Successful in 32s
CI / test-python-document-crawler (push) Successful in 18s
CI / test-python-dsms-gateway (push) Successful in 16s
- Remove 5 unused UCCA routes (wizard, stats, dsb-pool) from Go main.go - Delete 64 deprecated Go handlers (DSGVO, Vendors, Incidents, Drafting) - Delete legacy proxy routes (dsgvo, vendors) - Add LLM Audit Dashboard (3 tabs: Log, Nutzung, Compliance) with export - Add RBAC Admin UI (5 tabs: Mandanten, Namespaces, Rollen, Benutzer, LLM-Policies) - Add proxy routes for audit-llm and rbac to Go backend - Add Workshop, Portfolio, Roadmap proxy routes and frontends - Add LLM Audit + RBAC Admin to SDKSidebar Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -12,17 +12,14 @@ import (
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/api/handlers"
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/audit"
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/config"
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/dsgvo"
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/llm"
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/rbac"
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/academy"
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/incidents"
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/roadmap"
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/training"
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/ucca"
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/whistleblower"
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/iace"
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/vendor"
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/workshop"
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/portfolio"
|
||||
"github.com/gin-contrib/cors"
|
||||
@@ -59,7 +56,6 @@ func main() {
|
||||
// Initialize stores
|
||||
rbacStore := rbac.NewStore(pool)
|
||||
auditStore := audit.NewStore(pool)
|
||||
dsgvoStore := dsgvo.NewStore(pool)
|
||||
uccaStore := ucca.NewStore(pool)
|
||||
escalationStore := ucca.NewEscalationStore(pool)
|
||||
corpusVersionStore := ucca.NewCorpusVersionStore(pool)
|
||||
@@ -68,8 +64,6 @@ func main() {
|
||||
portfolioStore := portfolio.NewStore(pool)
|
||||
academyStore := academy.NewStore(pool)
|
||||
whistleblowerStore := whistleblower.NewStore(pool)
|
||||
incidentStore := incidents.NewStore(pool)
|
||||
vendorStore := vendor.NewStore(pool)
|
||||
iaceStore := iace.NewStore(pool)
|
||||
trainingStore := training.NewStore(pool)
|
||||
|
||||
@@ -108,17 +102,13 @@ func main() {
|
||||
rbacHandlers := handlers.NewRBACHandlers(rbacStore, rbacService, policyEngine)
|
||||
llmHandlers := handlers.NewLLMHandlers(accessGate, providerRegistry, piiDetector, auditStore, trailBuilder)
|
||||
auditHandlers := handlers.NewAuditHandlers(auditStore, exporter)
|
||||
dsgvoHandlers := handlers.NewDSGVOHandlers(dsgvoStore)
|
||||
uccaHandlers := handlers.NewUCCAHandlers(uccaStore, escalationStore, providerRegistry)
|
||||
escalationHandlers := handlers.NewEscalationHandlers(escalationStore, uccaStore)
|
||||
roadmapHandlers := handlers.NewRoadmapHandlers(roadmapStore)
|
||||
workshopHandlers := handlers.NewWorkshopHandlers(workshopStore)
|
||||
portfolioHandlers := handlers.NewPortfolioHandlers(portfolioStore)
|
||||
draftingHandlers := handlers.NewDraftingHandlers(accessGate, providerRegistry, piiDetector, auditStore, trailBuilder)
|
||||
academyHandlers := handlers.NewAcademyHandlers(academyStore, trainingStore)
|
||||
whistleblowerHandlers := handlers.NewWhistleblowerHandlers(whistleblowerStore)
|
||||
incidentHandlers := handlers.NewIncidentHandlers(incidentStore)
|
||||
vendorHandlers := handlers.NewVendorHandlers(vendorStore)
|
||||
iaceHandler := handlers.NewIACEHandler(iaceStore)
|
||||
trainingHandlers := handlers.NewTrainingHandlers(trainingStore, contentGenerator)
|
||||
ragHandlers := handlers.NewRAGHandlers(corpusVersionStore)
|
||||
@@ -245,74 +235,6 @@ func main() {
|
||||
auditRoutes.GET("/export/compliance", auditHandlers.ExportComplianceReport)
|
||||
}
|
||||
|
||||
// DSGVO routes (Art. 30, 32, 35, 15-22 DSGVO)
|
||||
dsgvoRoutes := v1.Group("/dsgvo")
|
||||
{
|
||||
// Statistics
|
||||
dsgvoRoutes.GET("/stats", dsgvoHandlers.GetStats)
|
||||
|
||||
// DEPRECATED: VVT routes - frontend uses backend-compliance proxy instead
|
||||
// VVT - Verarbeitungsverzeichnis (Art. 30)
|
||||
vvt := dsgvoRoutes.Group("/processing-activities")
|
||||
{
|
||||
vvt.GET("", dsgvoHandlers.ListProcessingActivities)
|
||||
vvt.GET("/:id", dsgvoHandlers.GetProcessingActivity)
|
||||
vvt.POST("", dsgvoHandlers.CreateProcessingActivity)
|
||||
vvt.PUT("/:id", dsgvoHandlers.UpdateProcessingActivity)
|
||||
vvt.DELETE("/:id", dsgvoHandlers.DeleteProcessingActivity)
|
||||
}
|
||||
|
||||
// TOM - Technische und Organisatorische Maßnahmen (Art. 32)
|
||||
// DEPRECATED: TOM is now managed by backend-compliance (Python).
|
||||
// Use: GET/POST /api/compliance/tom/state, /tom/measures, /tom/stats, /tom/export
|
||||
tom := dsgvoRoutes.Group("/tom")
|
||||
{
|
||||
tom.GET("", dsgvoHandlers.ListTOMs)
|
||||
tom.GET("/:id", dsgvoHandlers.GetTOM)
|
||||
tom.POST("", dsgvoHandlers.CreateTOM)
|
||||
}
|
||||
|
||||
// DSR - Data Subject Requests / Betroffenenrechte (Art. 15-22)
|
||||
// DEPRECATED: DSR is now managed by backend-compliance (Python).
|
||||
// Use: GET/POST/PUT /api/compliance/dsr/* on backend-compliance:8002
|
||||
dsr := dsgvoRoutes.Group("/dsr")
|
||||
{
|
||||
dsr.GET("", dsgvoHandlers.ListDSRs)
|
||||
dsr.GET("/:id", dsgvoHandlers.GetDSR)
|
||||
dsr.POST("", dsgvoHandlers.CreateDSR)
|
||||
dsr.PUT("/:id", dsgvoHandlers.UpdateDSR)
|
||||
}
|
||||
|
||||
// Retention Policies - Löschfristen (Art. 17)
|
||||
retention := dsgvoRoutes.Group("/retention-policies")
|
||||
{
|
||||
retention.GET("", dsgvoHandlers.ListRetentionPolicies)
|
||||
retention.POST("", dsgvoHandlers.CreateRetentionPolicy)
|
||||
}
|
||||
|
||||
// DSFA - Datenschutz-Folgenabschätzung (Art. 35)
|
||||
// DEPRECATED: DSFA migrated to backend-compliance (Python/FastAPI).
|
||||
// Use backend-compliance /api/compliance/dsfa/* instead.
|
||||
dsfa := dsgvoRoutes.Group("/dsfa")
|
||||
{
|
||||
dsfa.GET("", dsgvoHandlers.ListDSFAs)
|
||||
dsfa.GET("/:id", dsgvoHandlers.GetDSFA)
|
||||
dsfa.POST("", dsgvoHandlers.CreateDSFA)
|
||||
dsfa.PUT("/:id", dsgvoHandlers.UpdateDSFA)
|
||||
dsfa.DELETE("/:id", dsgvoHandlers.DeleteDSFA)
|
||||
dsfa.GET("/:id/export", dsgvoHandlers.ExportDSFA)
|
||||
}
|
||||
|
||||
// Export routes
|
||||
exports := dsgvoRoutes.Group("/export")
|
||||
{
|
||||
exports.GET("/vvt", dsgvoHandlers.ExportVVT) // DEPRECATED: use backend-compliance /vvt/export?format=csv
|
||||
exports.GET("/tom", dsgvoHandlers.ExportTOM) // DEPRECATED: use backend-compliance /tom/export?format=csv
|
||||
exports.GET("/dsr", dsgvoHandlers.ExportDSR) // DEPRECATED: use backend-compliance /dsr/export?format=csv
|
||||
exports.GET("/retention", dsgvoHandlers.ExportRetentionPolicies)
|
||||
}
|
||||
}
|
||||
|
||||
// UCCA routes - Use-Case Compliance & Feasibility Advisor
|
||||
uccaRoutes := v1.Group("/ucca")
|
||||
{
|
||||
@@ -338,16 +260,7 @@ func main() {
|
||||
// Export
|
||||
uccaRoutes.GET("/export/:id", uccaHandlers.Export)
|
||||
|
||||
// Statistics
|
||||
uccaRoutes.GET("/stats", uccaHandlers.GetStats)
|
||||
|
||||
// Wizard routes - Legal Assistant integrated
|
||||
uccaRoutes.GET("/wizard/schema", uccaHandlers.GetWizardSchema)
|
||||
uccaRoutes.POST("/wizard/ask", uccaHandlers.AskWizardQuestion)
|
||||
|
||||
// DEPRECATED: UCCA Escalation management (E0-E3 workflow)
|
||||
// Frontend uses Python backend-compliance escalation_routes.py (/api/compliance/escalations).
|
||||
// These UCCA-specific routes remain for assessment-review workflows only.
|
||||
// Escalation management (assessment-review workflows)
|
||||
uccaRoutes.GET("/escalations", escalationHandlers.ListEscalations)
|
||||
uccaRoutes.GET("/escalations/stats", escalationHandlers.GetEscalationStats)
|
||||
uccaRoutes.GET("/escalations/:id", escalationHandlers.GetEscalation)
|
||||
@@ -356,10 +269,6 @@ func main() {
|
||||
uccaRoutes.POST("/escalations/:id/review", escalationHandlers.StartReview)
|
||||
uccaRoutes.POST("/escalations/:id/decide", escalationHandlers.DecideEscalation)
|
||||
|
||||
// DEPRECATED: DSB Pool management — see note above
|
||||
uccaRoutes.GET("/dsb-pool", escalationHandlers.ListDSBPool)
|
||||
uccaRoutes.POST("/dsb-pool", escalationHandlers.AddDSBPoolMember)
|
||||
|
||||
// Obligations framework (v2 with TOM mapping)
|
||||
obligationsHandlers.RegisterRoutes(uccaRoutes)
|
||||
}
|
||||
@@ -477,15 +386,6 @@ func main() {
|
||||
portfolioRoutes.POST("/compare", portfolioHandlers.ComparePortfolios)
|
||||
}
|
||||
|
||||
// Drafting Engine routes - Compliance Document Drafting & Validation
|
||||
draftingRoutes := v1.Group("/drafting")
|
||||
draftingRoutes.Use(rbacMiddleware.RequireLLMAccess())
|
||||
{
|
||||
draftingRoutes.POST("/draft", draftingHandlers.DraftDocument)
|
||||
draftingRoutes.POST("/validate", draftingHandlers.ValidateDocument)
|
||||
draftingRoutes.GET("/history", draftingHandlers.GetDraftHistory)
|
||||
}
|
||||
|
||||
// Academy routes - E-Learning / Compliance Training
|
||||
academyRoutes := v1.Group("/academy")
|
||||
{
|
||||
@@ -616,82 +516,6 @@ func main() {
|
||||
whistleblowerRoutes.GET("/stats", whistleblowerHandlers.GetStatistics)
|
||||
}
|
||||
|
||||
// DEPRECATED: Incidents routes — Python backend is now Source of Truth.
|
||||
// Frontend proxies to backend-compliance:8002/api/compliance/incidents/*
|
||||
// These Go routes remain registered but should not be extended.
|
||||
incidentRoutes := v1.Group("/incidents")
|
||||
{
|
||||
// Incident CRUD
|
||||
incidentRoutes.POST("", incidentHandlers.CreateIncident)
|
||||
incidentRoutes.GET("", incidentHandlers.ListIncidents)
|
||||
incidentRoutes.GET("/:id", incidentHandlers.GetIncident)
|
||||
incidentRoutes.PUT("/:id", incidentHandlers.UpdateIncident)
|
||||
incidentRoutes.DELETE("/:id", incidentHandlers.DeleteIncident)
|
||||
|
||||
// Risk Assessment
|
||||
incidentRoutes.POST("/:id/assess-risk", incidentHandlers.AssessRisk)
|
||||
|
||||
// Authority Notification (Art. 33)
|
||||
incidentRoutes.POST("/:id/notify-authority", incidentHandlers.SubmitAuthorityNotification)
|
||||
|
||||
// Data Subject Notification (Art. 34)
|
||||
incidentRoutes.POST("/:id/notify-subjects", incidentHandlers.NotifyDataSubjects)
|
||||
|
||||
// Measures
|
||||
incidentRoutes.POST("/:id/measures", incidentHandlers.AddMeasure)
|
||||
incidentRoutes.PUT("/:id/measures/:measureId", incidentHandlers.UpdateMeasure)
|
||||
incidentRoutes.POST("/:id/measures/:measureId/complete", incidentHandlers.CompleteMeasure)
|
||||
|
||||
// Timeline
|
||||
incidentRoutes.POST("/:id/timeline", incidentHandlers.AddTimelineEntry)
|
||||
|
||||
// Lifecycle
|
||||
incidentRoutes.POST("/:id/close", incidentHandlers.CloseIncident)
|
||||
|
||||
// Statistics
|
||||
incidentRoutes.GET("/stats", incidentHandlers.GetStatistics)
|
||||
}
|
||||
|
||||
// DEPRECATED: Vendor Compliance routes — Python backend is now Source of Truth.
|
||||
// Frontend proxies to backend-compliance:8002/api/compliance/vendor-compliance/*
|
||||
// These Go routes remain registered but should not be extended.
|
||||
vendorRoutes := v1.Group("/vendors")
|
||||
{
|
||||
// Vendor CRUD
|
||||
vendorRoutes.POST("", vendorHandlers.CreateVendor)
|
||||
vendorRoutes.GET("", vendorHandlers.ListVendors)
|
||||
vendorRoutes.GET("/:id", vendorHandlers.GetVendor)
|
||||
vendorRoutes.PUT("/:id", vendorHandlers.UpdateVendor)
|
||||
vendorRoutes.DELETE("/:id", vendorHandlers.DeleteVendor)
|
||||
|
||||
// Contracts (AVV/DPA)
|
||||
vendorRoutes.POST("/contracts", vendorHandlers.CreateContract)
|
||||
vendorRoutes.GET("/contracts", vendorHandlers.ListContracts)
|
||||
vendorRoutes.GET("/contracts/:id", vendorHandlers.GetContract)
|
||||
vendorRoutes.PUT("/contracts/:id", vendorHandlers.UpdateContract)
|
||||
vendorRoutes.DELETE("/contracts/:id", vendorHandlers.DeleteContract)
|
||||
|
||||
// Findings
|
||||
vendorRoutes.POST("/findings", vendorHandlers.CreateFinding)
|
||||
vendorRoutes.GET("/findings", vendorHandlers.ListFindings)
|
||||
vendorRoutes.GET("/findings/:id", vendorHandlers.GetFinding)
|
||||
vendorRoutes.PUT("/findings/:id", vendorHandlers.UpdateFinding)
|
||||
vendorRoutes.POST("/findings/:id/resolve", vendorHandlers.ResolveFinding)
|
||||
|
||||
// Control Instances
|
||||
vendorRoutes.POST("/controls", vendorHandlers.UpsertControlInstance)
|
||||
vendorRoutes.GET("/controls", vendorHandlers.ListControlInstances)
|
||||
|
||||
// Templates
|
||||
vendorRoutes.GET("/templates", vendorHandlers.ListTemplates)
|
||||
vendorRoutes.GET("/templates/:templateId", vendorHandlers.GetTemplate)
|
||||
vendorRoutes.POST("/templates", vendorHandlers.CreateTemplate)
|
||||
vendorRoutes.POST("/templates/:templateId/apply", vendorHandlers.ApplyTemplate)
|
||||
|
||||
// Statistics
|
||||
vendorRoutes.GET("/stats", vendorHandlers.GetStatistics)
|
||||
}
|
||||
|
||||
// IACE routes - Industrial AI Compliance Engine (CE-Risikobeurteilung SW/FW/KI)
|
||||
iaceRoutes := v1.Group("/iace")
|
||||
{
|
||||
|
||||
@@ -1,336 +0,0 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/audit"
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/llm"
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/rbac"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// DraftingHandlers handles Drafting Engine API endpoints
|
||||
type DraftingHandlers struct {
|
||||
accessGate *llm.AccessGate
|
||||
registry *llm.ProviderRegistry
|
||||
piiDetector *llm.PIIDetector
|
||||
auditStore *audit.Store
|
||||
trailBuilder *audit.TrailBuilder
|
||||
}
|
||||
|
||||
// NewDraftingHandlers creates new Drafting Engine handlers
|
||||
func NewDraftingHandlers(
|
||||
accessGate *llm.AccessGate,
|
||||
registry *llm.ProviderRegistry,
|
||||
piiDetector *llm.PIIDetector,
|
||||
auditStore *audit.Store,
|
||||
trailBuilder *audit.TrailBuilder,
|
||||
) *DraftingHandlers {
|
||||
return &DraftingHandlers{
|
||||
accessGate: accessGate,
|
||||
registry: registry,
|
||||
piiDetector: piiDetector,
|
||||
auditStore: auditStore,
|
||||
trailBuilder: trailBuilder,
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Request/Response Types
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// DraftDocumentRequest represents a request to generate a compliance document draft
|
||||
type DraftDocumentRequest struct {
|
||||
DocumentType string `json:"document_type" binding:"required"`
|
||||
ScopeLevel string `json:"scope_level" binding:"required"`
|
||||
Context map[string]interface{} `json:"context"`
|
||||
Instructions string `json:"instructions"`
|
||||
Model string `json:"model"`
|
||||
}
|
||||
|
||||
// ValidateDocumentRequest represents a request to validate document consistency
|
||||
type ValidateDocumentRequest struct {
|
||||
DocumentType string `json:"document_type" binding:"required"`
|
||||
DraftContent string `json:"draft_content"`
|
||||
ValidationContext map[string]interface{} `json:"validation_context"`
|
||||
Model string `json:"model"`
|
||||
}
|
||||
|
||||
// DraftHistoryEntry represents a single audit trail entry for drafts
|
||||
type DraftHistoryEntry struct {
|
||||
ID string `json:"id"`
|
||||
UserID string `json:"user_id"`
|
||||
TenantID string `json:"tenant_id"`
|
||||
DocumentType string `json:"document_type"`
|
||||
ScopeLevel string `json:"scope_level"`
|
||||
Operation string `json:"operation"`
|
||||
ConstraintsRespected bool `json:"constraints_respected"`
|
||||
TokensUsed int `json:"tokens_used"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Handlers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// DraftDocument handles document draft generation via LLM with constraint validation
|
||||
func (h *DraftingHandlers) DraftDocument(c *gin.Context) {
|
||||
var req DraftDocumentRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
userID := rbac.GetUserID(c)
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
namespaceID := rbac.GetNamespaceID(c)
|
||||
|
||||
if userID == uuid.Nil || tenantID == uuid.Nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "authentication required"})
|
||||
return
|
||||
}
|
||||
|
||||
// Validate scope level
|
||||
validLevels := map[string]bool{"L1": true, "L2": true, "L3": true, "L4": true}
|
||||
if !validLevels[req.ScopeLevel] {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid scope_level, must be L1-L4"})
|
||||
return
|
||||
}
|
||||
|
||||
// Validate document type
|
||||
validTypes := map[string]bool{
|
||||
"vvt": true, "tom": true, "dsfa": true, "dsi": true, "lf": true,
|
||||
"av_vertrag": true, "betroffenenrechte": true, "einwilligung": true,
|
||||
"daten_transfer": true, "datenpannen": true, "vertragsmanagement": true,
|
||||
"schulung": true, "audit_log": true, "risikoanalyse": true,
|
||||
"notfallplan": true, "zertifizierung": true, "datenschutzmanagement": true,
|
||||
"iace_ce_assessment": true,
|
||||
}
|
||||
if !validTypes[req.DocumentType] {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid document_type"})
|
||||
return
|
||||
}
|
||||
|
||||
// Build system prompt for drafting
|
||||
systemPrompt := fmt.Sprintf(
|
||||
`Du bist ein DSGVO-Compliance-Experte. Erstelle einen strukturierten Entwurf fuer Dokument "%s" auf Level %s.
|
||||
Antworte NUR im JSON-Format mit einem "sections" Array.
|
||||
Jede Section hat: id, title, content, schemaField.
|
||||
Halte die Tiefe strikt am vorgegebenen Level.
|
||||
Markiere fehlende Informationen mit [PLATZHALTER: Beschreibung].
|
||||
Sprache: Deutsch.`,
|
||||
req.DocumentType, req.ScopeLevel,
|
||||
)
|
||||
|
||||
userPrompt := "Erstelle den Dokumententwurf."
|
||||
if req.Instructions != "" {
|
||||
userPrompt = req.Instructions
|
||||
}
|
||||
|
||||
// Detect PII in context
|
||||
contextStr := fmt.Sprintf("%v", req.Context)
|
||||
dataCategories := h.piiDetector.DetectDataCategories(contextStr)
|
||||
|
||||
// Process through access gate
|
||||
chatReq := &llm.ChatRequest{
|
||||
Model: req.Model,
|
||||
Messages: []llm.Message{
|
||||
{Role: "system", Content: systemPrompt},
|
||||
{Role: "user", Content: userPrompt},
|
||||
},
|
||||
MaxTokens: 16384,
|
||||
Temperature: 0.15,
|
||||
}
|
||||
|
||||
gatedReq, err := h.accessGate.ProcessChatRequest(
|
||||
c.Request.Context(),
|
||||
userID, tenantID, namespaceID,
|
||||
chatReq, dataCategories,
|
||||
)
|
||||
if err != nil {
|
||||
h.logDraftAudit(c, userID, tenantID, req.DocumentType, req.ScopeLevel, "draft", false, 0, err.Error())
|
||||
c.JSON(http.StatusForbidden, gin.H{
|
||||
"error": "access_denied",
|
||||
"message": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Execute the request
|
||||
resp, err := h.accessGate.ExecuteChat(c.Request.Context(), gatedReq)
|
||||
if err != nil {
|
||||
h.logDraftAudit(c, userID, tenantID, req.DocumentType, req.ScopeLevel, "draft", false, 0, err.Error())
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"error": "llm_error",
|
||||
"message": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
tokensUsed := 0
|
||||
if resp.Usage.TotalTokens > 0 {
|
||||
tokensUsed = resp.Usage.TotalTokens
|
||||
}
|
||||
|
||||
// Log successful draft
|
||||
h.logDraftAudit(c, userID, tenantID, req.DocumentType, req.ScopeLevel, "draft", true, tokensUsed, "")
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"document_type": req.DocumentType,
|
||||
"scope_level": req.ScopeLevel,
|
||||
"content": resp.Message.Content,
|
||||
"model": resp.Model,
|
||||
"provider": resp.Provider,
|
||||
"tokens_used": tokensUsed,
|
||||
"pii_detected": gatedReq.PIIDetected,
|
||||
})
|
||||
}
|
||||
|
||||
// ValidateDocument handles document cross-consistency validation
|
||||
func (h *DraftingHandlers) ValidateDocument(c *gin.Context) {
|
||||
var req ValidateDocumentRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
userID := rbac.GetUserID(c)
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
namespaceID := rbac.GetNamespaceID(c)
|
||||
|
||||
if userID == uuid.Nil || tenantID == uuid.Nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "authentication required"})
|
||||
return
|
||||
}
|
||||
|
||||
// Build validation prompt
|
||||
systemPrompt := `Du bist ein DSGVO-Compliance-Validator. Pruefe die Konsistenz und Vollstaendigkeit.
|
||||
Antworte NUR im JSON-Format:
|
||||
{
|
||||
"passed": boolean,
|
||||
"errors": [{"id": string, "severity": "error", "title": string, "description": string, "documentType": string, "legalReference": string}],
|
||||
"warnings": [{"id": string, "severity": "warning", "title": string, "description": string}],
|
||||
"suggestions": [{"id": string, "severity": "suggestion", "title": string, "description": string, "suggestion": string}]
|
||||
}`
|
||||
|
||||
validationPrompt := fmt.Sprintf("Validiere Dokument '%s'.\nInhalt:\n%s\nKontext:\n%v",
|
||||
req.DocumentType, req.DraftContent, req.ValidationContext)
|
||||
|
||||
// Detect PII
|
||||
dataCategories := h.piiDetector.DetectDataCategories(req.DraftContent)
|
||||
|
||||
chatReq := &llm.ChatRequest{
|
||||
Model: req.Model,
|
||||
Messages: []llm.Message{
|
||||
{Role: "system", Content: systemPrompt},
|
||||
{Role: "user", Content: validationPrompt},
|
||||
},
|
||||
MaxTokens: 8192,
|
||||
Temperature: 0.1,
|
||||
}
|
||||
|
||||
gatedReq, err := h.accessGate.ProcessChatRequest(
|
||||
c.Request.Context(),
|
||||
userID, tenantID, namespaceID,
|
||||
chatReq, dataCategories,
|
||||
)
|
||||
if err != nil {
|
||||
h.logDraftAudit(c, userID, tenantID, req.DocumentType, "", "validate", false, 0, err.Error())
|
||||
c.JSON(http.StatusForbidden, gin.H{
|
||||
"error": "access_denied",
|
||||
"message": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := h.accessGate.ExecuteChat(c.Request.Context(), gatedReq)
|
||||
if err != nil {
|
||||
h.logDraftAudit(c, userID, tenantID, req.DocumentType, "", "validate", false, 0, err.Error())
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"error": "llm_error",
|
||||
"message": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
tokensUsed := 0
|
||||
if resp.Usage.TotalTokens > 0 {
|
||||
tokensUsed = resp.Usage.TotalTokens
|
||||
}
|
||||
|
||||
h.logDraftAudit(c, userID, tenantID, req.DocumentType, "", "validate", true, tokensUsed, "")
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"document_type": req.DocumentType,
|
||||
"validation": resp.Message.Content,
|
||||
"model": resp.Model,
|
||||
"provider": resp.Provider,
|
||||
"tokens_used": tokensUsed,
|
||||
"pii_detected": gatedReq.PIIDetected,
|
||||
})
|
||||
}
|
||||
|
||||
// GetDraftHistory returns the audit trail of all drafting operations for a tenant
|
||||
func (h *DraftingHandlers) GetDraftHistory(c *gin.Context) {
|
||||
userID := rbac.GetUserID(c)
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
|
||||
if userID == uuid.Nil || tenantID == uuid.Nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "authentication required"})
|
||||
return
|
||||
}
|
||||
|
||||
// Query audit store for drafting operations
|
||||
entries, _, err := h.auditStore.QueryGeneralAuditEntries(c.Request.Context(), &audit.GeneralAuditFilter{
|
||||
TenantID: tenantID,
|
||||
ResourceType: "compliance_document",
|
||||
Limit: 50,
|
||||
})
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to query draft history"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"history": entries,
|
||||
"total": len(entries),
|
||||
})
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Audit Logging
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func (h *DraftingHandlers) logDraftAudit(
|
||||
c *gin.Context,
|
||||
userID, tenantID uuid.UUID,
|
||||
documentType, scopeLevel, operation string,
|
||||
constraintsRespected bool,
|
||||
tokensUsed int,
|
||||
errorMsg string,
|
||||
) {
|
||||
newValues := map[string]any{
|
||||
"document_type": documentType,
|
||||
"scope_level": scopeLevel,
|
||||
"constraints_respected": constraintsRespected,
|
||||
"tokens_used": tokensUsed,
|
||||
}
|
||||
if errorMsg != "" {
|
||||
newValues["error"] = errorMsg
|
||||
}
|
||||
|
||||
entry := h.trailBuilder.NewGeneralEntry().
|
||||
WithTenant(tenantID).
|
||||
WithUser(userID).
|
||||
WithAction("drafting_engine." + operation).
|
||||
WithResource("compliance_document", nil).
|
||||
WithNewValues(newValues).
|
||||
WithClient(c.ClientIP(), c.GetHeader("User-Agent"))
|
||||
|
||||
go func() {
|
||||
entry.Save(c.Request.Context())
|
||||
}()
|
||||
}
|
||||
@@ -1,802 +0,0 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/dsgvo"
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/rbac"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// DSGVOHandlers handles DSGVO-related API endpoints
|
||||
type DSGVOHandlers struct {
|
||||
store *dsgvo.Store
|
||||
}
|
||||
|
||||
// NewDSGVOHandlers creates new DSGVO handlers
|
||||
func NewDSGVOHandlers(store *dsgvo.Store) *DSGVOHandlers {
|
||||
return &DSGVOHandlers{store: store}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// VVT - Verarbeitungsverzeichnis (Processing Activities)
|
||||
// DEPRECATED: VVT is now managed by backend-compliance (Python).
|
||||
// These handlers will be removed once all DSGVO sub-modules are consolidated.
|
||||
// ============================================================================
|
||||
|
||||
// ListProcessingActivities returns all processing activities for a tenant
|
||||
func (h *DSGVOHandlers) ListProcessingActivities(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
if tenantID == uuid.Nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "tenant ID required"})
|
||||
return
|
||||
}
|
||||
|
||||
var namespaceID *uuid.UUID
|
||||
if nsID := c.Query("namespace_id"); nsID != "" {
|
||||
if id, err := uuid.Parse(nsID); err == nil {
|
||||
namespaceID = &id
|
||||
}
|
||||
}
|
||||
|
||||
activities, err := h.store.ListProcessingActivities(c.Request.Context(), tenantID, namespaceID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"processing_activities": activities})
|
||||
}
|
||||
|
||||
// GetProcessingActivity returns a processing activity by ID
|
||||
func (h *DSGVOHandlers) GetProcessingActivity(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid ID"})
|
||||
return
|
||||
}
|
||||
|
||||
activity, err := h.store.GetProcessingActivity(c.Request.Context(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if activity == nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, activity)
|
||||
}
|
||||
|
||||
// CreateProcessingActivity creates a new processing activity
|
||||
func (h *DSGVOHandlers) CreateProcessingActivity(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
userID := rbac.GetUserID(c)
|
||||
if tenantID == uuid.Nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "tenant ID required"})
|
||||
return
|
||||
}
|
||||
|
||||
var activity dsgvo.ProcessingActivity
|
||||
if err := c.ShouldBindJSON(&activity); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
activity.TenantID = tenantID
|
||||
activity.CreatedBy = userID
|
||||
if activity.Status == "" {
|
||||
activity.Status = "draft"
|
||||
}
|
||||
|
||||
if err := h.store.CreateProcessingActivity(c.Request.Context(), &activity); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, activity)
|
||||
}
|
||||
|
||||
// UpdateProcessingActivity updates a processing activity
|
||||
func (h *DSGVOHandlers) UpdateProcessingActivity(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid ID"})
|
||||
return
|
||||
}
|
||||
|
||||
var activity dsgvo.ProcessingActivity
|
||||
if err := c.ShouldBindJSON(&activity); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
activity.ID = id
|
||||
if err := h.store.UpdateProcessingActivity(c.Request.Context(), &activity); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, activity)
|
||||
}
|
||||
|
||||
// DeleteProcessingActivity deletes a processing activity
|
||||
func (h *DSGVOHandlers) DeleteProcessingActivity(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid ID"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.store.DeleteProcessingActivity(c.Request.Context(), id); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"message": "deleted"})
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// TOM - Technische und Organisatorische Maßnahmen
|
||||
// ============================================================================
|
||||
// DEPRECATED: TOM is now managed by backend-compliance (Python).
|
||||
// These handlers remain for backwards compatibility but should not be used.
|
||||
// Use backend-compliance endpoints: GET/POST /api/compliance/tom/...
|
||||
|
||||
// ListTOMs returns all TOMs for a tenant
|
||||
// DEPRECATED: Use backend-compliance GET /api/compliance/tom/measures
|
||||
func (h *DSGVOHandlers) ListTOMs(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
if tenantID == uuid.Nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "tenant ID required"})
|
||||
return
|
||||
}
|
||||
|
||||
category := c.Query("category")
|
||||
|
||||
toms, err := h.store.ListTOMs(c.Request.Context(), tenantID, category)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"toms": toms, "categories": dsgvo.TOMCategories})
|
||||
}
|
||||
|
||||
// GetTOM returns a TOM by ID
|
||||
func (h *DSGVOHandlers) GetTOM(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid ID"})
|
||||
return
|
||||
}
|
||||
|
||||
tom, err := h.store.GetTOM(c.Request.Context(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if tom == nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, tom)
|
||||
}
|
||||
|
||||
// CreateTOM creates a new TOM
|
||||
func (h *DSGVOHandlers) CreateTOM(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
userID := rbac.GetUserID(c)
|
||||
if tenantID == uuid.Nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "tenant ID required"})
|
||||
return
|
||||
}
|
||||
|
||||
var tom dsgvo.TOM
|
||||
if err := c.ShouldBindJSON(&tom); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
tom.TenantID = tenantID
|
||||
tom.CreatedBy = userID
|
||||
if tom.ImplementationStatus == "" {
|
||||
tom.ImplementationStatus = "planned"
|
||||
}
|
||||
|
||||
if err := h.store.CreateTOM(c.Request.Context(), &tom); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, tom)
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// DSR - Data Subject Requests
|
||||
// DEPRECATED: DSR is now managed by backend-compliance (Python/FastAPI).
|
||||
// Use: /api/compliance/dsr/* endpoints on backend-compliance:8002
|
||||
// ============================================================================
|
||||
|
||||
// ListDSRs returns all DSRs for a tenant
|
||||
// DEPRECATED: Use backend-compliance GET /api/compliance/dsr
|
||||
func (h *DSGVOHandlers) ListDSRs(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
if tenantID == uuid.Nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "tenant ID required"})
|
||||
return
|
||||
}
|
||||
|
||||
status := c.Query("status")
|
||||
requestType := c.Query("type")
|
||||
|
||||
dsrs, err := h.store.ListDSRs(c.Request.Context(), tenantID, status, requestType)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"dsrs": dsrs, "types": dsgvo.DSRTypes})
|
||||
}
|
||||
|
||||
// GetDSR returns a DSR by ID
|
||||
// DEPRECATED: Use backend-compliance GET /api/compliance/dsr/{id}
|
||||
func (h *DSGVOHandlers) GetDSR(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid ID"})
|
||||
return
|
||||
}
|
||||
|
||||
dsr, err := h.store.GetDSR(c.Request.Context(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if dsr == nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, dsr)
|
||||
}
|
||||
|
||||
// CreateDSR creates a new DSR
|
||||
// DEPRECATED: Use backend-compliance POST /api/compliance/dsr
|
||||
func (h *DSGVOHandlers) CreateDSR(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
userID := rbac.GetUserID(c)
|
||||
if tenantID == uuid.Nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "tenant ID required"})
|
||||
return
|
||||
}
|
||||
|
||||
var dsr dsgvo.DSR
|
||||
if err := c.ShouldBindJSON(&dsr); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
dsr.TenantID = tenantID
|
||||
dsr.CreatedBy = userID
|
||||
if dsr.Status == "" {
|
||||
dsr.Status = "received"
|
||||
}
|
||||
|
||||
if err := h.store.CreateDSR(c.Request.Context(), &dsr); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, dsr)
|
||||
}
|
||||
|
||||
// UpdateDSR updates a DSR
|
||||
// DEPRECATED: Use backend-compliance PUT /api/compliance/dsr/{id}
|
||||
func (h *DSGVOHandlers) UpdateDSR(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid ID"})
|
||||
return
|
||||
}
|
||||
|
||||
var dsr dsgvo.DSR
|
||||
if err := c.ShouldBindJSON(&dsr); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
dsr.ID = id
|
||||
if err := h.store.UpdateDSR(c.Request.Context(), &dsr); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, dsr)
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Retention Policies
|
||||
// ============================================================================
|
||||
|
||||
// ListRetentionPolicies returns all retention policies for a tenant
|
||||
func (h *DSGVOHandlers) ListRetentionPolicies(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
if tenantID == uuid.Nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "tenant ID required"})
|
||||
return
|
||||
}
|
||||
|
||||
policies, err := h.store.ListRetentionPolicies(c.Request.Context(), tenantID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"policies": policies,
|
||||
"common_periods": dsgvo.CommonRetentionPeriods,
|
||||
})
|
||||
}
|
||||
|
||||
// CreateRetentionPolicy creates a new retention policy
|
||||
func (h *DSGVOHandlers) CreateRetentionPolicy(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
userID := rbac.GetUserID(c)
|
||||
if tenantID == uuid.Nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "tenant ID required"})
|
||||
return
|
||||
}
|
||||
|
||||
var policy dsgvo.RetentionPolicy
|
||||
if err := c.ShouldBindJSON(&policy); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
policy.TenantID = tenantID
|
||||
policy.CreatedBy = userID
|
||||
if policy.Status == "" {
|
||||
policy.Status = "draft"
|
||||
}
|
||||
|
||||
if err := h.store.CreateRetentionPolicy(c.Request.Context(), &policy); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, policy)
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Statistics
|
||||
// ============================================================================
|
||||
|
||||
// GetStats returns DSGVO statistics for a tenant
|
||||
func (h *DSGVOHandlers) GetStats(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
if tenantID == uuid.Nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "tenant ID required"})
|
||||
return
|
||||
}
|
||||
|
||||
stats, err := h.store.GetStats(c.Request.Context(), tenantID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, stats)
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// DSFA - Datenschutz-Folgenabschätzung
|
||||
// DEPRECATED: DSFA endpoints migrated to backend-compliance (Python/FastAPI).
|
||||
// These in-memory Go handlers are kept for backwards compatibility only.
|
||||
// Use backend-compliance /api/compliance/dsfa/* instead.
|
||||
// ============================================================================
|
||||
|
||||
// ListDSFAs returns all DSFAs for a tenant
|
||||
// DEPRECATED: Use backend-compliance GET /api/compliance/dsfa
|
||||
func (h *DSGVOHandlers) ListDSFAs(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
if tenantID == uuid.Nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "tenant ID required"})
|
||||
return
|
||||
}
|
||||
|
||||
status := c.Query("status")
|
||||
|
||||
dsfas, err := h.store.ListDSFAs(c.Request.Context(), tenantID, status)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"dsfas": dsfas})
|
||||
}
|
||||
|
||||
// GetDSFA returns a DSFA by ID
|
||||
// DEPRECATED: Use backend-compliance GET /api/compliance/dsfa/{id}
|
||||
func (h *DSGVOHandlers) GetDSFA(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid ID"})
|
||||
return
|
||||
}
|
||||
|
||||
dsfa, err := h.store.GetDSFA(c.Request.Context(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if dsfa == nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, dsfa)
|
||||
}
|
||||
|
||||
// CreateDSFA creates a new DSFA
|
||||
// DEPRECATED: Use backend-compliance POST /api/compliance/dsfa
|
||||
func (h *DSGVOHandlers) CreateDSFA(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
userID := rbac.GetUserID(c)
|
||||
if tenantID == uuid.Nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "tenant ID required"})
|
||||
return
|
||||
}
|
||||
|
||||
var dsfa dsgvo.DSFA
|
||||
if err := c.ShouldBindJSON(&dsfa); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
dsfa.TenantID = tenantID
|
||||
dsfa.CreatedBy = userID
|
||||
if dsfa.Status == "" {
|
||||
dsfa.Status = "draft"
|
||||
}
|
||||
|
||||
if err := h.store.CreateDSFA(c.Request.Context(), &dsfa); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, dsfa)
|
||||
}
|
||||
|
||||
// UpdateDSFA updates a DSFA
|
||||
// DEPRECATED: Use backend-compliance PUT /api/compliance/dsfa/{id}
|
||||
func (h *DSGVOHandlers) UpdateDSFA(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid ID"})
|
||||
return
|
||||
}
|
||||
|
||||
var dsfa dsgvo.DSFA
|
||||
if err := c.ShouldBindJSON(&dsfa); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
dsfa.ID = id
|
||||
if err := h.store.UpdateDSFA(c.Request.Context(), &dsfa); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, dsfa)
|
||||
}
|
||||
|
||||
// DeleteDSFA deletes a DSFA
|
||||
// DEPRECATED: Use backend-compliance DELETE /api/compliance/dsfa/{id}
|
||||
func (h *DSGVOHandlers) DeleteDSFA(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid ID"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.store.DeleteDSFA(c.Request.Context(), id); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"message": "deleted"})
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// PDF Export
|
||||
// ============================================================================
|
||||
|
||||
// ExportVVT exports the Verarbeitungsverzeichnis as CSV/JSON
|
||||
func (h *DSGVOHandlers) ExportVVT(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
if tenantID == uuid.Nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "tenant ID required"})
|
||||
return
|
||||
}
|
||||
|
||||
format := c.DefaultQuery("format", "csv")
|
||||
|
||||
activities, err := h.store.ListProcessingActivities(c.Request.Context(), tenantID, nil)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if format == "json" {
|
||||
c.Header("Content-Disposition", "attachment; filename=vvt_export.json")
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"exported_at": time.Now().UTC().Format(time.RFC3339),
|
||||
"processing_activities": activities,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// CSV Export
|
||||
var buf bytes.Buffer
|
||||
buf.WriteString("ID;Name;Zweck;Rechtsgrundlage;Datenkategorien;Betroffene;Empfänger;Drittland;Aufbewahrung;Verantwortlich;Status;Erstellt\n")
|
||||
|
||||
for _, pa := range activities {
|
||||
buf.WriteString(fmt.Sprintf("%s;%s;%s;%s;%s;%s;%s;%t;%s;%s;%s;%s\n",
|
||||
pa.ID.String(),
|
||||
escapeCSV(pa.Name),
|
||||
escapeCSV(pa.Purpose),
|
||||
pa.LegalBasis,
|
||||
joinStrings(pa.DataCategories),
|
||||
joinStrings(pa.DataSubjectCategories),
|
||||
joinStrings(pa.Recipients),
|
||||
pa.ThirdCountryTransfer,
|
||||
pa.RetentionPeriod,
|
||||
escapeCSV(pa.ResponsiblePerson),
|
||||
pa.Status,
|
||||
pa.CreatedAt.Format("2006-01-02"),
|
||||
))
|
||||
}
|
||||
|
||||
c.Header("Content-Type", "text/csv; charset=utf-8")
|
||||
c.Header("Content-Disposition", "attachment; filename=vvt_export.csv")
|
||||
c.Data(http.StatusOK, "text/csv; charset=utf-8", buf.Bytes())
|
||||
}
|
||||
|
||||
// ExportTOM exports the TOM catalog as CSV/JSON
|
||||
// DEPRECATED: Use backend-compliance GET /api/compliance/tom/export
|
||||
func (h *DSGVOHandlers) ExportTOM(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
if tenantID == uuid.Nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "tenant ID required"})
|
||||
return
|
||||
}
|
||||
|
||||
format := c.DefaultQuery("format", "csv")
|
||||
|
||||
toms, err := h.store.ListTOMs(c.Request.Context(), tenantID, "")
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if format == "json" {
|
||||
c.Header("Content-Disposition", "attachment; filename=tom_export.json")
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"exported_at": time.Now().UTC().Format(time.RFC3339),
|
||||
"toms": toms,
|
||||
"categories": dsgvo.TOMCategories,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// CSV Export
|
||||
var buf bytes.Buffer
|
||||
buf.WriteString("ID;Kategorie;Name;Beschreibung;Typ;Status;Implementiert am;Verantwortlich;Wirksamkeit;Erstellt\n")
|
||||
|
||||
for _, tom := range toms {
|
||||
implementedAt := ""
|
||||
if tom.ImplementedAt != nil {
|
||||
implementedAt = tom.ImplementedAt.Format("2006-01-02")
|
||||
}
|
||||
buf.WriteString(fmt.Sprintf("%s;%s;%s;%s;%s;%s;%s;%s;%s;%s\n",
|
||||
tom.ID.String(),
|
||||
tom.Category,
|
||||
escapeCSV(tom.Name),
|
||||
escapeCSV(tom.Description),
|
||||
tom.Type,
|
||||
tom.ImplementationStatus,
|
||||
implementedAt,
|
||||
escapeCSV(tom.ResponsiblePerson),
|
||||
tom.EffectivenessRating,
|
||||
tom.CreatedAt.Format("2006-01-02"),
|
||||
))
|
||||
}
|
||||
|
||||
c.Header("Content-Type", "text/csv; charset=utf-8")
|
||||
c.Header("Content-Disposition", "attachment; filename=tom_export.csv")
|
||||
c.Data(http.StatusOK, "text/csv; charset=utf-8", buf.Bytes())
|
||||
}
|
||||
|
||||
// ExportDSR exports DSR overview as CSV/JSON
|
||||
// DEPRECATED: Use backend-compliance GET /api/compliance/dsr/export?format=csv|json
|
||||
func (h *DSGVOHandlers) ExportDSR(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
if tenantID == uuid.Nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "tenant ID required"})
|
||||
return
|
||||
}
|
||||
|
||||
format := c.DefaultQuery("format", "csv")
|
||||
|
||||
dsrs, err := h.store.ListDSRs(c.Request.Context(), tenantID, "", "")
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if format == "json" {
|
||||
c.Header("Content-Disposition", "attachment; filename=dsr_export.json")
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"exported_at": time.Now().UTC().Format(time.RFC3339),
|
||||
"dsrs": dsrs,
|
||||
"types": dsgvo.DSRTypes,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// CSV Export
|
||||
var buf bytes.Buffer
|
||||
buf.WriteString("ID;Typ;Name;E-Mail;Status;Eingegangen;Frist;Abgeschlossen;Kanal;Zugewiesen\n")
|
||||
|
||||
for _, dsr := range dsrs {
|
||||
completedAt := ""
|
||||
if dsr.CompletedAt != nil {
|
||||
completedAt = dsr.CompletedAt.Format("2006-01-02")
|
||||
}
|
||||
assignedTo := ""
|
||||
if dsr.AssignedTo != nil {
|
||||
assignedTo = dsr.AssignedTo.String()
|
||||
}
|
||||
buf.WriteString(fmt.Sprintf("%s;%s;%s;%s;%s;%s;%s;%s;%s;%s\n",
|
||||
dsr.ID.String(),
|
||||
dsr.RequestType,
|
||||
escapeCSV(dsr.SubjectName),
|
||||
dsr.SubjectEmail,
|
||||
dsr.Status,
|
||||
dsr.ReceivedAt.Format("2006-01-02"),
|
||||
dsr.DeadlineAt.Format("2006-01-02"),
|
||||
completedAt,
|
||||
dsr.RequestChannel,
|
||||
assignedTo,
|
||||
))
|
||||
}
|
||||
|
||||
c.Header("Content-Type", "text/csv; charset=utf-8")
|
||||
c.Header("Content-Disposition", "attachment; filename=dsr_export.csv")
|
||||
c.Data(http.StatusOK, "text/csv; charset=utf-8", buf.Bytes())
|
||||
}
|
||||
|
||||
// ExportDSFA exports a DSFA as JSON
|
||||
// DEPRECATED: Use backend-compliance GET /api/compliance/dsfa/{id}/export?format=json
|
||||
func (h *DSGVOHandlers) ExportDSFA(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid ID"})
|
||||
return
|
||||
}
|
||||
|
||||
dsfa, err := h.store.GetDSFA(c.Request.Context(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if dsfa == nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
|
||||
return
|
||||
}
|
||||
|
||||
c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=dsfa_%s.json", id.String()[:8]))
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"exported_at": time.Now().UTC().Format(time.RFC3339),
|
||||
"dsfa": dsfa,
|
||||
})
|
||||
}
|
||||
|
||||
// ExportRetentionPolicies exports retention policies as CSV/JSON
|
||||
func (h *DSGVOHandlers) ExportRetentionPolicies(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
if tenantID == uuid.Nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "tenant ID required"})
|
||||
return
|
||||
}
|
||||
|
||||
format := c.DefaultQuery("format", "csv")
|
||||
|
||||
policies, err := h.store.ListRetentionPolicies(c.Request.Context(), tenantID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if format == "json" {
|
||||
c.Header("Content-Disposition", "attachment; filename=retention_policies_export.json")
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"exported_at": time.Now().UTC().Format(time.RFC3339),
|
||||
"policies": policies,
|
||||
"common_periods": dsgvo.CommonRetentionPeriods,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// CSV Export
|
||||
var buf bytes.Buffer
|
||||
buf.WriteString("ID;Name;Datenkategorie;Aufbewahrungsdauer (Tage);Dauer (Text);Rechtsgrundlage;Referenz;Löschmethode;Status\n")
|
||||
|
||||
for _, rp := range policies {
|
||||
buf.WriteString(fmt.Sprintf("%s;%s;%s;%d;%s;%s;%s;%s;%s\n",
|
||||
rp.ID.String(),
|
||||
escapeCSV(rp.Name),
|
||||
rp.DataCategory,
|
||||
rp.RetentionPeriodDays,
|
||||
escapeCSV(rp.RetentionPeriodText),
|
||||
escapeCSV(rp.LegalBasis),
|
||||
escapeCSV(rp.LegalReference),
|
||||
rp.DeletionMethod,
|
||||
rp.Status,
|
||||
))
|
||||
}
|
||||
|
||||
c.Header("Content-Type", "text/csv; charset=utf-8")
|
||||
c.Header("Content-Disposition", "attachment; filename=retention_policies_export.csv")
|
||||
c.Data(http.StatusOK, "text/csv; charset=utf-8", buf.Bytes())
|
||||
}
|
||||
|
||||
// Helper functions
|
||||
|
||||
func escapeCSV(s string) string {
|
||||
// Simple CSV escaping - wrap in quotes if contains semicolon, quote, or newline
|
||||
if s == "" {
|
||||
return ""
|
||||
}
|
||||
needsQuotes := false
|
||||
for _, c := range s {
|
||||
if c == ';' || c == '"' || c == '\n' || c == '\r' {
|
||||
needsQuotes = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if needsQuotes {
|
||||
// Double any quotes and wrap in quotes
|
||||
escaped := ""
|
||||
for _, c := range s {
|
||||
if c == '"' {
|
||||
escaped += "\"\""
|
||||
} else if c == '\n' || c == '\r' {
|
||||
escaped += " "
|
||||
} else {
|
||||
escaped += string(c)
|
||||
}
|
||||
}
|
||||
return "\"" + escaped + "\""
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func joinStrings(strs []string) string {
|
||||
if len(strs) == 0 {
|
||||
return ""
|
||||
}
|
||||
result := strs[0]
|
||||
for i := 1; i < len(strs); i++ {
|
||||
result += ", " + strs[i]
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -1,672 +0,0 @@
|
||||
// DEPRECATED: Python backend (backend-compliance) is now Source of Truth for Incidents.
|
||||
// Frontend proxies to backend-compliance:8002/api/compliance/incidents/*
|
||||
// These Go handlers remain for backward compatibility but should not be extended.
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/incidents"
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/rbac"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// IncidentHandlers handles incident/breach management HTTP requests
|
||||
// DEPRECATED: Use Python backend-compliance incident_routes.py instead.
|
||||
type IncidentHandlers struct {
|
||||
store *incidents.Store
|
||||
}
|
||||
|
||||
// NewIncidentHandlers creates new incident handlers
|
||||
func NewIncidentHandlers(store *incidents.Store) *IncidentHandlers {
|
||||
return &IncidentHandlers{store: store}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Incident CRUD
|
||||
// ============================================================================
|
||||
|
||||
// CreateIncident creates a new incident
|
||||
// POST /sdk/v1/incidents
|
||||
func (h *IncidentHandlers) CreateIncident(c *gin.Context) {
|
||||
var req incidents.CreateIncidentRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
userID := rbac.GetUserID(c)
|
||||
|
||||
detectedAt := time.Now().UTC()
|
||||
if req.DetectedAt != nil {
|
||||
detectedAt = *req.DetectedAt
|
||||
}
|
||||
|
||||
// Auto-calculate 72h deadline per DSGVO Art. 33
|
||||
deadline := incidents.Calculate72hDeadline(detectedAt)
|
||||
|
||||
incident := &incidents.Incident{
|
||||
TenantID: tenantID,
|
||||
Title: req.Title,
|
||||
Description: req.Description,
|
||||
Category: req.Category,
|
||||
Status: incidents.IncidentStatusDetected,
|
||||
Severity: req.Severity,
|
||||
DetectedAt: detectedAt,
|
||||
ReportedBy: userID,
|
||||
AffectedDataCategories: req.AffectedDataCategories,
|
||||
AffectedDataSubjectCount: req.AffectedDataSubjectCount,
|
||||
AffectedSystems: req.AffectedSystems,
|
||||
AuthorityNotification: &incidents.AuthorityNotification{
|
||||
Status: incidents.NotificationStatusPending,
|
||||
Deadline: deadline,
|
||||
},
|
||||
DataSubjectNotification: &incidents.DataSubjectNotification{
|
||||
Required: false,
|
||||
Status: incidents.NotificationStatusNotRequired,
|
||||
},
|
||||
Timeline: []incidents.TimelineEntry{
|
||||
{
|
||||
Timestamp: time.Now().UTC(),
|
||||
Action: "incident_created",
|
||||
UserID: userID,
|
||||
Details: "Incident detected and reported",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
if err := h.store.CreateIncident(c.Request.Context(), incident); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, gin.H{
|
||||
"incident": incident,
|
||||
"authority_deadline": deadline,
|
||||
"hours_until_deadline": time.Until(deadline).Hours(),
|
||||
})
|
||||
}
|
||||
|
||||
// GetIncident retrieves an incident by ID
|
||||
// GET /sdk/v1/incidents/:id
|
||||
func (h *IncidentHandlers) GetIncident(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid incident ID"})
|
||||
return
|
||||
}
|
||||
|
||||
incident, err := h.store.GetIncident(c.Request.Context(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if incident == nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "incident not found"})
|
||||
return
|
||||
}
|
||||
|
||||
// Get measures
|
||||
measures, _ := h.store.ListMeasures(c.Request.Context(), id)
|
||||
|
||||
// Calculate deadline info if authority notification exists
|
||||
var deadlineInfo gin.H
|
||||
if incident.AuthorityNotification != nil {
|
||||
hoursRemaining := time.Until(incident.AuthorityNotification.Deadline).Hours()
|
||||
deadlineInfo = gin.H{
|
||||
"deadline": incident.AuthorityNotification.Deadline,
|
||||
"hours_remaining": hoursRemaining,
|
||||
"overdue": hoursRemaining < 0,
|
||||
}
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"incident": incident,
|
||||
"measures": measures,
|
||||
"deadline_info": deadlineInfo,
|
||||
})
|
||||
}
|
||||
|
||||
// ListIncidents lists incidents for a tenant
|
||||
// GET /sdk/v1/incidents
|
||||
func (h *IncidentHandlers) ListIncidents(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
|
||||
filters := &incidents.IncidentFilters{
|
||||
Limit: 50,
|
||||
}
|
||||
|
||||
if status := c.Query("status"); status != "" {
|
||||
filters.Status = incidents.IncidentStatus(status)
|
||||
}
|
||||
if severity := c.Query("severity"); severity != "" {
|
||||
filters.Severity = incidents.IncidentSeverity(severity)
|
||||
}
|
||||
if category := c.Query("category"); category != "" {
|
||||
filters.Category = incidents.IncidentCategory(category)
|
||||
}
|
||||
|
||||
incidentList, total, err := h.store.ListIncidents(c.Request.Context(), tenantID, filters)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, incidents.IncidentListResponse{
|
||||
Incidents: incidentList,
|
||||
Total: total,
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateIncident updates an incident
|
||||
// PUT /sdk/v1/incidents/:id
|
||||
func (h *IncidentHandlers) UpdateIncident(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid incident ID"})
|
||||
return
|
||||
}
|
||||
|
||||
incident, err := h.store.GetIncident(c.Request.Context(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if incident == nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "incident not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var req incidents.UpdateIncidentRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if req.Title != "" {
|
||||
incident.Title = req.Title
|
||||
}
|
||||
if req.Description != "" {
|
||||
incident.Description = req.Description
|
||||
}
|
||||
if req.Category != "" {
|
||||
incident.Category = req.Category
|
||||
}
|
||||
if req.Status != "" {
|
||||
incident.Status = req.Status
|
||||
}
|
||||
if req.Severity != "" {
|
||||
incident.Severity = req.Severity
|
||||
}
|
||||
if req.AffectedDataCategories != nil {
|
||||
incident.AffectedDataCategories = req.AffectedDataCategories
|
||||
}
|
||||
if req.AffectedDataSubjectCount != nil {
|
||||
incident.AffectedDataSubjectCount = *req.AffectedDataSubjectCount
|
||||
}
|
||||
if req.AffectedSystems != nil {
|
||||
incident.AffectedSystems = req.AffectedSystems
|
||||
}
|
||||
|
||||
if err := h.store.UpdateIncident(c.Request.Context(), incident); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"incident": incident})
|
||||
}
|
||||
|
||||
// DeleteIncident deletes an incident
|
||||
// DELETE /sdk/v1/incidents/:id
|
||||
func (h *IncidentHandlers) DeleteIncident(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid incident ID"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.store.DeleteIncident(c.Request.Context(), id); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"message": "incident deleted"})
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Risk Assessment
|
||||
// ============================================================================
|
||||
|
||||
// AssessRisk performs a risk assessment for an incident
|
||||
// POST /sdk/v1/incidents/:id/risk-assessment
|
||||
func (h *IncidentHandlers) AssessRisk(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid incident ID"})
|
||||
return
|
||||
}
|
||||
|
||||
incident, err := h.store.GetIncident(c.Request.Context(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if incident == nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "incident not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var req incidents.RiskAssessmentRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
userID := rbac.GetUserID(c)
|
||||
|
||||
// Auto-calculate risk level
|
||||
riskLevel := incidents.CalculateRiskLevel(req.Likelihood, req.Impact)
|
||||
notificationRequired := incidents.IsNotificationRequired(riskLevel)
|
||||
|
||||
assessment := &incidents.RiskAssessment{
|
||||
Likelihood: req.Likelihood,
|
||||
Impact: req.Impact,
|
||||
RiskLevel: riskLevel,
|
||||
AssessedAt: time.Now().UTC(),
|
||||
AssessedBy: userID,
|
||||
Notes: req.Notes,
|
||||
}
|
||||
|
||||
if err := h.store.UpdateRiskAssessment(c.Request.Context(), id, assessment); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
// Update status to assessment
|
||||
incident.Status = incidents.IncidentStatusAssessment
|
||||
h.store.UpdateIncident(c.Request.Context(), incident)
|
||||
|
||||
// Add timeline entry
|
||||
h.store.AddTimelineEntry(c.Request.Context(), id, incidents.TimelineEntry{
|
||||
Timestamp: time.Now().UTC(),
|
||||
Action: "risk_assessed",
|
||||
UserID: userID,
|
||||
Details: fmt.Sprintf("Risk level: %s (likelihood=%d, impact=%d)", riskLevel, req.Likelihood, req.Impact),
|
||||
})
|
||||
|
||||
// If notification is required, update authority notification status
|
||||
if notificationRequired && incident.AuthorityNotification != nil {
|
||||
incident.AuthorityNotification.Status = incidents.NotificationStatusPending
|
||||
h.store.UpdateAuthorityNotification(c.Request.Context(), id, incident.AuthorityNotification)
|
||||
|
||||
// Update status to notification_required
|
||||
incident.Status = incidents.IncidentStatusNotificationRequired
|
||||
h.store.UpdateIncident(c.Request.Context(), incident)
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"risk_assessment": assessment,
|
||||
"notification_required": notificationRequired,
|
||||
"incident_status": incident.Status,
|
||||
})
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Authority Notification (Art. 33)
|
||||
// ============================================================================
|
||||
|
||||
// SubmitAuthorityNotification submits the supervisory authority notification
|
||||
// POST /sdk/v1/incidents/:id/authority-notification
|
||||
func (h *IncidentHandlers) SubmitAuthorityNotification(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid incident ID"})
|
||||
return
|
||||
}
|
||||
|
||||
incident, err := h.store.GetIncident(c.Request.Context(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if incident == nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "incident not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var req incidents.SubmitAuthorityNotificationRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
userID := rbac.GetUserID(c)
|
||||
now := time.Now().UTC()
|
||||
|
||||
// Preserve existing deadline
|
||||
deadline := incidents.Calculate72hDeadline(incident.DetectedAt)
|
||||
if incident.AuthorityNotification != nil {
|
||||
deadline = incident.AuthorityNotification.Deadline
|
||||
}
|
||||
|
||||
notification := &incidents.AuthorityNotification{
|
||||
Status: incidents.NotificationStatusSent,
|
||||
Deadline: deadline,
|
||||
SubmittedAt: &now,
|
||||
AuthorityName: req.AuthorityName,
|
||||
ReferenceNumber: req.ReferenceNumber,
|
||||
ContactPerson: req.ContactPerson,
|
||||
Notes: req.Notes,
|
||||
}
|
||||
|
||||
if err := h.store.UpdateAuthorityNotification(c.Request.Context(), id, notification); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
// Update incident status
|
||||
incident.Status = incidents.IncidentStatusNotificationSent
|
||||
h.store.UpdateIncident(c.Request.Context(), incident)
|
||||
|
||||
// Add timeline entry
|
||||
h.store.AddTimelineEntry(c.Request.Context(), id, incidents.TimelineEntry{
|
||||
Timestamp: now,
|
||||
Action: "authority_notified",
|
||||
UserID: userID,
|
||||
Details: "Authority notification submitted to " + req.AuthorityName,
|
||||
})
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"authority_notification": notification,
|
||||
"submitted_within_72h": now.Before(deadline),
|
||||
})
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Data Subject Notification (Art. 34)
|
||||
// ============================================================================
|
||||
|
||||
// NotifyDataSubjects submits the data subject notification
|
||||
// POST /sdk/v1/incidents/:id/data-subject-notification
|
||||
func (h *IncidentHandlers) NotifyDataSubjects(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid incident ID"})
|
||||
return
|
||||
}
|
||||
|
||||
incident, err := h.store.GetIncident(c.Request.Context(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if incident == nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "incident not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var req incidents.NotifyDataSubjectsRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
userID := rbac.GetUserID(c)
|
||||
now := time.Now().UTC()
|
||||
|
||||
affectedCount := req.AffectedCount
|
||||
if affectedCount == 0 {
|
||||
affectedCount = incident.AffectedDataSubjectCount
|
||||
}
|
||||
|
||||
notification := &incidents.DataSubjectNotification{
|
||||
Required: true,
|
||||
Status: incidents.NotificationStatusSent,
|
||||
SentAt: &now,
|
||||
AffectedCount: affectedCount,
|
||||
NotificationText: req.NotificationText,
|
||||
Channel: req.Channel,
|
||||
}
|
||||
|
||||
if err := h.store.UpdateDataSubjectNotification(c.Request.Context(), id, notification); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
// Add timeline entry
|
||||
h.store.AddTimelineEntry(c.Request.Context(), id, incidents.TimelineEntry{
|
||||
Timestamp: now,
|
||||
Action: "data_subjects_notified",
|
||||
UserID: userID,
|
||||
Details: "Data subjects notified via " + req.Channel + " (" + fmt.Sprintf("%d", affectedCount) + " affected)",
|
||||
})
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"data_subject_notification": notification,
|
||||
})
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Measures
|
||||
// ============================================================================
|
||||
|
||||
// AddMeasure adds a corrective measure to an incident
|
||||
// POST /sdk/v1/incidents/:id/measures
|
||||
func (h *IncidentHandlers) AddMeasure(c *gin.Context) {
|
||||
incidentID, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid incident ID"})
|
||||
return
|
||||
}
|
||||
|
||||
// Verify incident exists
|
||||
incident, err := h.store.GetIncident(c.Request.Context(), incidentID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if incident == nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "incident not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var req incidents.AddMeasureRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
userID := rbac.GetUserID(c)
|
||||
|
||||
measure := &incidents.IncidentMeasure{
|
||||
IncidentID: incidentID,
|
||||
Title: req.Title,
|
||||
Description: req.Description,
|
||||
MeasureType: req.MeasureType,
|
||||
Status: incidents.MeasureStatusPlanned,
|
||||
Responsible: req.Responsible,
|
||||
DueDate: req.DueDate,
|
||||
}
|
||||
|
||||
if err := h.store.AddMeasure(c.Request.Context(), measure); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
// Add timeline entry
|
||||
h.store.AddTimelineEntry(c.Request.Context(), incidentID, incidents.TimelineEntry{
|
||||
Timestamp: time.Now().UTC(),
|
||||
Action: "measure_added",
|
||||
UserID: userID,
|
||||
Details: "Measure added: " + req.Title + " (" + string(req.MeasureType) + ")",
|
||||
})
|
||||
|
||||
c.JSON(http.StatusCreated, gin.H{"measure": measure})
|
||||
}
|
||||
|
||||
// UpdateMeasure updates a measure
|
||||
// PUT /sdk/v1/incidents/measures/:measureId
|
||||
func (h *IncidentHandlers) UpdateMeasure(c *gin.Context) {
|
||||
measureID, err := uuid.Parse(c.Param("measureId"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid measure ID"})
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
Title string `json:"title,omitempty"`
|
||||
Description string `json:"description,omitempty"`
|
||||
MeasureType incidents.MeasureType `json:"measure_type,omitempty"`
|
||||
Status incidents.MeasureStatus `json:"status,omitempty"`
|
||||
Responsible string `json:"responsible,omitempty"`
|
||||
DueDate *time.Time `json:"due_date,omitempty"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
measure := &incidents.IncidentMeasure{
|
||||
ID: measureID,
|
||||
Title: req.Title,
|
||||
Description: req.Description,
|
||||
MeasureType: req.MeasureType,
|
||||
Status: req.Status,
|
||||
Responsible: req.Responsible,
|
||||
DueDate: req.DueDate,
|
||||
}
|
||||
|
||||
if err := h.store.UpdateMeasure(c.Request.Context(), measure); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"measure": measure})
|
||||
}
|
||||
|
||||
// CompleteMeasure marks a measure as completed
|
||||
// POST /sdk/v1/incidents/measures/:measureId/complete
|
||||
func (h *IncidentHandlers) CompleteMeasure(c *gin.Context) {
|
||||
measureID, err := uuid.Parse(c.Param("measureId"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid measure ID"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.store.CompleteMeasure(c.Request.Context(), measureID); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"message": "measure completed"})
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Timeline
|
||||
// ============================================================================
|
||||
|
||||
// AddTimelineEntry adds a timeline entry to an incident
|
||||
// POST /sdk/v1/incidents/:id/timeline
|
||||
func (h *IncidentHandlers) AddTimelineEntry(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid incident ID"})
|
||||
return
|
||||
}
|
||||
|
||||
var req incidents.AddTimelineEntryRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
userID := rbac.GetUserID(c)
|
||||
|
||||
entry := incidents.TimelineEntry{
|
||||
Timestamp: time.Now().UTC(),
|
||||
Action: req.Action,
|
||||
UserID: userID,
|
||||
Details: req.Details,
|
||||
}
|
||||
|
||||
if err := h.store.AddTimelineEntry(c.Request.Context(), id, entry); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, gin.H{"timeline_entry": entry})
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Close Incident
|
||||
// ============================================================================
|
||||
|
||||
// CloseIncident closes an incident with root cause analysis
|
||||
// POST /sdk/v1/incidents/:id/close
|
||||
func (h *IncidentHandlers) CloseIncident(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid incident ID"})
|
||||
return
|
||||
}
|
||||
|
||||
incident, err := h.store.GetIncident(c.Request.Context(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if incident == nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "incident not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var req incidents.CloseIncidentRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
userID := rbac.GetUserID(c)
|
||||
|
||||
if err := h.store.CloseIncident(c.Request.Context(), id, req.RootCause, req.LessonsLearned); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
// Add timeline entry
|
||||
h.store.AddTimelineEntry(c.Request.Context(), id, incidents.TimelineEntry{
|
||||
Timestamp: time.Now().UTC(),
|
||||
Action: "incident_closed",
|
||||
UserID: userID,
|
||||
Details: "Incident closed. Root cause: " + req.RootCause,
|
||||
})
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"message": "incident closed",
|
||||
"root_cause": req.RootCause,
|
||||
"lessons_learned": req.LessonsLearned,
|
||||
})
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Statistics
|
||||
// ============================================================================
|
||||
|
||||
// GetStatistics returns aggregated incident statistics
|
||||
// GET /sdk/v1/incidents/statistics
|
||||
func (h *IncidentHandlers) GetStatistics(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
|
||||
stats, err := h.store.GetStatistics(c.Request.Context(), tenantID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, stats)
|
||||
}
|
||||
|
||||
@@ -1,855 +0,0 @@
|
||||
// DEPRECATED: Vendor Compliance handlers are superseded by the Python backend
|
||||
// (backend-compliance/compliance/api/vendor_compliance_routes.py).
|
||||
// Frontend now routes through /api/sdk/v1/vendor-compliance → backend-compliance:8002.
|
||||
// These Go handlers remain for backward compatibility but should not be extended.
|
||||
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/rbac"
|
||||
"github.com/breakpilot/ai-compliance-sdk/internal/vendor"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// VendorHandlers handles vendor-compliance HTTP requests
|
||||
type VendorHandlers struct {
|
||||
store *vendor.Store
|
||||
}
|
||||
|
||||
// NewVendorHandlers creates new vendor handlers
|
||||
func NewVendorHandlers(store *vendor.Store) *VendorHandlers {
|
||||
return &VendorHandlers{store: store}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Vendor CRUD
|
||||
// ============================================================================
|
||||
|
||||
// CreateVendor creates a new vendor
|
||||
// POST /sdk/v1/vendors
|
||||
func (h *VendorHandlers) CreateVendor(c *gin.Context) {
|
||||
var req vendor.CreateVendorRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
userID := rbac.GetUserID(c)
|
||||
|
||||
v := &vendor.Vendor{
|
||||
TenantID: tenantID,
|
||||
Name: req.Name,
|
||||
LegalForm: req.LegalForm,
|
||||
Country: req.Country,
|
||||
Address: req.Address,
|
||||
Website: req.Website,
|
||||
ContactName: req.ContactName,
|
||||
ContactEmail: req.ContactEmail,
|
||||
ContactPhone: req.ContactPhone,
|
||||
ContactDepartment: req.ContactDepartment,
|
||||
Role: req.Role,
|
||||
ServiceCategory: req.ServiceCategory,
|
||||
ServiceDescription: req.ServiceDescription,
|
||||
DataAccessLevel: req.DataAccessLevel,
|
||||
ProcessingLocations: req.ProcessingLocations,
|
||||
Certifications: req.Certifications,
|
||||
ReviewFrequency: req.ReviewFrequency,
|
||||
ProcessingActivityIDs: req.ProcessingActivityIDs,
|
||||
TemplateID: req.TemplateID,
|
||||
Status: vendor.VendorStatusActive,
|
||||
CreatedBy: userID.String(),
|
||||
}
|
||||
|
||||
if err := h.store.CreateVendor(c.Request.Context(), v); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, gin.H{"vendor": v})
|
||||
}
|
||||
|
||||
// ListVendors lists all vendors for a tenant
|
||||
// GET /sdk/v1/vendors
|
||||
func (h *VendorHandlers) ListVendors(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
|
||||
vendors, err := h.store.ListVendors(c.Request.Context(), tenantID.String())
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"vendors": vendors,
|
||||
"total": len(vendors),
|
||||
})
|
||||
}
|
||||
|
||||
// GetVendor retrieves a vendor by ID with contracts and findings
|
||||
// GET /sdk/v1/vendors/:id
|
||||
func (h *VendorHandlers) GetVendor(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
id := c.Param("id")
|
||||
|
||||
v, err := h.store.GetVendor(c.Request.Context(), tenantID.String(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if v == nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "vendor not found"})
|
||||
return
|
||||
}
|
||||
|
||||
contracts, _ := h.store.ListContracts(c.Request.Context(), tenantID.String(), &id)
|
||||
findings, _ := h.store.ListFindings(c.Request.Context(), tenantID.String(), &id, nil)
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"vendor": v,
|
||||
"contracts": contracts,
|
||||
"findings": findings,
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateVendor updates a vendor
|
||||
// PUT /sdk/v1/vendors/:id
|
||||
func (h *VendorHandlers) UpdateVendor(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
id := c.Param("id")
|
||||
|
||||
v, err := h.store.GetVendor(c.Request.Context(), tenantID.String(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if v == nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "vendor not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var req vendor.UpdateVendorRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
// Apply non-nil fields
|
||||
if req.Name != nil {
|
||||
v.Name = *req.Name
|
||||
}
|
||||
if req.LegalForm != nil {
|
||||
v.LegalForm = *req.LegalForm
|
||||
}
|
||||
if req.Country != nil {
|
||||
v.Country = *req.Country
|
||||
}
|
||||
if req.Address != nil {
|
||||
v.Address = req.Address
|
||||
}
|
||||
if req.Website != nil {
|
||||
v.Website = *req.Website
|
||||
}
|
||||
if req.ContactName != nil {
|
||||
v.ContactName = *req.ContactName
|
||||
}
|
||||
if req.ContactEmail != nil {
|
||||
v.ContactEmail = *req.ContactEmail
|
||||
}
|
||||
if req.ContactPhone != nil {
|
||||
v.ContactPhone = *req.ContactPhone
|
||||
}
|
||||
if req.ContactDepartment != nil {
|
||||
v.ContactDepartment = *req.ContactDepartment
|
||||
}
|
||||
if req.Role != nil {
|
||||
v.Role = *req.Role
|
||||
}
|
||||
if req.ServiceCategory != nil {
|
||||
v.ServiceCategory = *req.ServiceCategory
|
||||
}
|
||||
if req.ServiceDescription != nil {
|
||||
v.ServiceDescription = *req.ServiceDescription
|
||||
}
|
||||
if req.DataAccessLevel != nil {
|
||||
v.DataAccessLevel = *req.DataAccessLevel
|
||||
}
|
||||
if req.ProcessingLocations != nil {
|
||||
v.ProcessingLocations = req.ProcessingLocations
|
||||
}
|
||||
if req.Certifications != nil {
|
||||
v.Certifications = req.Certifications
|
||||
}
|
||||
if req.InherentRiskScore != nil {
|
||||
v.InherentRiskScore = req.InherentRiskScore
|
||||
}
|
||||
if req.ResidualRiskScore != nil {
|
||||
v.ResidualRiskScore = req.ResidualRiskScore
|
||||
}
|
||||
if req.ManualRiskAdjustment != nil {
|
||||
v.ManualRiskAdjustment = req.ManualRiskAdjustment
|
||||
}
|
||||
if req.ReviewFrequency != nil {
|
||||
v.ReviewFrequency = *req.ReviewFrequency
|
||||
}
|
||||
if req.LastReviewDate != nil {
|
||||
v.LastReviewDate = req.LastReviewDate
|
||||
}
|
||||
if req.NextReviewDate != nil {
|
||||
v.NextReviewDate = req.NextReviewDate
|
||||
}
|
||||
if req.ProcessingActivityIDs != nil {
|
||||
v.ProcessingActivityIDs = req.ProcessingActivityIDs
|
||||
}
|
||||
if req.Status != nil {
|
||||
v.Status = *req.Status
|
||||
}
|
||||
if req.TemplateID != nil {
|
||||
v.TemplateID = req.TemplateID
|
||||
}
|
||||
|
||||
if err := h.store.UpdateVendor(c.Request.Context(), v); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"vendor": v})
|
||||
}
|
||||
|
||||
// DeleteVendor deletes a vendor
|
||||
// DELETE /sdk/v1/vendors/:id
|
||||
func (h *VendorHandlers) DeleteVendor(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
id := c.Param("id")
|
||||
|
||||
if err := h.store.DeleteVendor(c.Request.Context(), tenantID.String(), id); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"message": "vendor deleted"})
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Contract CRUD
|
||||
// ============================================================================
|
||||
|
||||
// CreateContract creates a new contract for a vendor
|
||||
// POST /sdk/v1/vendors/contracts
|
||||
func (h *VendorHandlers) CreateContract(c *gin.Context) {
|
||||
var req vendor.CreateContractRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
userID := rbac.GetUserID(c)
|
||||
|
||||
contract := &vendor.Contract{
|
||||
TenantID: tenantID,
|
||||
VendorID: req.VendorID,
|
||||
FileName: req.FileName,
|
||||
OriginalName: req.OriginalName,
|
||||
MimeType: req.MimeType,
|
||||
FileSize: req.FileSize,
|
||||
StoragePath: req.StoragePath,
|
||||
DocumentType: req.DocumentType,
|
||||
Parties: req.Parties,
|
||||
EffectiveDate: req.EffectiveDate,
|
||||
ExpirationDate: req.ExpirationDate,
|
||||
AutoRenewal: req.AutoRenewal,
|
||||
RenewalNoticePeriod: req.RenewalNoticePeriod,
|
||||
Version: req.Version,
|
||||
PreviousVersionID: req.PreviousVersionID,
|
||||
ReviewStatus: "PENDING",
|
||||
CreatedBy: userID.String(),
|
||||
}
|
||||
|
||||
if contract.Version == "" {
|
||||
contract.Version = "1.0"
|
||||
}
|
||||
|
||||
if err := h.store.CreateContract(c.Request.Context(), contract); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, gin.H{"contract": contract})
|
||||
}
|
||||
|
||||
// ListContracts lists contracts for a tenant
|
||||
// GET /sdk/v1/vendors/contracts
|
||||
func (h *VendorHandlers) ListContracts(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
|
||||
var vendorID *string
|
||||
if vid := c.Query("vendor_id"); vid != "" {
|
||||
vendorID = &vid
|
||||
}
|
||||
|
||||
contracts, err := h.store.ListContracts(c.Request.Context(), tenantID.String(), vendorID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"contracts": contracts,
|
||||
"total": len(contracts),
|
||||
})
|
||||
}
|
||||
|
||||
// GetContract retrieves a contract by ID
|
||||
// GET /sdk/v1/vendors/contracts/:id
|
||||
func (h *VendorHandlers) GetContract(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
id := c.Param("id")
|
||||
|
||||
contract, err := h.store.GetContract(c.Request.Context(), tenantID.String(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if contract == nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "contract not found"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"contract": contract})
|
||||
}
|
||||
|
||||
// UpdateContract updates a contract
|
||||
// PUT /sdk/v1/vendors/contracts/:id
|
||||
func (h *VendorHandlers) UpdateContract(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
id := c.Param("id")
|
||||
|
||||
contract, err := h.store.GetContract(c.Request.Context(), tenantID.String(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if contract == nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "contract not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var req vendor.UpdateContractRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if req.DocumentType != nil {
|
||||
contract.DocumentType = *req.DocumentType
|
||||
}
|
||||
if req.Parties != nil {
|
||||
contract.Parties = req.Parties
|
||||
}
|
||||
if req.EffectiveDate != nil {
|
||||
contract.EffectiveDate = req.EffectiveDate
|
||||
}
|
||||
if req.ExpirationDate != nil {
|
||||
contract.ExpirationDate = req.ExpirationDate
|
||||
}
|
||||
if req.AutoRenewal != nil {
|
||||
contract.AutoRenewal = *req.AutoRenewal
|
||||
}
|
||||
if req.RenewalNoticePeriod != nil {
|
||||
contract.RenewalNoticePeriod = *req.RenewalNoticePeriod
|
||||
}
|
||||
if req.ReviewStatus != nil {
|
||||
contract.ReviewStatus = *req.ReviewStatus
|
||||
}
|
||||
if req.ReviewCompletedAt != nil {
|
||||
contract.ReviewCompletedAt = req.ReviewCompletedAt
|
||||
}
|
||||
if req.ComplianceScore != nil {
|
||||
contract.ComplianceScore = req.ComplianceScore
|
||||
}
|
||||
if req.Version != nil {
|
||||
contract.Version = *req.Version
|
||||
}
|
||||
if req.ExtractedText != nil {
|
||||
contract.ExtractedText = *req.ExtractedText
|
||||
}
|
||||
if req.PageCount != nil {
|
||||
contract.PageCount = req.PageCount
|
||||
}
|
||||
|
||||
if err := h.store.UpdateContract(c.Request.Context(), contract); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"contract": contract})
|
||||
}
|
||||
|
||||
// DeleteContract deletes a contract
|
||||
// DELETE /sdk/v1/vendors/contracts/:id
|
||||
func (h *VendorHandlers) DeleteContract(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
id := c.Param("id")
|
||||
|
||||
if err := h.store.DeleteContract(c.Request.Context(), tenantID.String(), id); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"message": "contract deleted"})
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Finding CRUD
|
||||
// ============================================================================
|
||||
|
||||
// CreateFinding creates a new compliance finding
|
||||
// POST /sdk/v1/vendors/findings
|
||||
func (h *VendorHandlers) CreateFinding(c *gin.Context) {
|
||||
var req vendor.CreateFindingRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
|
||||
finding := &vendor.Finding{
|
||||
TenantID: tenantID,
|
||||
VendorID: req.VendorID,
|
||||
ContractID: req.ContractID,
|
||||
FindingType: req.FindingType,
|
||||
Category: req.Category,
|
||||
Severity: req.Severity,
|
||||
Title: req.Title,
|
||||
Description: req.Description,
|
||||
Recommendation: req.Recommendation,
|
||||
Citations: req.Citations,
|
||||
Status: vendor.FindingStatusOpen,
|
||||
Assignee: req.Assignee,
|
||||
DueDate: req.DueDate,
|
||||
}
|
||||
|
||||
if err := h.store.CreateFinding(c.Request.Context(), finding); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, gin.H{"finding": finding})
|
||||
}
|
||||
|
||||
// ListFindings lists findings for a tenant
|
||||
// GET /sdk/v1/vendors/findings
|
||||
func (h *VendorHandlers) ListFindings(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
|
||||
var vendorID, contractID *string
|
||||
if vid := c.Query("vendor_id"); vid != "" {
|
||||
vendorID = &vid
|
||||
}
|
||||
if cid := c.Query("contract_id"); cid != "" {
|
||||
contractID = &cid
|
||||
}
|
||||
|
||||
findings, err := h.store.ListFindings(c.Request.Context(), tenantID.String(), vendorID, contractID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"findings": findings,
|
||||
"total": len(findings),
|
||||
})
|
||||
}
|
||||
|
||||
// GetFinding retrieves a finding by ID
|
||||
// GET /sdk/v1/vendors/findings/:id
|
||||
func (h *VendorHandlers) GetFinding(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
id := c.Param("id")
|
||||
|
||||
finding, err := h.store.GetFinding(c.Request.Context(), tenantID.String(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if finding == nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "finding not found"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"finding": finding})
|
||||
}
|
||||
|
||||
// UpdateFinding updates a finding
|
||||
// PUT /sdk/v1/vendors/findings/:id
|
||||
func (h *VendorHandlers) UpdateFinding(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
id := c.Param("id")
|
||||
|
||||
finding, err := h.store.GetFinding(c.Request.Context(), tenantID.String(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if finding == nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "finding not found"})
|
||||
return
|
||||
}
|
||||
|
||||
var req vendor.UpdateFindingRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if req.FindingType != nil {
|
||||
finding.FindingType = *req.FindingType
|
||||
}
|
||||
if req.Category != nil {
|
||||
finding.Category = *req.Category
|
||||
}
|
||||
if req.Severity != nil {
|
||||
finding.Severity = *req.Severity
|
||||
}
|
||||
if req.Title != nil {
|
||||
finding.Title = *req.Title
|
||||
}
|
||||
if req.Description != nil {
|
||||
finding.Description = *req.Description
|
||||
}
|
||||
if req.Recommendation != nil {
|
||||
finding.Recommendation = *req.Recommendation
|
||||
}
|
||||
if req.Citations != nil {
|
||||
finding.Citations = req.Citations
|
||||
}
|
||||
if req.Status != nil {
|
||||
finding.Status = *req.Status
|
||||
}
|
||||
if req.Assignee != nil {
|
||||
finding.Assignee = *req.Assignee
|
||||
}
|
||||
if req.DueDate != nil {
|
||||
finding.DueDate = req.DueDate
|
||||
}
|
||||
if req.Resolution != nil {
|
||||
finding.Resolution = *req.Resolution
|
||||
}
|
||||
|
||||
if err := h.store.UpdateFinding(c.Request.Context(), finding); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"finding": finding})
|
||||
}
|
||||
|
||||
// ResolveFinding resolves a finding with a resolution description
|
||||
// POST /sdk/v1/vendors/findings/:id/resolve
|
||||
func (h *VendorHandlers) ResolveFinding(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
userID := rbac.GetUserID(c)
|
||||
id := c.Param("id")
|
||||
|
||||
var req vendor.ResolveFindingRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.store.ResolveFinding(c.Request.Context(), tenantID.String(), id, req.Resolution, userID.String()); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"message": "finding resolved"})
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Control Instance Operations
|
||||
// ============================================================================
|
||||
|
||||
// UpsertControlInstance creates or updates a control instance
|
||||
// POST /sdk/v1/vendors/controls
|
||||
func (h *VendorHandlers) UpsertControlInstance(c *gin.Context) {
|
||||
var req struct {
|
||||
VendorID string `json:"vendor_id" binding:"required"`
|
||||
ControlID string `json:"control_id" binding:"required"`
|
||||
ControlDomain string `json:"control_domain"`
|
||||
Status vendor.ControlStatus `json:"status" binding:"required"`
|
||||
EvidenceIDs json.RawMessage `json:"evidence_ids,omitempty"`
|
||||
Notes string `json:"notes,omitempty"`
|
||||
NextAssessmentDate *time.Time `json:"next_assessment_date,omitempty"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
userID := rbac.GetUserID(c)
|
||||
now := time.Now().UTC()
|
||||
userIDStr := userID.String()
|
||||
|
||||
ci := &vendor.ControlInstance{
|
||||
TenantID: tenantID,
|
||||
ControlID: req.ControlID,
|
||||
ControlDomain: req.ControlDomain,
|
||||
Status: req.Status,
|
||||
EvidenceIDs: req.EvidenceIDs,
|
||||
Notes: req.Notes,
|
||||
LastAssessedAt: &now,
|
||||
LastAssessedBy: &userIDStr,
|
||||
NextAssessmentDate: req.NextAssessmentDate,
|
||||
}
|
||||
|
||||
// Parse VendorID
|
||||
vendorUUID, err := parseUUID(req.VendorID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid vendor_id"})
|
||||
return
|
||||
}
|
||||
ci.VendorID = vendorUUID
|
||||
|
||||
if err := h.store.UpsertControlInstance(c.Request.Context(), ci); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"control_instance": ci})
|
||||
}
|
||||
|
||||
// ListControlInstances lists control instances for a vendor
|
||||
// GET /sdk/v1/vendors/controls
|
||||
func (h *VendorHandlers) ListControlInstances(c *gin.Context) {
|
||||
vendorID := c.Query("vendor_id")
|
||||
if vendorID == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "vendor_id query parameter is required"})
|
||||
return
|
||||
}
|
||||
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
|
||||
instances, err := h.store.ListControlInstances(c.Request.Context(), tenantID.String(), vendorID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"control_instances": instances,
|
||||
"total": len(instances),
|
||||
})
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Template Operations
|
||||
// ============================================================================
|
||||
|
||||
// ListTemplates lists available templates
|
||||
// GET /sdk/v1/vendors/templates
|
||||
func (h *VendorHandlers) ListTemplates(c *gin.Context) {
|
||||
templateType := c.DefaultQuery("type", "VENDOR")
|
||||
|
||||
var category, industry *string
|
||||
if cat := c.Query("category"); cat != "" {
|
||||
category = &cat
|
||||
}
|
||||
if ind := c.Query("industry"); ind != "" {
|
||||
industry = &ind
|
||||
}
|
||||
|
||||
templates, err := h.store.ListTemplates(c.Request.Context(), templateType, category, industry)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"templates": templates,
|
||||
"total": len(templates),
|
||||
})
|
||||
}
|
||||
|
||||
// GetTemplate retrieves a template by its template_id string
|
||||
// GET /sdk/v1/vendors/templates/:templateId
|
||||
func (h *VendorHandlers) GetTemplate(c *gin.Context) {
|
||||
templateID := c.Param("templateId")
|
||||
if templateID == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "template ID is required"})
|
||||
return
|
||||
}
|
||||
|
||||
tmpl, err := h.store.GetTemplate(c.Request.Context(), templateID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if tmpl == nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "template not found"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"template": tmpl})
|
||||
}
|
||||
|
||||
// CreateTemplate creates a custom template
|
||||
// POST /sdk/v1/vendors/templates
|
||||
func (h *VendorHandlers) CreateTemplate(c *gin.Context) {
|
||||
var req vendor.CreateTemplateRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
tmpl := &vendor.Template{
|
||||
TemplateType: req.TemplateType,
|
||||
TemplateID: req.TemplateID,
|
||||
Category: req.Category,
|
||||
NameDE: req.NameDE,
|
||||
NameEN: req.NameEN,
|
||||
DescriptionDE: req.DescriptionDE,
|
||||
DescriptionEN: req.DescriptionEN,
|
||||
TemplateData: req.TemplateData,
|
||||
Industry: req.Industry,
|
||||
Tags: req.Tags,
|
||||
IsSystem: req.IsSystem,
|
||||
IsActive: true,
|
||||
}
|
||||
|
||||
// Set tenant for custom (non-system) templates
|
||||
if !req.IsSystem {
|
||||
tid := rbac.GetTenantID(c).String()
|
||||
tmpl.TenantID = &tid
|
||||
}
|
||||
|
||||
if err := h.store.CreateTemplate(c.Request.Context(), tmpl); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, gin.H{"template": tmpl})
|
||||
}
|
||||
|
||||
// ApplyTemplate creates a vendor from a template
|
||||
// POST /sdk/v1/vendors/templates/:templateId/apply
|
||||
func (h *VendorHandlers) ApplyTemplate(c *gin.Context) {
|
||||
templateID := c.Param("templateId")
|
||||
if templateID == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "template ID is required"})
|
||||
return
|
||||
}
|
||||
|
||||
tmpl, err := h.store.GetTemplate(c.Request.Context(), templateID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if tmpl == nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "template not found"})
|
||||
return
|
||||
}
|
||||
|
||||
// Parse template_data to extract suggested vendor fields
|
||||
var templateData struct {
|
||||
ServiceCategory string `json:"service_category"`
|
||||
SuggestedRole string `json:"suggested_role"`
|
||||
DataAccessLevel string `json:"data_access_level"`
|
||||
ReviewFrequency string `json:"review_frequency"`
|
||||
Certifications json.RawMessage `json:"certifications"`
|
||||
ProcessingLocations json.RawMessage `json:"processing_locations"`
|
||||
}
|
||||
if err := json.Unmarshal(tmpl.TemplateData, &templateData); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to parse template data"})
|
||||
return
|
||||
}
|
||||
|
||||
// Optional overrides from request body
|
||||
var overrides struct {
|
||||
Name string `json:"name"`
|
||||
Country string `json:"country"`
|
||||
Website string `json:"website"`
|
||||
ContactName string `json:"contact_name"`
|
||||
ContactEmail string `json:"contact_email"`
|
||||
}
|
||||
c.ShouldBindJSON(&overrides)
|
||||
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
userID := rbac.GetUserID(c)
|
||||
|
||||
v := &vendor.Vendor{
|
||||
TenantID: tenantID,
|
||||
Name: overrides.Name,
|
||||
Country: overrides.Country,
|
||||
Website: overrides.Website,
|
||||
ContactName: overrides.ContactName,
|
||||
ContactEmail: overrides.ContactEmail,
|
||||
Role: vendor.VendorRole(templateData.SuggestedRole),
|
||||
ServiceCategory: templateData.ServiceCategory,
|
||||
DataAccessLevel: templateData.DataAccessLevel,
|
||||
ReviewFrequency: templateData.ReviewFrequency,
|
||||
Certifications: templateData.Certifications,
|
||||
ProcessingLocations: templateData.ProcessingLocations,
|
||||
Status: vendor.VendorStatusActive,
|
||||
TemplateID: &templateID,
|
||||
CreatedBy: userID.String(),
|
||||
}
|
||||
|
||||
if v.Name == "" {
|
||||
v.Name = tmpl.NameDE
|
||||
}
|
||||
if v.Country == "" {
|
||||
v.Country = "DE"
|
||||
}
|
||||
if v.Role == "" {
|
||||
v.Role = vendor.VendorRoleProcessor
|
||||
}
|
||||
|
||||
if err := h.store.CreateVendor(c.Request.Context(), v); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
// Increment template usage
|
||||
_ = h.store.IncrementTemplateUsage(c.Request.Context(), templateID)
|
||||
|
||||
c.JSON(http.StatusCreated, gin.H{
|
||||
"vendor": v,
|
||||
"template_id": templateID,
|
||||
"message": "vendor created from template",
|
||||
})
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Statistics
|
||||
// ============================================================================
|
||||
|
||||
// GetStatistics returns aggregated vendor statistics
|
||||
// GET /sdk/v1/vendors/stats
|
||||
func (h *VendorHandlers) GetStatistics(c *gin.Context) {
|
||||
tenantID := rbac.GetTenantID(c)
|
||||
|
||||
stats, err := h.store.GetVendorStats(c.Request.Context(), tenantID.String())
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, stats)
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Helpers
|
||||
// ============================================================================
|
||||
|
||||
func parseUUID(s string) (uuid.UUID, error) {
|
||||
return uuid.Parse(s)
|
||||
}
|
||||
@@ -1,235 +0,0 @@
|
||||
package dsgvo
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// VVT - Verarbeitungsverzeichnis (Art. 30 DSGVO)
|
||||
// ============================================================================
|
||||
|
||||
// ProcessingActivity represents an entry in the Records of Processing Activities
|
||||
type ProcessingActivity struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
TenantID uuid.UUID `json:"tenant_id"`
|
||||
NamespaceID *uuid.UUID `json:"namespace_id,omitempty"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Purpose string `json:"purpose"`
|
||||
LegalBasis string `json:"legal_basis"` // consent, contract, legal_obligation, vital_interests, public_interest, legitimate_interests
|
||||
LegalBasisDetails string `json:"legal_basis_details,omitempty"`
|
||||
DataCategories []string `json:"data_categories"` // personal, sensitive, health, financial, etc.
|
||||
DataSubjectCategories []string `json:"data_subject_categories"` // customers, employees, suppliers, etc.
|
||||
Recipients []string `json:"recipients"` // Internal departments, external processors
|
||||
ThirdCountryTransfer bool `json:"third_country_transfer"`
|
||||
TransferSafeguards string `json:"transfer_safeguards,omitempty"` // SCCs, adequacy decision, BCRs
|
||||
RetentionPeriod string `json:"retention_period"`
|
||||
RetentionPolicyID *uuid.UUID `json:"retention_policy_id,omitempty"`
|
||||
TOMReference []uuid.UUID `json:"tom_reference,omitempty"` // Links to TOM entries
|
||||
DSFARequired bool `json:"dsfa_required"`
|
||||
DSFAID *uuid.UUID `json:"dsfa_id,omitempty"`
|
||||
ResponsiblePerson string `json:"responsible_person"`
|
||||
ResponsibleDepartment string `json:"responsible_department"`
|
||||
Systems []string `json:"systems"` // IT systems involved
|
||||
Status string `json:"status"` // draft, active, under_review, archived
|
||||
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
CreatedBy uuid.UUID `json:"created_by"`
|
||||
LastReviewedAt *time.Time `json:"last_reviewed_at,omitempty"`
|
||||
NextReviewAt *time.Time `json:"next_review_at,omitempty"`
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// DSFA - Datenschutz-Folgenabschätzung (Art. 35 DSGVO)
|
||||
// ============================================================================
|
||||
|
||||
// DSFA represents a Data Protection Impact Assessment
|
||||
type DSFA struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
TenantID uuid.UUID `json:"tenant_id"`
|
||||
NamespaceID *uuid.UUID `json:"namespace_id,omitempty"`
|
||||
ProcessingActivityID *uuid.UUID `json:"processing_activity_id,omitempty"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
ProcessingDescription string `json:"processing_description"`
|
||||
NecessityAssessment string `json:"necessity_assessment"`
|
||||
ProportionalityAssment string `json:"proportionality_assessment"`
|
||||
Risks []DSFARisk `json:"risks"`
|
||||
Mitigations []DSFAMitigation `json:"mitigations"`
|
||||
DPOConsulted bool `json:"dpo_consulted"`
|
||||
DPOOpinion string `json:"dpo_opinion,omitempty"`
|
||||
AuthorityConsulted bool `json:"authority_consulted"`
|
||||
AuthorityReference string `json:"authority_reference,omitempty"`
|
||||
Status string `json:"status"` // draft, in_progress, completed, approved, rejected
|
||||
OverallRiskLevel string `json:"overall_risk_level"` // low, medium, high, very_high
|
||||
Conclusion string `json:"conclusion"`
|
||||
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
CreatedBy uuid.UUID `json:"created_by"`
|
||||
ApprovedBy *uuid.UUID `json:"approved_by,omitempty"`
|
||||
ApprovedAt *time.Time `json:"approved_at,omitempty"`
|
||||
}
|
||||
|
||||
// DSFARisk represents a risk identified in the DSFA
|
||||
type DSFARisk struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Category string `json:"category"` // confidentiality, integrity, availability, rights_freedoms
|
||||
Description string `json:"description"`
|
||||
Likelihood string `json:"likelihood"` // low, medium, high
|
||||
Impact string `json:"impact"` // low, medium, high
|
||||
RiskLevel string `json:"risk_level"` // calculated: low, medium, high, very_high
|
||||
AffectedData []string `json:"affected_data"`
|
||||
}
|
||||
|
||||
// DSFAMitigation represents a mitigation measure for a DSFA risk
|
||||
type DSFAMitigation struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
RiskID uuid.UUID `json:"risk_id"`
|
||||
Description string `json:"description"`
|
||||
Type string `json:"type"` // technical, organizational, legal
|
||||
Status string `json:"status"` // planned, in_progress, implemented, verified
|
||||
ImplementedAt *time.Time `json:"implemented_at,omitempty"`
|
||||
VerifiedAt *time.Time `json:"verified_at,omitempty"`
|
||||
ResidualRisk string `json:"residual_risk"` // low, medium, high
|
||||
TOMReference *uuid.UUID `json:"tom_reference,omitempty"`
|
||||
ResponsibleParty string `json:"responsible_party"`
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// TOM - Technische und Organisatorische Maßnahmen (Art. 32 DSGVO)
|
||||
// ============================================================================
|
||||
|
||||
// TOM represents a Technical or Organizational Measure
|
||||
type TOM struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
TenantID uuid.UUID `json:"tenant_id"`
|
||||
NamespaceID *uuid.UUID `json:"namespace_id,omitempty"`
|
||||
Category string `json:"category"` // access_control, encryption, pseudonymization, availability, resilience, monitoring, incident_response
|
||||
Subcategory string `json:"subcategory,omitempty"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Type string `json:"type"` // technical, organizational
|
||||
ImplementationStatus string `json:"implementation_status"` // planned, in_progress, implemented, verified, not_applicable
|
||||
ImplementedAt *time.Time `json:"implemented_at,omitempty"`
|
||||
VerifiedAt *time.Time `json:"verified_at,omitempty"`
|
||||
VerifiedBy *uuid.UUID `json:"verified_by,omitempty"`
|
||||
EffectivenessRating string `json:"effectiveness_rating,omitempty"` // low, medium, high
|
||||
Documentation string `json:"documentation,omitempty"`
|
||||
ResponsiblePerson string `json:"responsible_person"`
|
||||
ResponsibleDepartment string `json:"responsible_department"`
|
||||
ReviewFrequency string `json:"review_frequency"` // monthly, quarterly, annually
|
||||
LastReviewAt *time.Time `json:"last_review_at,omitempty"`
|
||||
NextReviewAt *time.Time `json:"next_review_at,omitempty"`
|
||||
RelatedControls []string `json:"related_controls,omitempty"` // ISO 27001 controls, SOC2, etc.
|
||||
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
CreatedBy uuid.UUID `json:"created_by"`
|
||||
}
|
||||
|
||||
// TOMCategory represents predefined TOM categories per Art. 32 DSGVO
|
||||
var TOMCategories = []string{
|
||||
"access_control", // Zutrittskontrolle
|
||||
"admission_control", // Zugangskontrolle
|
||||
"access_management", // Zugriffskontrolle
|
||||
"transfer_control", // Weitergabekontrolle
|
||||
"input_control", // Eingabekontrolle
|
||||
"availability_control", // Verfügbarkeitskontrolle
|
||||
"separation_control", // Trennungskontrolle
|
||||
"encryption", // Verschlüsselung
|
||||
"pseudonymization", // Pseudonymisierung
|
||||
"resilience", // Belastbarkeit
|
||||
"recovery", // Wiederherstellung
|
||||
"testing", // Regelmäßige Überprüfung
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// DSR - Data Subject Requests / Betroffenenrechte (Art. 15-22 DSGVO)
|
||||
// ============================================================================
|
||||
|
||||
// DSR represents a Data Subject Request
|
||||
type DSR struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
TenantID uuid.UUID `json:"tenant_id"`
|
||||
NamespaceID *uuid.UUID `json:"namespace_id,omitempty"`
|
||||
RequestType string `json:"request_type"` // access, rectification, erasure, restriction, portability, objection
|
||||
Status string `json:"status"` // received, verified, in_progress, completed, rejected, extended
|
||||
SubjectName string `json:"subject_name"`
|
||||
SubjectEmail string `json:"subject_email"`
|
||||
SubjectIdentifier string `json:"subject_identifier,omitempty"` // Customer ID, User ID, etc.
|
||||
RequestDescription string `json:"request_description"`
|
||||
RequestChannel string `json:"request_channel"` // email, form, phone, letter
|
||||
ReceivedAt time.Time `json:"received_at"`
|
||||
VerifiedAt *time.Time `json:"verified_at,omitempty"`
|
||||
VerificationMethod string `json:"verification_method,omitempty"`
|
||||
DeadlineAt time.Time `json:"deadline_at"` // Art. 12(3): 1 month, extendable by 2 months
|
||||
ExtendedDeadlineAt *time.Time `json:"extended_deadline_at,omitempty"`
|
||||
ExtensionReason string `json:"extension_reason,omitempty"`
|
||||
CompletedAt *time.Time `json:"completed_at,omitempty"`
|
||||
ResponseSent bool `json:"response_sent"`
|
||||
ResponseSentAt *time.Time `json:"response_sent_at,omitempty"`
|
||||
ResponseMethod string `json:"response_method,omitempty"`
|
||||
RejectionReason string `json:"rejection_reason,omitempty"`
|
||||
Notes string `json:"notes,omitempty"`
|
||||
AffectedSystems []string `json:"affected_systems,omitempty"`
|
||||
AssignedTo *uuid.UUID `json:"assigned_to,omitempty"`
|
||||
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
CreatedBy uuid.UUID `json:"created_by"`
|
||||
}
|
||||
|
||||
// DSRType represents the types of data subject requests
|
||||
var DSRTypes = map[string]string{
|
||||
"access": "Art. 15 - Auskunftsrecht",
|
||||
"rectification": "Art. 16 - Recht auf Berichtigung",
|
||||
"erasure": "Art. 17 - Recht auf Löschung",
|
||||
"restriction": "Art. 18 - Recht auf Einschränkung",
|
||||
"portability": "Art. 20 - Recht auf Datenübertragbarkeit",
|
||||
"objection": "Art. 21 - Widerspruchsrecht",
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Retention - Löschfristen (Art. 17 DSGVO)
|
||||
// ============================================================================
|
||||
|
||||
// RetentionPolicy represents a data retention policy
|
||||
type RetentionPolicy struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
TenantID uuid.UUID `json:"tenant_id"`
|
||||
NamespaceID *uuid.UUID `json:"namespace_id,omitempty"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
DataCategory string `json:"data_category"`
|
||||
RetentionPeriodDays int `json:"retention_period_days"`
|
||||
RetentionPeriodText string `json:"retention_period_text"` // Human readable: "3 Jahre", "10 Jahre nach Vertragsende"
|
||||
LegalBasis string `json:"legal_basis"` // Legal requirement, consent, legitimate interest
|
||||
LegalReference string `json:"legal_reference,omitempty"` // § 147 AO, § 257 HGB, etc.
|
||||
DeletionMethod string `json:"deletion_method"` // automatic, manual, anonymization
|
||||
DeletionProcedure string `json:"deletion_procedure,omitempty"`
|
||||
ExceptionCriteria string `json:"exception_criteria,omitempty"`
|
||||
ApplicableSystems []string `json:"applicable_systems,omitempty"`
|
||||
ResponsiblePerson string `json:"responsible_person"`
|
||||
ResponsibleDepartment string `json:"responsible_department"`
|
||||
Status string `json:"status"` // draft, active, archived
|
||||
LastReviewAt *time.Time `json:"last_review_at,omitempty"`
|
||||
NextReviewAt *time.Time `json:"next_review_at,omitempty"`
|
||||
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
CreatedBy uuid.UUID `json:"created_by"`
|
||||
}
|
||||
|
||||
// CommonRetentionPeriods defines common retention periods in German law
|
||||
var CommonRetentionPeriods = map[string]int{
|
||||
"steuerlich_10_jahre": 3650, // § 147 AO - Buchungsbelege
|
||||
"handelsrechtlich_6_jahre": 2190, // § 257 HGB - Handelsbriefe
|
||||
"arbeitsrechtlich_3_jahre": 1095, // Lohnunterlagen nach Ausscheiden
|
||||
"bewerbungen_6_monate": 180, // AGG-Frist
|
||||
"consent_widerruf_3_jahre": 1095, // Nachweis der Einwilligung
|
||||
"vertragsunterlagen_3_jahre": 1095, // Verjährungsfrist
|
||||
}
|
||||
@@ -1,664 +0,0 @@
|
||||
package dsgvo
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// Store handles DSGVO data persistence
|
||||
type Store struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
// NewStore creates a new DSGVO store
|
||||
func NewStore(pool *pgxpool.Pool) *Store {
|
||||
return &Store{pool: pool}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// VVT - Verarbeitungsverzeichnis
|
||||
// ============================================================================
|
||||
|
||||
// CreateProcessingActivity creates a new processing activity
|
||||
func (s *Store) CreateProcessingActivity(ctx context.Context, pa *ProcessingActivity) error {
|
||||
pa.ID = uuid.New()
|
||||
pa.CreatedAt = time.Now().UTC()
|
||||
pa.UpdatedAt = pa.CreatedAt
|
||||
|
||||
metadata, _ := json.Marshal(pa.Metadata)
|
||||
dataCategories, _ := json.Marshal(pa.DataCategories)
|
||||
dataSubjectCategories, _ := json.Marshal(pa.DataSubjectCategories)
|
||||
recipients, _ := json.Marshal(pa.Recipients)
|
||||
tomReference, _ := json.Marshal(pa.TOMReference)
|
||||
systems, _ := json.Marshal(pa.Systems)
|
||||
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
INSERT INTO dsgvo_processing_activities (
|
||||
id, tenant_id, namespace_id, name, description, purpose, legal_basis, legal_basis_details,
|
||||
data_categories, data_subject_categories, recipients, third_country_transfer, transfer_safeguards,
|
||||
retention_period, retention_policy_id, tom_reference, dsfa_required, dsfa_id,
|
||||
responsible_person, responsible_department, systems, status, metadata,
|
||||
created_at, updated_at, created_by, last_reviewed_at, next_review_at
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, $26, $27, $28)
|
||||
`, pa.ID, pa.TenantID, pa.NamespaceID, pa.Name, pa.Description, pa.Purpose, pa.LegalBasis, pa.LegalBasisDetails,
|
||||
dataCategories, dataSubjectCategories, recipients, pa.ThirdCountryTransfer, pa.TransferSafeguards,
|
||||
pa.RetentionPeriod, pa.RetentionPolicyID, tomReference, pa.DSFARequired, pa.DSFAID,
|
||||
pa.ResponsiblePerson, pa.ResponsibleDepartment, systems, pa.Status, metadata,
|
||||
pa.CreatedAt, pa.UpdatedAt, pa.CreatedBy, pa.LastReviewedAt, pa.NextReviewAt)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// GetProcessingActivity retrieves a processing activity by ID
|
||||
func (s *Store) GetProcessingActivity(ctx context.Context, id uuid.UUID) (*ProcessingActivity, error) {
|
||||
var pa ProcessingActivity
|
||||
var metadata, dataCategories, dataSubjectCategories, recipients, tomReference, systems []byte
|
||||
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT id, tenant_id, namespace_id, name, description, purpose, legal_basis, legal_basis_details,
|
||||
data_categories, data_subject_categories, recipients, third_country_transfer, transfer_safeguards,
|
||||
retention_period, retention_policy_id, tom_reference, dsfa_required, dsfa_id,
|
||||
responsible_person, responsible_department, systems, status, metadata,
|
||||
created_at, updated_at, created_by, last_reviewed_at, next_review_at
|
||||
FROM dsgvo_processing_activities WHERE id = $1
|
||||
`, id).Scan(&pa.ID, &pa.TenantID, &pa.NamespaceID, &pa.Name, &pa.Description, &pa.Purpose, &pa.LegalBasis, &pa.LegalBasisDetails,
|
||||
&dataCategories, &dataSubjectCategories, &recipients, &pa.ThirdCountryTransfer, &pa.TransferSafeguards,
|
||||
&pa.RetentionPeriod, &pa.RetentionPolicyID, &tomReference, &pa.DSFARequired, &pa.DSFAID,
|
||||
&pa.ResponsiblePerson, &pa.ResponsibleDepartment, &systems, &pa.Status, &metadata,
|
||||
&pa.CreatedAt, &pa.UpdatedAt, &pa.CreatedBy, &pa.LastReviewedAt, &pa.NextReviewAt)
|
||||
|
||||
if err == pgx.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
json.Unmarshal(metadata, &pa.Metadata)
|
||||
json.Unmarshal(dataCategories, &pa.DataCategories)
|
||||
json.Unmarshal(dataSubjectCategories, &pa.DataSubjectCategories)
|
||||
json.Unmarshal(recipients, &pa.Recipients)
|
||||
json.Unmarshal(tomReference, &pa.TOMReference)
|
||||
json.Unmarshal(systems, &pa.Systems)
|
||||
|
||||
return &pa, nil
|
||||
}
|
||||
|
||||
// ListProcessingActivities lists processing activities for a tenant
|
||||
func (s *Store) ListProcessingActivities(ctx context.Context, tenantID uuid.UUID, namespaceID *uuid.UUID) ([]ProcessingActivity, error) {
|
||||
query := `
|
||||
SELECT id, tenant_id, namespace_id, name, description, purpose, legal_basis, legal_basis_details,
|
||||
data_categories, data_subject_categories, recipients, third_country_transfer, transfer_safeguards,
|
||||
retention_period, retention_policy_id, tom_reference, dsfa_required, dsfa_id,
|
||||
responsible_person, responsible_department, systems, status, metadata,
|
||||
created_at, updated_at, created_by, last_reviewed_at, next_review_at
|
||||
FROM dsgvo_processing_activities WHERE tenant_id = $1`
|
||||
|
||||
args := []interface{}{tenantID}
|
||||
if namespaceID != nil {
|
||||
query += " AND namespace_id = $2"
|
||||
args = append(args, *namespaceID)
|
||||
}
|
||||
query += " ORDER BY name"
|
||||
|
||||
rows, err := s.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var activities []ProcessingActivity
|
||||
for rows.Next() {
|
||||
var pa ProcessingActivity
|
||||
var metadata, dataCategories, dataSubjectCategories, recipients, tomReference, systems []byte
|
||||
|
||||
err := rows.Scan(&pa.ID, &pa.TenantID, &pa.NamespaceID, &pa.Name, &pa.Description, &pa.Purpose, &pa.LegalBasis, &pa.LegalBasisDetails,
|
||||
&dataCategories, &dataSubjectCategories, &recipients, &pa.ThirdCountryTransfer, &pa.TransferSafeguards,
|
||||
&pa.RetentionPeriod, &pa.RetentionPolicyID, &tomReference, &pa.DSFARequired, &pa.DSFAID,
|
||||
&pa.ResponsiblePerson, &pa.ResponsibleDepartment, &systems, &pa.Status, &metadata,
|
||||
&pa.CreatedAt, &pa.UpdatedAt, &pa.CreatedBy, &pa.LastReviewedAt, &pa.NextReviewAt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
json.Unmarshal(metadata, &pa.Metadata)
|
||||
json.Unmarshal(dataCategories, &pa.DataCategories)
|
||||
json.Unmarshal(dataSubjectCategories, &pa.DataSubjectCategories)
|
||||
json.Unmarshal(recipients, &pa.Recipients)
|
||||
json.Unmarshal(tomReference, &pa.TOMReference)
|
||||
json.Unmarshal(systems, &pa.Systems)
|
||||
|
||||
activities = append(activities, pa)
|
||||
}
|
||||
|
||||
return activities, nil
|
||||
}
|
||||
|
||||
// UpdateProcessingActivity updates a processing activity
|
||||
func (s *Store) UpdateProcessingActivity(ctx context.Context, pa *ProcessingActivity) error {
|
||||
pa.UpdatedAt = time.Now().UTC()
|
||||
|
||||
metadata, _ := json.Marshal(pa.Metadata)
|
||||
dataCategories, _ := json.Marshal(pa.DataCategories)
|
||||
dataSubjectCategories, _ := json.Marshal(pa.DataSubjectCategories)
|
||||
recipients, _ := json.Marshal(pa.Recipients)
|
||||
tomReference, _ := json.Marshal(pa.TOMReference)
|
||||
systems, _ := json.Marshal(pa.Systems)
|
||||
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
UPDATE dsgvo_processing_activities SET
|
||||
name = $2, description = $3, purpose = $4, legal_basis = $5, legal_basis_details = $6,
|
||||
data_categories = $7, data_subject_categories = $8, recipients = $9, third_country_transfer = $10,
|
||||
transfer_safeguards = $11, retention_period = $12, retention_policy_id = $13, tom_reference = $14,
|
||||
dsfa_required = $15, dsfa_id = $16, responsible_person = $17, responsible_department = $18,
|
||||
systems = $19, status = $20, metadata = $21, updated_at = $22, last_reviewed_at = $23, next_review_at = $24
|
||||
WHERE id = $1
|
||||
`, pa.ID, pa.Name, pa.Description, pa.Purpose, pa.LegalBasis, pa.LegalBasisDetails,
|
||||
dataCategories, dataSubjectCategories, recipients, pa.ThirdCountryTransfer,
|
||||
pa.TransferSafeguards, pa.RetentionPeriod, pa.RetentionPolicyID, tomReference,
|
||||
pa.DSFARequired, pa.DSFAID, pa.ResponsiblePerson, pa.ResponsibleDepartment,
|
||||
systems, pa.Status, metadata, pa.UpdatedAt, pa.LastReviewedAt, pa.NextReviewAt)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// DeleteProcessingActivity deletes a processing activity
|
||||
func (s *Store) DeleteProcessingActivity(ctx context.Context, id uuid.UUID) error {
|
||||
_, err := s.pool.Exec(ctx, "DELETE FROM dsgvo_processing_activities WHERE id = $1", id)
|
||||
return err
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// TOM - Technische und Organisatorische Maßnahmen
|
||||
// ============================================================================
|
||||
|
||||
// CreateTOM creates a new TOM entry
|
||||
func (s *Store) CreateTOM(ctx context.Context, tom *TOM) error {
|
||||
tom.ID = uuid.New()
|
||||
tom.CreatedAt = time.Now().UTC()
|
||||
tom.UpdatedAt = tom.CreatedAt
|
||||
|
||||
metadata, _ := json.Marshal(tom.Metadata)
|
||||
relatedControls, _ := json.Marshal(tom.RelatedControls)
|
||||
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
INSERT INTO dsgvo_tom (
|
||||
id, tenant_id, namespace_id, category, subcategory, name, description, type,
|
||||
implementation_status, implemented_at, verified_at, verified_by, effectiveness_rating,
|
||||
documentation, responsible_person, responsible_department, review_frequency,
|
||||
last_review_at, next_review_at, related_controls, metadata, created_at, updated_at, created_by
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24)
|
||||
`, tom.ID, tom.TenantID, tom.NamespaceID, tom.Category, tom.Subcategory, tom.Name, tom.Description, tom.Type,
|
||||
tom.ImplementationStatus, tom.ImplementedAt, tom.VerifiedAt, tom.VerifiedBy, tom.EffectivenessRating,
|
||||
tom.Documentation, tom.ResponsiblePerson, tom.ResponsibleDepartment, tom.ReviewFrequency,
|
||||
tom.LastReviewAt, tom.NextReviewAt, relatedControls, metadata, tom.CreatedAt, tom.UpdatedAt, tom.CreatedBy)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// GetTOM retrieves a TOM by ID
|
||||
func (s *Store) GetTOM(ctx context.Context, id uuid.UUID) (*TOM, error) {
|
||||
var tom TOM
|
||||
var metadata, relatedControls []byte
|
||||
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT id, tenant_id, namespace_id, category, subcategory, name, description, type,
|
||||
implementation_status, implemented_at, verified_at, verified_by, effectiveness_rating,
|
||||
documentation, responsible_person, responsible_department, review_frequency,
|
||||
last_review_at, next_review_at, related_controls, metadata, created_at, updated_at, created_by
|
||||
FROM dsgvo_tom WHERE id = $1
|
||||
`, id).Scan(&tom.ID, &tom.TenantID, &tom.NamespaceID, &tom.Category, &tom.Subcategory, &tom.Name, &tom.Description, &tom.Type,
|
||||
&tom.ImplementationStatus, &tom.ImplementedAt, &tom.VerifiedAt, &tom.VerifiedBy, &tom.EffectivenessRating,
|
||||
&tom.Documentation, &tom.ResponsiblePerson, &tom.ResponsibleDepartment, &tom.ReviewFrequency,
|
||||
&tom.LastReviewAt, &tom.NextReviewAt, &relatedControls, &metadata, &tom.CreatedAt, &tom.UpdatedAt, &tom.CreatedBy)
|
||||
|
||||
if err == pgx.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
json.Unmarshal(metadata, &tom.Metadata)
|
||||
json.Unmarshal(relatedControls, &tom.RelatedControls)
|
||||
|
||||
return &tom, nil
|
||||
}
|
||||
|
||||
// ListTOMs lists TOMs for a tenant
|
||||
func (s *Store) ListTOMs(ctx context.Context, tenantID uuid.UUID, category string) ([]TOM, error) {
|
||||
query := `
|
||||
SELECT id, tenant_id, namespace_id, category, subcategory, name, description, type,
|
||||
implementation_status, implemented_at, verified_at, verified_by, effectiveness_rating,
|
||||
documentation, responsible_person, responsible_department, review_frequency,
|
||||
last_review_at, next_review_at, related_controls, metadata, created_at, updated_at, created_by
|
||||
FROM dsgvo_tom WHERE tenant_id = $1`
|
||||
|
||||
args := []interface{}{tenantID}
|
||||
if category != "" {
|
||||
query += " AND category = $2"
|
||||
args = append(args, category)
|
||||
}
|
||||
query += " ORDER BY category, name"
|
||||
|
||||
rows, err := s.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var toms []TOM
|
||||
for rows.Next() {
|
||||
var tom TOM
|
||||
var metadata, relatedControls []byte
|
||||
|
||||
err := rows.Scan(&tom.ID, &tom.TenantID, &tom.NamespaceID, &tom.Category, &tom.Subcategory, &tom.Name, &tom.Description, &tom.Type,
|
||||
&tom.ImplementationStatus, &tom.ImplementedAt, &tom.VerifiedAt, &tom.VerifiedBy, &tom.EffectivenessRating,
|
||||
&tom.Documentation, &tom.ResponsiblePerson, &tom.ResponsibleDepartment, &tom.ReviewFrequency,
|
||||
&tom.LastReviewAt, &tom.NextReviewAt, &relatedControls, &metadata, &tom.CreatedAt, &tom.UpdatedAt, &tom.CreatedBy)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
json.Unmarshal(metadata, &tom.Metadata)
|
||||
json.Unmarshal(relatedControls, &tom.RelatedControls)
|
||||
|
||||
toms = append(toms, tom)
|
||||
}
|
||||
|
||||
return toms, nil
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// DSR - Data Subject Requests
|
||||
// ============================================================================
|
||||
|
||||
// CreateDSR creates a new DSR
|
||||
func (s *Store) CreateDSR(ctx context.Context, dsr *DSR) error {
|
||||
dsr.ID = uuid.New()
|
||||
dsr.CreatedAt = time.Now().UTC()
|
||||
dsr.UpdatedAt = dsr.CreatedAt
|
||||
|
||||
// Default deadline: 1 month from receipt
|
||||
if dsr.DeadlineAt.IsZero() {
|
||||
dsr.DeadlineAt = dsr.ReceivedAt.AddDate(0, 1, 0)
|
||||
}
|
||||
|
||||
metadata, _ := json.Marshal(dsr.Metadata)
|
||||
affectedSystems, _ := json.Marshal(dsr.AffectedSystems)
|
||||
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
INSERT INTO dsgvo_dsr (
|
||||
id, tenant_id, namespace_id, request_type, status, subject_name, subject_email,
|
||||
subject_identifier, request_description, request_channel, received_at, verified_at,
|
||||
verification_method, deadline_at, extended_deadline_at, extension_reason,
|
||||
completed_at, response_sent, response_sent_at, response_method, rejection_reason,
|
||||
notes, affected_systems, assigned_to, metadata, created_at, updated_at, created_by
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, $26, $27, $28)
|
||||
`, dsr.ID, dsr.TenantID, dsr.NamespaceID, dsr.RequestType, dsr.Status, dsr.SubjectName, dsr.SubjectEmail,
|
||||
dsr.SubjectIdentifier, dsr.RequestDescription, dsr.RequestChannel, dsr.ReceivedAt, dsr.VerifiedAt,
|
||||
dsr.VerificationMethod, dsr.DeadlineAt, dsr.ExtendedDeadlineAt, dsr.ExtensionReason,
|
||||
dsr.CompletedAt, dsr.ResponseSent, dsr.ResponseSentAt, dsr.ResponseMethod, dsr.RejectionReason,
|
||||
dsr.Notes, affectedSystems, dsr.AssignedTo, metadata, dsr.CreatedAt, dsr.UpdatedAt, dsr.CreatedBy)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// GetDSR retrieves a DSR by ID
|
||||
func (s *Store) GetDSR(ctx context.Context, id uuid.UUID) (*DSR, error) {
|
||||
var dsr DSR
|
||||
var metadata, affectedSystems []byte
|
||||
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT id, tenant_id, namespace_id, request_type, status, subject_name, subject_email,
|
||||
subject_identifier, request_description, request_channel, received_at, verified_at,
|
||||
verification_method, deadline_at, extended_deadline_at, extension_reason,
|
||||
completed_at, response_sent, response_sent_at, response_method, rejection_reason,
|
||||
notes, affected_systems, assigned_to, metadata, created_at, updated_at, created_by
|
||||
FROM dsgvo_dsr WHERE id = $1
|
||||
`, id).Scan(&dsr.ID, &dsr.TenantID, &dsr.NamespaceID, &dsr.RequestType, &dsr.Status, &dsr.SubjectName, &dsr.SubjectEmail,
|
||||
&dsr.SubjectIdentifier, &dsr.RequestDescription, &dsr.RequestChannel, &dsr.ReceivedAt, &dsr.VerifiedAt,
|
||||
&dsr.VerificationMethod, &dsr.DeadlineAt, &dsr.ExtendedDeadlineAt, &dsr.ExtensionReason,
|
||||
&dsr.CompletedAt, &dsr.ResponseSent, &dsr.ResponseSentAt, &dsr.ResponseMethod, &dsr.RejectionReason,
|
||||
&dsr.Notes, &affectedSystems, &dsr.AssignedTo, &metadata, &dsr.CreatedAt, &dsr.UpdatedAt, &dsr.CreatedBy)
|
||||
|
||||
if err == pgx.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
json.Unmarshal(metadata, &dsr.Metadata)
|
||||
json.Unmarshal(affectedSystems, &dsr.AffectedSystems)
|
||||
|
||||
return &dsr, nil
|
||||
}
|
||||
|
||||
// ListDSRs lists DSRs for a tenant with optional filters
|
||||
func (s *Store) ListDSRs(ctx context.Context, tenantID uuid.UUID, status string, requestType string) ([]DSR, error) {
|
||||
query := `
|
||||
SELECT id, tenant_id, namespace_id, request_type, status, subject_name, subject_email,
|
||||
subject_identifier, request_description, request_channel, received_at, verified_at,
|
||||
verification_method, deadline_at, extended_deadline_at, extension_reason,
|
||||
completed_at, response_sent, response_sent_at, response_method, rejection_reason,
|
||||
notes, affected_systems, assigned_to, metadata, created_at, updated_at, created_by
|
||||
FROM dsgvo_dsr WHERE tenant_id = $1`
|
||||
|
||||
args := []interface{}{tenantID}
|
||||
argIdx := 2
|
||||
|
||||
if status != "" {
|
||||
query += " AND status = $" + string(rune('0'+argIdx))
|
||||
args = append(args, status)
|
||||
argIdx++
|
||||
}
|
||||
if requestType != "" {
|
||||
query += " AND request_type = $" + string(rune('0'+argIdx))
|
||||
args = append(args, requestType)
|
||||
}
|
||||
query += " ORDER BY deadline_at ASC"
|
||||
|
||||
rows, err := s.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var dsrs []DSR
|
||||
for rows.Next() {
|
||||
var dsr DSR
|
||||
var metadata, affectedSystems []byte
|
||||
|
||||
err := rows.Scan(&dsr.ID, &dsr.TenantID, &dsr.NamespaceID, &dsr.RequestType, &dsr.Status, &dsr.SubjectName, &dsr.SubjectEmail,
|
||||
&dsr.SubjectIdentifier, &dsr.RequestDescription, &dsr.RequestChannel, &dsr.ReceivedAt, &dsr.VerifiedAt,
|
||||
&dsr.VerificationMethod, &dsr.DeadlineAt, &dsr.ExtendedDeadlineAt, &dsr.ExtensionReason,
|
||||
&dsr.CompletedAt, &dsr.ResponseSent, &dsr.ResponseSentAt, &dsr.ResponseMethod, &dsr.RejectionReason,
|
||||
&dsr.Notes, &affectedSystems, &dsr.AssignedTo, &metadata, &dsr.CreatedAt, &dsr.UpdatedAt, &dsr.CreatedBy)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
json.Unmarshal(metadata, &dsr.Metadata)
|
||||
json.Unmarshal(affectedSystems, &dsr.AffectedSystems)
|
||||
|
||||
dsrs = append(dsrs, dsr)
|
||||
}
|
||||
|
||||
return dsrs, nil
|
||||
}
|
||||
|
||||
// UpdateDSR updates a DSR
|
||||
func (s *Store) UpdateDSR(ctx context.Context, dsr *DSR) error {
|
||||
dsr.UpdatedAt = time.Now().UTC()
|
||||
|
||||
metadata, _ := json.Marshal(dsr.Metadata)
|
||||
affectedSystems, _ := json.Marshal(dsr.AffectedSystems)
|
||||
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
UPDATE dsgvo_dsr SET
|
||||
status = $2, verified_at = $3, verification_method = $4, extended_deadline_at = $5,
|
||||
extension_reason = $6, completed_at = $7, response_sent = $8, response_sent_at = $9,
|
||||
response_method = $10, rejection_reason = $11, notes = $12, affected_systems = $13,
|
||||
assigned_to = $14, metadata = $15, updated_at = $16
|
||||
WHERE id = $1
|
||||
`, dsr.ID, dsr.Status, dsr.VerifiedAt, dsr.VerificationMethod, dsr.ExtendedDeadlineAt,
|
||||
dsr.ExtensionReason, dsr.CompletedAt, dsr.ResponseSent, dsr.ResponseSentAt,
|
||||
dsr.ResponseMethod, dsr.RejectionReason, dsr.Notes, affectedSystems,
|
||||
dsr.AssignedTo, metadata, dsr.UpdatedAt)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Retention Policies
|
||||
// ============================================================================
|
||||
|
||||
// CreateRetentionPolicy creates a new retention policy
|
||||
func (s *Store) CreateRetentionPolicy(ctx context.Context, rp *RetentionPolicy) error {
|
||||
rp.ID = uuid.New()
|
||||
rp.CreatedAt = time.Now().UTC()
|
||||
rp.UpdatedAt = rp.CreatedAt
|
||||
|
||||
metadata, _ := json.Marshal(rp.Metadata)
|
||||
applicableSystems, _ := json.Marshal(rp.ApplicableSystems)
|
||||
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
INSERT INTO dsgvo_retention_policies (
|
||||
id, tenant_id, namespace_id, name, description, data_category, retention_period_days,
|
||||
retention_period_text, legal_basis, legal_reference, deletion_method, deletion_procedure,
|
||||
exception_criteria, applicable_systems, responsible_person, responsible_department,
|
||||
status, last_review_at, next_review_at, metadata, created_at, updated_at, created_by
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23)
|
||||
`, rp.ID, rp.TenantID, rp.NamespaceID, rp.Name, rp.Description, rp.DataCategory, rp.RetentionPeriodDays,
|
||||
rp.RetentionPeriodText, rp.LegalBasis, rp.LegalReference, rp.DeletionMethod, rp.DeletionProcedure,
|
||||
rp.ExceptionCriteria, applicableSystems, rp.ResponsiblePerson, rp.ResponsibleDepartment,
|
||||
rp.Status, rp.LastReviewAt, rp.NextReviewAt, metadata, rp.CreatedAt, rp.UpdatedAt, rp.CreatedBy)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// ListRetentionPolicies lists retention policies for a tenant
|
||||
func (s *Store) ListRetentionPolicies(ctx context.Context, tenantID uuid.UUID) ([]RetentionPolicy, error) {
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT id, tenant_id, namespace_id, name, description, data_category, retention_period_days,
|
||||
retention_period_text, legal_basis, legal_reference, deletion_method, deletion_procedure,
|
||||
exception_criteria, applicable_systems, responsible_person, responsible_department,
|
||||
status, last_review_at, next_review_at, metadata, created_at, updated_at, created_by
|
||||
FROM dsgvo_retention_policies WHERE tenant_id = $1 ORDER BY name
|
||||
`, tenantID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var policies []RetentionPolicy
|
||||
for rows.Next() {
|
||||
var rp RetentionPolicy
|
||||
var metadata, applicableSystems []byte
|
||||
|
||||
err := rows.Scan(&rp.ID, &rp.TenantID, &rp.NamespaceID, &rp.Name, &rp.Description, &rp.DataCategory, &rp.RetentionPeriodDays,
|
||||
&rp.RetentionPeriodText, &rp.LegalBasis, &rp.LegalReference, &rp.DeletionMethod, &rp.DeletionProcedure,
|
||||
&rp.ExceptionCriteria, &applicableSystems, &rp.ResponsiblePerson, &rp.ResponsibleDepartment,
|
||||
&rp.Status, &rp.LastReviewAt, &rp.NextReviewAt, &metadata, &rp.CreatedAt, &rp.UpdatedAt, &rp.CreatedBy)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
json.Unmarshal(metadata, &rp.Metadata)
|
||||
json.Unmarshal(applicableSystems, &rp.ApplicableSystems)
|
||||
|
||||
policies = append(policies, rp)
|
||||
}
|
||||
|
||||
return policies, nil
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// DSFA - Datenschutz-Folgenabschätzung
|
||||
// ============================================================================
|
||||
|
||||
// CreateDSFA creates a new DSFA
|
||||
func (s *Store) CreateDSFA(ctx context.Context, dsfa *DSFA) error {
|
||||
dsfa.ID = uuid.New()
|
||||
dsfa.CreatedAt = time.Now().UTC()
|
||||
dsfa.UpdatedAt = dsfa.CreatedAt
|
||||
|
||||
metadata, _ := json.Marshal(dsfa.Metadata)
|
||||
risks, _ := json.Marshal(dsfa.Risks)
|
||||
mitigations, _ := json.Marshal(dsfa.Mitigations)
|
||||
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
INSERT INTO dsgvo_dsfa (
|
||||
id, tenant_id, namespace_id, processing_activity_id, name, description,
|
||||
processing_description, necessity_assessment, proportionality_assessment,
|
||||
risks, mitigations, dpo_consulted, dpo_opinion, authority_consulted, authority_reference,
|
||||
status, overall_risk_level, conclusion, metadata, created_at, updated_at, created_by,
|
||||
approved_by, approved_at
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24)
|
||||
`, dsfa.ID, dsfa.TenantID, dsfa.NamespaceID, dsfa.ProcessingActivityID, dsfa.Name, dsfa.Description,
|
||||
dsfa.ProcessingDescription, dsfa.NecessityAssessment, dsfa.ProportionalityAssment,
|
||||
risks, mitigations, dsfa.DPOConsulted, dsfa.DPOOpinion, dsfa.AuthorityConsulted, dsfa.AuthorityReference,
|
||||
dsfa.Status, dsfa.OverallRiskLevel, dsfa.Conclusion, metadata, dsfa.CreatedAt, dsfa.UpdatedAt, dsfa.CreatedBy,
|
||||
dsfa.ApprovedBy, dsfa.ApprovedAt)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// GetDSFA retrieves a DSFA by ID
|
||||
func (s *Store) GetDSFA(ctx context.Context, id uuid.UUID) (*DSFA, error) {
|
||||
var dsfa DSFA
|
||||
var metadata, risks, mitigations []byte
|
||||
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT id, tenant_id, namespace_id, processing_activity_id, name, description,
|
||||
processing_description, necessity_assessment, proportionality_assessment,
|
||||
risks, mitigations, dpo_consulted, dpo_opinion, authority_consulted, authority_reference,
|
||||
status, overall_risk_level, conclusion, metadata, created_at, updated_at, created_by,
|
||||
approved_by, approved_at
|
||||
FROM dsgvo_dsfa WHERE id = $1
|
||||
`, id).Scan(&dsfa.ID, &dsfa.TenantID, &dsfa.NamespaceID, &dsfa.ProcessingActivityID, &dsfa.Name, &dsfa.Description,
|
||||
&dsfa.ProcessingDescription, &dsfa.NecessityAssessment, &dsfa.ProportionalityAssment,
|
||||
&risks, &mitigations, &dsfa.DPOConsulted, &dsfa.DPOOpinion, &dsfa.AuthorityConsulted, &dsfa.AuthorityReference,
|
||||
&dsfa.Status, &dsfa.OverallRiskLevel, &dsfa.Conclusion, &metadata, &dsfa.CreatedAt, &dsfa.UpdatedAt, &dsfa.CreatedBy,
|
||||
&dsfa.ApprovedBy, &dsfa.ApprovedAt)
|
||||
|
||||
if err == pgx.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
json.Unmarshal(metadata, &dsfa.Metadata)
|
||||
json.Unmarshal(risks, &dsfa.Risks)
|
||||
json.Unmarshal(mitigations, &dsfa.Mitigations)
|
||||
|
||||
return &dsfa, nil
|
||||
}
|
||||
|
||||
// ListDSFAs lists DSFAs for a tenant
|
||||
func (s *Store) ListDSFAs(ctx context.Context, tenantID uuid.UUID, status string) ([]DSFA, error) {
|
||||
query := `
|
||||
SELECT id, tenant_id, namespace_id, processing_activity_id, name, description,
|
||||
processing_description, necessity_assessment, proportionality_assessment,
|
||||
risks, mitigations, dpo_consulted, dpo_opinion, authority_consulted, authority_reference,
|
||||
status, overall_risk_level, conclusion, metadata, created_at, updated_at, created_by,
|
||||
approved_by, approved_at
|
||||
FROM dsgvo_dsfa WHERE tenant_id = $1`
|
||||
|
||||
args := []interface{}{tenantID}
|
||||
if status != "" {
|
||||
query += " AND status = $2"
|
||||
args = append(args, status)
|
||||
}
|
||||
query += " ORDER BY created_at DESC"
|
||||
|
||||
rows, err := s.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var dsfas []DSFA
|
||||
for rows.Next() {
|
||||
var dsfa DSFA
|
||||
var metadata, risks, mitigations []byte
|
||||
|
||||
err := rows.Scan(&dsfa.ID, &dsfa.TenantID, &dsfa.NamespaceID, &dsfa.ProcessingActivityID, &dsfa.Name, &dsfa.Description,
|
||||
&dsfa.ProcessingDescription, &dsfa.NecessityAssessment, &dsfa.ProportionalityAssment,
|
||||
&risks, &mitigations, &dsfa.DPOConsulted, &dsfa.DPOOpinion, &dsfa.AuthorityConsulted, &dsfa.AuthorityReference,
|
||||
&dsfa.Status, &dsfa.OverallRiskLevel, &dsfa.Conclusion, &metadata, &dsfa.CreatedAt, &dsfa.UpdatedAt, &dsfa.CreatedBy,
|
||||
&dsfa.ApprovedBy, &dsfa.ApprovedAt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
json.Unmarshal(metadata, &dsfa.Metadata)
|
||||
json.Unmarshal(risks, &dsfa.Risks)
|
||||
json.Unmarshal(mitigations, &dsfa.Mitigations)
|
||||
|
||||
dsfas = append(dsfas, dsfa)
|
||||
}
|
||||
|
||||
return dsfas, nil
|
||||
}
|
||||
|
||||
// UpdateDSFA updates a DSFA
|
||||
func (s *Store) UpdateDSFA(ctx context.Context, dsfa *DSFA) error {
|
||||
dsfa.UpdatedAt = time.Now().UTC()
|
||||
|
||||
metadata, _ := json.Marshal(dsfa.Metadata)
|
||||
risks, _ := json.Marshal(dsfa.Risks)
|
||||
mitigations, _ := json.Marshal(dsfa.Mitigations)
|
||||
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
UPDATE dsgvo_dsfa SET
|
||||
name = $2, description = $3, processing_description = $4,
|
||||
necessity_assessment = $5, proportionality_assessment = $6,
|
||||
risks = $7, mitigations = $8, dpo_consulted = $9, dpo_opinion = $10,
|
||||
authority_consulted = $11, authority_reference = $12, status = $13,
|
||||
overall_risk_level = $14, conclusion = $15, metadata = $16, updated_at = $17,
|
||||
approved_by = $18, approved_at = $19
|
||||
WHERE id = $1
|
||||
`, dsfa.ID, dsfa.Name, dsfa.Description, dsfa.ProcessingDescription,
|
||||
dsfa.NecessityAssessment, dsfa.ProportionalityAssment,
|
||||
risks, mitigations, dsfa.DPOConsulted, dsfa.DPOOpinion,
|
||||
dsfa.AuthorityConsulted, dsfa.AuthorityReference, dsfa.Status,
|
||||
dsfa.OverallRiskLevel, dsfa.Conclusion, metadata, dsfa.UpdatedAt,
|
||||
dsfa.ApprovedBy, dsfa.ApprovedAt)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// DeleteDSFA deletes a DSFA
|
||||
func (s *Store) DeleteDSFA(ctx context.Context, id uuid.UUID) error {
|
||||
_, err := s.pool.Exec(ctx, "DELETE FROM dsgvo_dsfa WHERE id = $1", id)
|
||||
return err
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Statistics
|
||||
// ============================================================================
|
||||
|
||||
// DSGVOStats contains DSGVO module statistics
|
||||
type DSGVOStats struct {
|
||||
ProcessingActivities int `json:"processing_activities"`
|
||||
ActiveProcessings int `json:"active_processings"`
|
||||
TOMsImplemented int `json:"toms_implemented"`
|
||||
TOMsPlanned int `json:"toms_planned"`
|
||||
OpenDSRs int `json:"open_dsrs"`
|
||||
OverdueDSRs int `json:"overdue_dsrs"`
|
||||
RetentionPolicies int `json:"retention_policies"`
|
||||
DSFAsCompleted int `json:"dsfas_completed"`
|
||||
}
|
||||
|
||||
// GetStats returns DSGVO statistics for a tenant
|
||||
func (s *Store) GetStats(ctx context.Context, tenantID uuid.UUID) (*DSGVOStats, error) {
|
||||
stats := &DSGVOStats{}
|
||||
|
||||
// Processing Activities
|
||||
s.pool.QueryRow(ctx, "SELECT COUNT(*) FROM dsgvo_processing_activities WHERE tenant_id = $1", tenantID).Scan(&stats.ProcessingActivities)
|
||||
s.pool.QueryRow(ctx, "SELECT COUNT(*) FROM dsgvo_processing_activities WHERE tenant_id = $1 AND status = 'active'", tenantID).Scan(&stats.ActiveProcessings)
|
||||
|
||||
// TOMs
|
||||
s.pool.QueryRow(ctx, "SELECT COUNT(*) FROM dsgvo_tom WHERE tenant_id = $1 AND implementation_status = 'implemented'", tenantID).Scan(&stats.TOMsImplemented)
|
||||
s.pool.QueryRow(ctx, "SELECT COUNT(*) FROM dsgvo_tom WHERE tenant_id = $1 AND implementation_status IN ('planned', 'in_progress')", tenantID).Scan(&stats.TOMsPlanned)
|
||||
|
||||
// DSRs
|
||||
s.pool.QueryRow(ctx, "SELECT COUNT(*) FROM dsgvo_dsr WHERE tenant_id = $1 AND status NOT IN ('completed', 'rejected')", tenantID).Scan(&stats.OpenDSRs)
|
||||
s.pool.QueryRow(ctx, "SELECT COUNT(*) FROM dsgvo_dsr WHERE tenant_id = $1 AND status NOT IN ('completed', 'rejected') AND deadline_at < NOW()", tenantID).Scan(&stats.OverdueDSRs)
|
||||
|
||||
// Retention Policies
|
||||
s.pool.QueryRow(ctx, "SELECT COUNT(*) FROM dsgvo_retention_policies WHERE tenant_id = $1 AND status = 'active'", tenantID).Scan(&stats.RetentionPolicies)
|
||||
|
||||
// DSFAs
|
||||
s.pool.QueryRow(ctx, "SELECT COUNT(*) FROM dsgvo_dsfa WHERE tenant_id = $1 AND status = 'approved'", tenantID).Scan(&stats.DSFAsCompleted)
|
||||
|
||||
return stats, nil
|
||||
}
|
||||
@@ -1,305 +0,0 @@
|
||||
package incidents
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// Constants / Enums
|
||||
// ============================================================================
|
||||
|
||||
// IncidentCategory represents the category of a security/data breach incident
|
||||
type IncidentCategory string
|
||||
|
||||
const (
|
||||
IncidentCategoryDataBreach IncidentCategory = "data_breach"
|
||||
IncidentCategoryUnauthorizedAccess IncidentCategory = "unauthorized_access"
|
||||
IncidentCategoryDataLoss IncidentCategory = "data_loss"
|
||||
IncidentCategorySystemCompromise IncidentCategory = "system_compromise"
|
||||
IncidentCategoryPhishing IncidentCategory = "phishing"
|
||||
IncidentCategoryRansomware IncidentCategory = "ransomware"
|
||||
IncidentCategoryInsiderThreat IncidentCategory = "insider_threat"
|
||||
IncidentCategoryPhysicalBreach IncidentCategory = "physical_breach"
|
||||
IncidentCategoryOther IncidentCategory = "other"
|
||||
)
|
||||
|
||||
// IncidentStatus represents the status of an incident through its lifecycle
|
||||
type IncidentStatus string
|
||||
|
||||
const (
|
||||
IncidentStatusDetected IncidentStatus = "detected"
|
||||
IncidentStatusAssessment IncidentStatus = "assessment"
|
||||
IncidentStatusContainment IncidentStatus = "containment"
|
||||
IncidentStatusNotificationRequired IncidentStatus = "notification_required"
|
||||
IncidentStatusNotificationSent IncidentStatus = "notification_sent"
|
||||
IncidentStatusRemediation IncidentStatus = "remediation"
|
||||
IncidentStatusClosed IncidentStatus = "closed"
|
||||
)
|
||||
|
||||
// IncidentSeverity represents the severity level of an incident
|
||||
type IncidentSeverity string
|
||||
|
||||
const (
|
||||
IncidentSeverityCritical IncidentSeverity = "critical"
|
||||
IncidentSeverityHigh IncidentSeverity = "high"
|
||||
IncidentSeverityMedium IncidentSeverity = "medium"
|
||||
IncidentSeverityLow IncidentSeverity = "low"
|
||||
)
|
||||
|
||||
// MeasureType represents the type of corrective measure
|
||||
type MeasureType string
|
||||
|
||||
const (
|
||||
MeasureTypeImmediate MeasureType = "immediate"
|
||||
MeasureTypeLongTerm MeasureType = "long_term"
|
||||
)
|
||||
|
||||
// MeasureStatus represents the status of a corrective measure
|
||||
type MeasureStatus string
|
||||
|
||||
const (
|
||||
MeasureStatusPlanned MeasureStatus = "planned"
|
||||
MeasureStatusInProgress MeasureStatus = "in_progress"
|
||||
MeasureStatusCompleted MeasureStatus = "completed"
|
||||
)
|
||||
|
||||
// NotificationStatus represents the status of a notification (authority or data subject)
|
||||
type NotificationStatus string
|
||||
|
||||
const (
|
||||
NotificationStatusNotRequired NotificationStatus = "not_required"
|
||||
NotificationStatusPending NotificationStatus = "pending"
|
||||
NotificationStatusSent NotificationStatus = "sent"
|
||||
NotificationStatusConfirmed NotificationStatus = "confirmed"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// Main Entities
|
||||
// ============================================================================
|
||||
|
||||
// Incident represents a security or data breach incident per DSGVO Art. 33/34
|
||||
type Incident struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
TenantID uuid.UUID `json:"tenant_id"`
|
||||
|
||||
// Incident info
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Category IncidentCategory `json:"category"`
|
||||
Status IncidentStatus `json:"status"`
|
||||
Severity IncidentSeverity `json:"severity"`
|
||||
|
||||
// Detection & reporting
|
||||
DetectedAt time.Time `json:"detected_at"`
|
||||
ReportedBy uuid.UUID `json:"reported_by"`
|
||||
|
||||
// Affected scope
|
||||
AffectedDataCategories []string `json:"affected_data_categories"` // JSONB
|
||||
AffectedDataSubjectCount int `json:"affected_data_subject_count"`
|
||||
AffectedSystems []string `json:"affected_systems"` // JSONB
|
||||
|
||||
// Assessments & notifications (JSONB embedded objects)
|
||||
RiskAssessment *RiskAssessment `json:"risk_assessment,omitempty"`
|
||||
AuthorityNotification *AuthorityNotification `json:"authority_notification,omitempty"`
|
||||
DataSubjectNotification *DataSubjectNotification `json:"data_subject_notification,omitempty"`
|
||||
|
||||
// Resolution
|
||||
RootCause string `json:"root_cause,omitempty"`
|
||||
LessonsLearned string `json:"lessons_learned,omitempty"`
|
||||
|
||||
// Timeline (JSONB array)
|
||||
Timeline []TimelineEntry `json:"timeline"`
|
||||
|
||||
// Audit
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
ClosedAt *time.Time `json:"closed_at,omitempty"`
|
||||
}
|
||||
|
||||
// RiskAssessment contains the risk assessment for an incident
|
||||
type RiskAssessment struct {
|
||||
Likelihood int `json:"likelihood"` // 1-5
|
||||
Impact int `json:"impact"` // 1-5
|
||||
RiskLevel string `json:"risk_level"` // critical, high, medium, low (auto-calculated)
|
||||
AssessedAt time.Time `json:"assessed_at"`
|
||||
AssessedBy uuid.UUID `json:"assessed_by"`
|
||||
Notes string `json:"notes,omitempty"`
|
||||
}
|
||||
|
||||
// AuthorityNotification tracks the supervisory authority notification per DSGVO Art. 33
|
||||
type AuthorityNotification struct {
|
||||
Status NotificationStatus `json:"status"`
|
||||
Deadline time.Time `json:"deadline"` // 72h from detected_at per Art. 33
|
||||
SubmittedAt *time.Time `json:"submitted_at,omitempty"`
|
||||
AuthorityName string `json:"authority_name,omitempty"`
|
||||
ReferenceNumber string `json:"reference_number,omitempty"`
|
||||
ContactPerson string `json:"contact_person,omitempty"`
|
||||
Notes string `json:"notes,omitempty"`
|
||||
}
|
||||
|
||||
// DataSubjectNotification tracks the data subject notification per DSGVO Art. 34
|
||||
type DataSubjectNotification struct {
|
||||
Required bool `json:"required"`
|
||||
Status NotificationStatus `json:"status"`
|
||||
SentAt *time.Time `json:"sent_at,omitempty"`
|
||||
AffectedCount int `json:"affected_count"`
|
||||
NotificationText string `json:"notification_text,omitempty"`
|
||||
Channel string `json:"channel,omitempty"` // email, letter, website
|
||||
}
|
||||
|
||||
// TimelineEntry represents a single event in the incident timeline
|
||||
type TimelineEntry struct {
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
Action string `json:"action"`
|
||||
UserID uuid.UUID `json:"user_id"`
|
||||
Details string `json:"details,omitempty"`
|
||||
}
|
||||
|
||||
// IncidentMeasure represents a corrective or preventive measure for an incident
|
||||
type IncidentMeasure struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
IncidentID uuid.UUID `json:"incident_id"`
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description,omitempty"`
|
||||
MeasureType MeasureType `json:"measure_type"`
|
||||
Status MeasureStatus `json:"status"`
|
||||
Responsible string `json:"responsible,omitempty"`
|
||||
DueDate *time.Time `json:"due_date,omitempty"`
|
||||
CompletedAt *time.Time `json:"completed_at,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// IncidentStatistics contains aggregated incident statistics for a tenant
|
||||
type IncidentStatistics struct {
|
||||
TotalIncidents int `json:"total_incidents"`
|
||||
OpenIncidents int `json:"open_incidents"`
|
||||
ByStatus map[string]int `json:"by_status"`
|
||||
BySeverity map[string]int `json:"by_severity"`
|
||||
ByCategory map[string]int `json:"by_category"`
|
||||
NotificationsPending int `json:"notifications_pending"`
|
||||
AvgResolutionHours float64 `json:"avg_resolution_hours"`
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// API Request/Response Types
|
||||
// ============================================================================
|
||||
|
||||
// CreateIncidentRequest is the API request for creating an incident
|
||||
type CreateIncidentRequest struct {
|
||||
Title string `json:"title" binding:"required"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Category IncidentCategory `json:"category" binding:"required"`
|
||||
Severity IncidentSeverity `json:"severity" binding:"required"`
|
||||
DetectedAt *time.Time `json:"detected_at,omitempty"` // defaults to now
|
||||
AffectedDataCategories []string `json:"affected_data_categories,omitempty"`
|
||||
AffectedDataSubjectCount int `json:"affected_data_subject_count,omitempty"`
|
||||
AffectedSystems []string `json:"affected_systems,omitempty"`
|
||||
}
|
||||
|
||||
// UpdateIncidentRequest is the API request for updating an incident
|
||||
type UpdateIncidentRequest struct {
|
||||
Title string `json:"title,omitempty"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Category IncidentCategory `json:"category,omitempty"`
|
||||
Status IncidentStatus `json:"status,omitempty"`
|
||||
Severity IncidentSeverity `json:"severity,omitempty"`
|
||||
AffectedDataCategories []string `json:"affected_data_categories,omitempty"`
|
||||
AffectedDataSubjectCount *int `json:"affected_data_subject_count,omitempty"`
|
||||
AffectedSystems []string `json:"affected_systems,omitempty"`
|
||||
}
|
||||
|
||||
// RiskAssessmentRequest is the API request for assessing risk
|
||||
type RiskAssessmentRequest struct {
|
||||
Likelihood int `json:"likelihood" binding:"required,min=1,max=5"`
|
||||
Impact int `json:"impact" binding:"required,min=1,max=5"`
|
||||
Notes string `json:"notes,omitempty"`
|
||||
}
|
||||
|
||||
// SubmitAuthorityNotificationRequest is the API request for submitting authority notification
|
||||
type SubmitAuthorityNotificationRequest struct {
|
||||
AuthorityName string `json:"authority_name" binding:"required"`
|
||||
ContactPerson string `json:"contact_person,omitempty"`
|
||||
ReferenceNumber string `json:"reference_number,omitempty"`
|
||||
Notes string `json:"notes,omitempty"`
|
||||
}
|
||||
|
||||
// NotifyDataSubjectsRequest is the API request for notifying data subjects
|
||||
type NotifyDataSubjectsRequest struct {
|
||||
NotificationText string `json:"notification_text" binding:"required"`
|
||||
Channel string `json:"channel" binding:"required"` // email, letter, website
|
||||
AffectedCount int `json:"affected_count,omitempty"`
|
||||
}
|
||||
|
||||
// AddMeasureRequest is the API request for adding a corrective measure
|
||||
type AddMeasureRequest struct {
|
||||
Title string `json:"title" binding:"required"`
|
||||
Description string `json:"description,omitempty"`
|
||||
MeasureType MeasureType `json:"measure_type" binding:"required"`
|
||||
Responsible string `json:"responsible,omitempty"`
|
||||
DueDate *time.Time `json:"due_date,omitempty"`
|
||||
}
|
||||
|
||||
// CloseIncidentRequest is the API request for closing an incident
|
||||
type CloseIncidentRequest struct {
|
||||
RootCause string `json:"root_cause" binding:"required"`
|
||||
LessonsLearned string `json:"lessons_learned,omitempty"`
|
||||
}
|
||||
|
||||
// AddTimelineEntryRequest is the API request for adding a timeline entry
|
||||
type AddTimelineEntryRequest struct {
|
||||
Action string `json:"action" binding:"required"`
|
||||
Details string `json:"details,omitempty"`
|
||||
}
|
||||
|
||||
// IncidentListResponse is the API response for listing incidents
|
||||
type IncidentListResponse struct {
|
||||
Incidents []Incident `json:"incidents"`
|
||||
Total int `json:"total"`
|
||||
}
|
||||
|
||||
// IncidentFilters defines filters for listing incidents
|
||||
type IncidentFilters struct {
|
||||
Status IncidentStatus
|
||||
Severity IncidentSeverity
|
||||
Category IncidentCategory
|
||||
Limit int
|
||||
Offset int
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Helper Functions
|
||||
// ============================================================================
|
||||
|
||||
// CalculateRiskLevel calculates the risk level from likelihood and impact scores.
|
||||
// Risk score = likelihood * impact. Thresholds:
|
||||
// - critical: score >= 20
|
||||
// - high: score >= 12
|
||||
// - medium: score >= 6
|
||||
// - low: score < 6
|
||||
func CalculateRiskLevel(likelihood, impact int) string {
|
||||
score := likelihood * impact
|
||||
switch {
|
||||
case score >= 20:
|
||||
return "critical"
|
||||
case score >= 12:
|
||||
return "high"
|
||||
case score >= 6:
|
||||
return "medium"
|
||||
default:
|
||||
return "low"
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate72hDeadline calculates the 72-hour notification deadline per DSGVO Art. 33.
|
||||
// The supervisory authority must be notified within 72 hours of becoming aware of a breach.
|
||||
func Calculate72hDeadline(detectedAt time.Time) time.Time {
|
||||
return detectedAt.Add(72 * time.Hour)
|
||||
}
|
||||
|
||||
// IsNotificationRequired determines whether authority notification is required
|
||||
// based on the assessed risk level. Notification is required for critical and high risk.
|
||||
func IsNotificationRequired(riskLevel string) bool {
|
||||
return riskLevel == "critical" || riskLevel == "high"
|
||||
}
|
||||
@@ -1,571 +0,0 @@
|
||||
package incidents
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// Store handles incident data persistence
|
||||
type Store struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
// NewStore creates a new incident store
|
||||
func NewStore(pool *pgxpool.Pool) *Store {
|
||||
return &Store{pool: pool}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Incident CRUD Operations
|
||||
// ============================================================================
|
||||
|
||||
// CreateIncident creates a new incident
|
||||
func (s *Store) CreateIncident(ctx context.Context, incident *Incident) error {
|
||||
incident.ID = uuid.New()
|
||||
incident.CreatedAt = time.Now().UTC()
|
||||
incident.UpdatedAt = incident.CreatedAt
|
||||
if incident.Status == "" {
|
||||
incident.Status = IncidentStatusDetected
|
||||
}
|
||||
if incident.AffectedDataCategories == nil {
|
||||
incident.AffectedDataCategories = []string{}
|
||||
}
|
||||
if incident.AffectedSystems == nil {
|
||||
incident.AffectedSystems = []string{}
|
||||
}
|
||||
if incident.Timeline == nil {
|
||||
incident.Timeline = []TimelineEntry{}
|
||||
}
|
||||
|
||||
affectedDataCategories, _ := json.Marshal(incident.AffectedDataCategories)
|
||||
affectedSystems, _ := json.Marshal(incident.AffectedSystems)
|
||||
riskAssessment, _ := json.Marshal(incident.RiskAssessment)
|
||||
authorityNotification, _ := json.Marshal(incident.AuthorityNotification)
|
||||
dataSubjectNotification, _ := json.Marshal(incident.DataSubjectNotification)
|
||||
timeline, _ := json.Marshal(incident.Timeline)
|
||||
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
INSERT INTO incident_incidents (
|
||||
id, tenant_id, title, description, category, status, severity,
|
||||
detected_at, reported_by,
|
||||
affected_data_categories, affected_data_subject_count, affected_systems,
|
||||
risk_assessment, authority_notification, data_subject_notification,
|
||||
root_cause, lessons_learned, timeline,
|
||||
created_at, updated_at, closed_at
|
||||
) VALUES (
|
||||
$1, $2, $3, $4, $5, $6, $7,
|
||||
$8, $9,
|
||||
$10, $11, $12,
|
||||
$13, $14, $15,
|
||||
$16, $17, $18,
|
||||
$19, $20, $21
|
||||
)
|
||||
`,
|
||||
incident.ID, incident.TenantID, incident.Title, incident.Description,
|
||||
string(incident.Category), string(incident.Status), string(incident.Severity),
|
||||
incident.DetectedAt, incident.ReportedBy,
|
||||
affectedDataCategories, incident.AffectedDataSubjectCount, affectedSystems,
|
||||
riskAssessment, authorityNotification, dataSubjectNotification,
|
||||
incident.RootCause, incident.LessonsLearned, timeline,
|
||||
incident.CreatedAt, incident.UpdatedAt, incident.ClosedAt,
|
||||
)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// GetIncident retrieves an incident by ID
|
||||
func (s *Store) GetIncident(ctx context.Context, id uuid.UUID) (*Incident, error) {
|
||||
var incident Incident
|
||||
var category, status, severity string
|
||||
var affectedDataCategories, affectedSystems []byte
|
||||
var riskAssessment, authorityNotification, dataSubjectNotification []byte
|
||||
var timeline []byte
|
||||
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT
|
||||
id, tenant_id, title, description, category, status, severity,
|
||||
detected_at, reported_by,
|
||||
affected_data_categories, affected_data_subject_count, affected_systems,
|
||||
risk_assessment, authority_notification, data_subject_notification,
|
||||
root_cause, lessons_learned, timeline,
|
||||
created_at, updated_at, closed_at
|
||||
FROM incident_incidents WHERE id = $1
|
||||
`, id).Scan(
|
||||
&incident.ID, &incident.TenantID, &incident.Title, &incident.Description,
|
||||
&category, &status, &severity,
|
||||
&incident.DetectedAt, &incident.ReportedBy,
|
||||
&affectedDataCategories, &incident.AffectedDataSubjectCount, &affectedSystems,
|
||||
&riskAssessment, &authorityNotification, &dataSubjectNotification,
|
||||
&incident.RootCause, &incident.LessonsLearned, &timeline,
|
||||
&incident.CreatedAt, &incident.UpdatedAt, &incident.ClosedAt,
|
||||
)
|
||||
|
||||
if err == pgx.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
incident.Category = IncidentCategory(category)
|
||||
incident.Status = IncidentStatus(status)
|
||||
incident.Severity = IncidentSeverity(severity)
|
||||
|
||||
json.Unmarshal(affectedDataCategories, &incident.AffectedDataCategories)
|
||||
json.Unmarshal(affectedSystems, &incident.AffectedSystems)
|
||||
json.Unmarshal(riskAssessment, &incident.RiskAssessment)
|
||||
json.Unmarshal(authorityNotification, &incident.AuthorityNotification)
|
||||
json.Unmarshal(dataSubjectNotification, &incident.DataSubjectNotification)
|
||||
json.Unmarshal(timeline, &incident.Timeline)
|
||||
|
||||
if incident.AffectedDataCategories == nil {
|
||||
incident.AffectedDataCategories = []string{}
|
||||
}
|
||||
if incident.AffectedSystems == nil {
|
||||
incident.AffectedSystems = []string{}
|
||||
}
|
||||
if incident.Timeline == nil {
|
||||
incident.Timeline = []TimelineEntry{}
|
||||
}
|
||||
|
||||
return &incident, nil
|
||||
}
|
||||
|
||||
// ListIncidents lists incidents for a tenant with optional filters
|
||||
func (s *Store) ListIncidents(ctx context.Context, tenantID uuid.UUID, filters *IncidentFilters) ([]Incident, int, error) {
|
||||
// Count query
|
||||
countQuery := "SELECT COUNT(*) FROM incident_incidents WHERE tenant_id = $1"
|
||||
countArgs := []interface{}{tenantID}
|
||||
countArgIdx := 2
|
||||
|
||||
if filters != nil {
|
||||
if filters.Status != "" {
|
||||
countQuery += fmt.Sprintf(" AND status = $%d", countArgIdx)
|
||||
countArgs = append(countArgs, string(filters.Status))
|
||||
countArgIdx++
|
||||
}
|
||||
if filters.Severity != "" {
|
||||
countQuery += fmt.Sprintf(" AND severity = $%d", countArgIdx)
|
||||
countArgs = append(countArgs, string(filters.Severity))
|
||||
countArgIdx++
|
||||
}
|
||||
if filters.Category != "" {
|
||||
countQuery += fmt.Sprintf(" AND category = $%d", countArgIdx)
|
||||
countArgs = append(countArgs, string(filters.Category))
|
||||
countArgIdx++
|
||||
}
|
||||
}
|
||||
|
||||
var total int
|
||||
err := s.pool.QueryRow(ctx, countQuery, countArgs...).Scan(&total)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
// Data query
|
||||
query := `
|
||||
SELECT
|
||||
id, tenant_id, title, description, category, status, severity,
|
||||
detected_at, reported_by,
|
||||
affected_data_categories, affected_data_subject_count, affected_systems,
|
||||
risk_assessment, authority_notification, data_subject_notification,
|
||||
root_cause, lessons_learned, timeline,
|
||||
created_at, updated_at, closed_at
|
||||
FROM incident_incidents WHERE tenant_id = $1`
|
||||
|
||||
args := []interface{}{tenantID}
|
||||
argIdx := 2
|
||||
|
||||
if filters != nil {
|
||||
if filters.Status != "" {
|
||||
query += fmt.Sprintf(" AND status = $%d", argIdx)
|
||||
args = append(args, string(filters.Status))
|
||||
argIdx++
|
||||
}
|
||||
if filters.Severity != "" {
|
||||
query += fmt.Sprintf(" AND severity = $%d", argIdx)
|
||||
args = append(args, string(filters.Severity))
|
||||
argIdx++
|
||||
}
|
||||
if filters.Category != "" {
|
||||
query += fmt.Sprintf(" AND category = $%d", argIdx)
|
||||
args = append(args, string(filters.Category))
|
||||
argIdx++
|
||||
}
|
||||
}
|
||||
|
||||
query += " ORDER BY detected_at DESC"
|
||||
|
||||
if filters != nil && filters.Limit > 0 {
|
||||
query += fmt.Sprintf(" LIMIT $%d", argIdx)
|
||||
args = append(args, filters.Limit)
|
||||
argIdx++
|
||||
|
||||
if filters.Offset > 0 {
|
||||
query += fmt.Sprintf(" OFFSET $%d", argIdx)
|
||||
args = append(args, filters.Offset)
|
||||
argIdx++
|
||||
}
|
||||
}
|
||||
|
||||
rows, err := s.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var incidents []Incident
|
||||
for rows.Next() {
|
||||
var incident Incident
|
||||
var category, status, severity string
|
||||
var affectedDataCategories, affectedSystems []byte
|
||||
var riskAssessment, authorityNotification, dataSubjectNotification []byte
|
||||
var timeline []byte
|
||||
|
||||
err := rows.Scan(
|
||||
&incident.ID, &incident.TenantID, &incident.Title, &incident.Description,
|
||||
&category, &status, &severity,
|
||||
&incident.DetectedAt, &incident.ReportedBy,
|
||||
&affectedDataCategories, &incident.AffectedDataSubjectCount, &affectedSystems,
|
||||
&riskAssessment, &authorityNotification, &dataSubjectNotification,
|
||||
&incident.RootCause, &incident.LessonsLearned, &timeline,
|
||||
&incident.CreatedAt, &incident.UpdatedAt, &incident.ClosedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
incident.Category = IncidentCategory(category)
|
||||
incident.Status = IncidentStatus(status)
|
||||
incident.Severity = IncidentSeverity(severity)
|
||||
|
||||
json.Unmarshal(affectedDataCategories, &incident.AffectedDataCategories)
|
||||
json.Unmarshal(affectedSystems, &incident.AffectedSystems)
|
||||
json.Unmarshal(riskAssessment, &incident.RiskAssessment)
|
||||
json.Unmarshal(authorityNotification, &incident.AuthorityNotification)
|
||||
json.Unmarshal(dataSubjectNotification, &incident.DataSubjectNotification)
|
||||
json.Unmarshal(timeline, &incident.Timeline)
|
||||
|
||||
if incident.AffectedDataCategories == nil {
|
||||
incident.AffectedDataCategories = []string{}
|
||||
}
|
||||
if incident.AffectedSystems == nil {
|
||||
incident.AffectedSystems = []string{}
|
||||
}
|
||||
if incident.Timeline == nil {
|
||||
incident.Timeline = []TimelineEntry{}
|
||||
}
|
||||
|
||||
incidents = append(incidents, incident)
|
||||
}
|
||||
|
||||
return incidents, total, nil
|
||||
}
|
||||
|
||||
// UpdateIncident updates an incident
|
||||
func (s *Store) UpdateIncident(ctx context.Context, incident *Incident) error {
|
||||
incident.UpdatedAt = time.Now().UTC()
|
||||
|
||||
affectedDataCategories, _ := json.Marshal(incident.AffectedDataCategories)
|
||||
affectedSystems, _ := json.Marshal(incident.AffectedSystems)
|
||||
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
UPDATE incident_incidents SET
|
||||
title = $2, description = $3, category = $4, status = $5, severity = $6,
|
||||
affected_data_categories = $7, affected_data_subject_count = $8, affected_systems = $9,
|
||||
root_cause = $10, lessons_learned = $11,
|
||||
updated_at = $12
|
||||
WHERE id = $1
|
||||
`,
|
||||
incident.ID, incident.Title, incident.Description,
|
||||
string(incident.Category), string(incident.Status), string(incident.Severity),
|
||||
affectedDataCategories, incident.AffectedDataSubjectCount, affectedSystems,
|
||||
incident.RootCause, incident.LessonsLearned,
|
||||
incident.UpdatedAt,
|
||||
)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// DeleteIncident deletes an incident and its related measures (cascade handled by FK)
|
||||
func (s *Store) DeleteIncident(ctx context.Context, id uuid.UUID) error {
|
||||
_, err := s.pool.Exec(ctx, "DELETE FROM incident_incidents WHERE id = $1", id)
|
||||
return err
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Risk Assessment Operations
|
||||
// ============================================================================
|
||||
|
||||
// UpdateRiskAssessment updates the risk assessment for an incident
|
||||
func (s *Store) UpdateRiskAssessment(ctx context.Context, incidentID uuid.UUID, assessment *RiskAssessment) error {
|
||||
assessmentJSON, _ := json.Marshal(assessment)
|
||||
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
UPDATE incident_incidents SET
|
||||
risk_assessment = $2,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`, incidentID, assessmentJSON)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Notification Operations
|
||||
// ============================================================================
|
||||
|
||||
// UpdateAuthorityNotification updates the authority notification for an incident
|
||||
func (s *Store) UpdateAuthorityNotification(ctx context.Context, incidentID uuid.UUID, notification *AuthorityNotification) error {
|
||||
notificationJSON, _ := json.Marshal(notification)
|
||||
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
UPDATE incident_incidents SET
|
||||
authority_notification = $2,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`, incidentID, notificationJSON)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// UpdateDataSubjectNotification updates the data subject notification for an incident
|
||||
func (s *Store) UpdateDataSubjectNotification(ctx context.Context, incidentID uuid.UUID, notification *DataSubjectNotification) error {
|
||||
notificationJSON, _ := json.Marshal(notification)
|
||||
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
UPDATE incident_incidents SET
|
||||
data_subject_notification = $2,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`, incidentID, notificationJSON)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Measure Operations
|
||||
// ============================================================================
|
||||
|
||||
// AddMeasure adds a corrective measure to an incident
|
||||
func (s *Store) AddMeasure(ctx context.Context, measure *IncidentMeasure) error {
|
||||
measure.ID = uuid.New()
|
||||
measure.CreatedAt = time.Now().UTC()
|
||||
if measure.Status == "" {
|
||||
measure.Status = MeasureStatusPlanned
|
||||
}
|
||||
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
INSERT INTO incident_measures (
|
||||
id, incident_id, title, description, measure_type, status,
|
||||
responsible, due_date, completed_at, created_at
|
||||
) VALUES (
|
||||
$1, $2, $3, $4, $5, $6,
|
||||
$7, $8, $9, $10
|
||||
)
|
||||
`,
|
||||
measure.ID, measure.IncidentID, measure.Title, measure.Description,
|
||||
string(measure.MeasureType), string(measure.Status),
|
||||
measure.Responsible, measure.DueDate, measure.CompletedAt, measure.CreatedAt,
|
||||
)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// ListMeasures lists all measures for an incident
|
||||
func (s *Store) ListMeasures(ctx context.Context, incidentID uuid.UUID) ([]IncidentMeasure, error) {
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT
|
||||
id, incident_id, title, description, measure_type, status,
|
||||
responsible, due_date, completed_at, created_at
|
||||
FROM incident_measures WHERE incident_id = $1
|
||||
ORDER BY created_at ASC
|
||||
`, incidentID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var measures []IncidentMeasure
|
||||
for rows.Next() {
|
||||
var m IncidentMeasure
|
||||
var measureType, status string
|
||||
|
||||
err := rows.Scan(
|
||||
&m.ID, &m.IncidentID, &m.Title, &m.Description,
|
||||
&measureType, &status,
|
||||
&m.Responsible, &m.DueDate, &m.CompletedAt, &m.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
m.MeasureType = MeasureType(measureType)
|
||||
m.Status = MeasureStatus(status)
|
||||
|
||||
measures = append(measures, m)
|
||||
}
|
||||
|
||||
return measures, nil
|
||||
}
|
||||
|
||||
// UpdateMeasure updates an existing measure
|
||||
func (s *Store) UpdateMeasure(ctx context.Context, measure *IncidentMeasure) error {
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
UPDATE incident_measures SET
|
||||
title = $2, description = $3, measure_type = $4, status = $5,
|
||||
responsible = $6, due_date = $7, completed_at = $8
|
||||
WHERE id = $1
|
||||
`,
|
||||
measure.ID, measure.Title, measure.Description,
|
||||
string(measure.MeasureType), string(measure.Status),
|
||||
measure.Responsible, measure.DueDate, measure.CompletedAt,
|
||||
)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// CompleteMeasure marks a measure as completed
|
||||
func (s *Store) CompleteMeasure(ctx context.Context, id uuid.UUID) error {
|
||||
now := time.Now().UTC()
|
||||
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
UPDATE incident_measures SET
|
||||
status = $2,
|
||||
completed_at = $3
|
||||
WHERE id = $1
|
||||
`, id, string(MeasureStatusCompleted), now)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Timeline Operations
|
||||
// ============================================================================
|
||||
|
||||
// AddTimelineEntry appends a timeline entry to the incident's JSONB timeline array
|
||||
func (s *Store) AddTimelineEntry(ctx context.Context, incidentID uuid.UUID, entry TimelineEntry) error {
|
||||
entryJSON, err := json.Marshal(entry)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Use the || operator to append to the JSONB array
|
||||
_, err = s.pool.Exec(ctx, `
|
||||
UPDATE incident_incidents SET
|
||||
timeline = COALESCE(timeline, '[]'::jsonb) || $2::jsonb,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`, incidentID, string(entryJSON))
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Close Incident
|
||||
// ============================================================================
|
||||
|
||||
// CloseIncident closes an incident with root cause and lessons learned
|
||||
func (s *Store) CloseIncident(ctx context.Context, id uuid.UUID, rootCause, lessonsLearned string) error {
|
||||
now := time.Now().UTC()
|
||||
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
UPDATE incident_incidents SET
|
||||
status = $2,
|
||||
root_cause = $3,
|
||||
lessons_learned = $4,
|
||||
closed_at = $5,
|
||||
updated_at = $5
|
||||
WHERE id = $1
|
||||
`, id, string(IncidentStatusClosed), rootCause, lessonsLearned, now)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Statistics
|
||||
// ============================================================================
|
||||
|
||||
// GetStatistics returns aggregated incident statistics for a tenant
|
||||
func (s *Store) GetStatistics(ctx context.Context, tenantID uuid.UUID) (*IncidentStatistics, error) {
|
||||
stats := &IncidentStatistics{
|
||||
ByStatus: make(map[string]int),
|
||||
BySeverity: make(map[string]int),
|
||||
ByCategory: make(map[string]int),
|
||||
}
|
||||
|
||||
// Total incidents
|
||||
s.pool.QueryRow(ctx,
|
||||
"SELECT COUNT(*) FROM incident_incidents WHERE tenant_id = $1",
|
||||
tenantID).Scan(&stats.TotalIncidents)
|
||||
|
||||
// Open incidents (not closed)
|
||||
s.pool.QueryRow(ctx,
|
||||
"SELECT COUNT(*) FROM incident_incidents WHERE tenant_id = $1 AND status != 'closed'",
|
||||
tenantID).Scan(&stats.OpenIncidents)
|
||||
|
||||
// By status
|
||||
rows, err := s.pool.Query(ctx,
|
||||
"SELECT status, COUNT(*) FROM incident_incidents WHERE tenant_id = $1 GROUP BY status",
|
||||
tenantID)
|
||||
if err == nil {
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var status string
|
||||
var count int
|
||||
rows.Scan(&status, &count)
|
||||
stats.ByStatus[status] = count
|
||||
}
|
||||
}
|
||||
|
||||
// By severity
|
||||
rows, err = s.pool.Query(ctx,
|
||||
"SELECT severity, COUNT(*) FROM incident_incidents WHERE tenant_id = $1 GROUP BY severity",
|
||||
tenantID)
|
||||
if err == nil {
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var severity string
|
||||
var count int
|
||||
rows.Scan(&severity, &count)
|
||||
stats.BySeverity[severity] = count
|
||||
}
|
||||
}
|
||||
|
||||
// By category
|
||||
rows, err = s.pool.Query(ctx,
|
||||
"SELECT category, COUNT(*) FROM incident_incidents WHERE tenant_id = $1 GROUP BY category",
|
||||
tenantID)
|
||||
if err == nil {
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var category string
|
||||
var count int
|
||||
rows.Scan(&category, &count)
|
||||
stats.ByCategory[category] = count
|
||||
}
|
||||
}
|
||||
|
||||
// Notifications pending
|
||||
s.pool.QueryRow(ctx, `
|
||||
SELECT COUNT(*) FROM incident_incidents
|
||||
WHERE tenant_id = $1
|
||||
AND (authority_notification->>'status' = 'pending'
|
||||
OR data_subject_notification->>'status' = 'pending')
|
||||
`, tenantID).Scan(&stats.NotificationsPending)
|
||||
|
||||
// Average resolution hours (for closed incidents)
|
||||
s.pool.QueryRow(ctx, `
|
||||
SELECT COALESCE(AVG(EXTRACT(EPOCH FROM (closed_at - detected_at)) / 3600), 0)
|
||||
FROM incident_incidents
|
||||
WHERE tenant_id = $1 AND status = 'closed' AND closed_at IS NOT NULL
|
||||
`, tenantID).Scan(&stats.AvgResolutionHours)
|
||||
|
||||
return stats, nil
|
||||
}
|
||||
488
ai-compliance-sdk/internal/vendor/models.go
vendored
488
ai-compliance-sdk/internal/vendor/models.go
vendored
@@ -1,488 +0,0 @@
|
||||
package vendor
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// Constants / Enums
|
||||
// ============================================================================
|
||||
|
||||
// VendorRole represents the GDPR role of a vendor in data processing
|
||||
type VendorRole string
|
||||
|
||||
const (
|
||||
VendorRoleProcessor VendorRole = "PROCESSOR"
|
||||
VendorRoleController VendorRole = "CONTROLLER"
|
||||
VendorRoleJointController VendorRole = "JOINT_CONTROLLER"
|
||||
VendorRoleSubProcessor VendorRole = "SUB_PROCESSOR"
|
||||
VendorRoleThirdParty VendorRole = "THIRD_PARTY"
|
||||
)
|
||||
|
||||
// VendorStatus represents the lifecycle status of a vendor
|
||||
type VendorStatus string
|
||||
|
||||
const (
|
||||
VendorStatusActive VendorStatus = "ACTIVE"
|
||||
VendorStatusInactive VendorStatus = "INACTIVE"
|
||||
VendorStatusPendingReview VendorStatus = "PENDING_REVIEW"
|
||||
VendorStatusTerminated VendorStatus = "TERMINATED"
|
||||
)
|
||||
|
||||
// DocumentType represents the type of a contract/compliance document
|
||||
type DocumentType string
|
||||
|
||||
const (
|
||||
DocumentTypeAVV DocumentType = "AVV"
|
||||
DocumentTypeMSA DocumentType = "MSA"
|
||||
DocumentTypeSLA DocumentType = "SLA"
|
||||
DocumentTypeSCC DocumentType = "SCC"
|
||||
DocumentTypeNDA DocumentType = "NDA"
|
||||
DocumentTypeTOMAnnex DocumentType = "TOM_ANNEX"
|
||||
DocumentTypeCertification DocumentType = "CERTIFICATION"
|
||||
DocumentTypeSubProcessorList DocumentType = "SUB_PROCESSOR_LIST"
|
||||
)
|
||||
|
||||
// FindingType represents the type of a compliance finding
|
||||
type FindingType string
|
||||
|
||||
const (
|
||||
FindingTypeOK FindingType = "OK"
|
||||
FindingTypeGap FindingType = "GAP"
|
||||
FindingTypeRisk FindingType = "RISK"
|
||||
FindingTypeUnknown FindingType = "UNKNOWN"
|
||||
)
|
||||
|
||||
// FindingStatus represents the resolution status of a finding
|
||||
type FindingStatus string
|
||||
|
||||
const (
|
||||
FindingStatusOpen FindingStatus = "OPEN"
|
||||
FindingStatusInProgress FindingStatus = "IN_PROGRESS"
|
||||
FindingStatusResolved FindingStatus = "RESOLVED"
|
||||
FindingStatusAccepted FindingStatus = "ACCEPTED"
|
||||
FindingStatusFalsePositive FindingStatus = "FALSE_POSITIVE"
|
||||
)
|
||||
|
||||
// ControlStatus represents the assessment status of a control instance
|
||||
type ControlStatus string
|
||||
|
||||
const (
|
||||
ControlStatusPass ControlStatus = "PASS"
|
||||
ControlStatusPartial ControlStatus = "PARTIAL"
|
||||
ControlStatusFail ControlStatus = "FAIL"
|
||||
ControlStatusNotApplicable ControlStatus = "NOT_APPLICABLE"
|
||||
ControlStatusPlanned ControlStatus = "PLANNED"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// Main Entities
|
||||
// ============================================================================
|
||||
|
||||
// Vendor represents a third-party vendor/service provider subject to GDPR compliance
|
||||
type Vendor struct {
|
||||
ID uuid.UUID `json:"id" db:"id"`
|
||||
TenantID uuid.UUID `json:"tenant_id" db:"tenant_id"`
|
||||
|
||||
// Basic info
|
||||
Name string `json:"name" db:"name"`
|
||||
LegalForm string `json:"legal_form,omitempty" db:"legal_form"`
|
||||
Country string `json:"country" db:"country"`
|
||||
Address json.RawMessage `json:"address,omitempty" db:"address"`
|
||||
Website string `json:"website,omitempty" db:"website"`
|
||||
|
||||
// Contact
|
||||
ContactName string `json:"contact_name,omitempty" db:"contact_name"`
|
||||
ContactEmail string `json:"contact_email,omitempty" db:"contact_email"`
|
||||
ContactPhone string `json:"contact_phone,omitempty" db:"contact_phone"`
|
||||
ContactDepartment string `json:"contact_department,omitempty" db:"contact_department"`
|
||||
|
||||
// GDPR role & service
|
||||
Role VendorRole `json:"role" db:"role"`
|
||||
ServiceCategory string `json:"service_category,omitempty" db:"service_category"`
|
||||
ServiceDescription string `json:"service_description,omitempty" db:"service_description"`
|
||||
DataAccessLevel string `json:"data_access_level,omitempty" db:"data_access_level"`
|
||||
|
||||
// Processing details (JSONB)
|
||||
ProcessingLocations json.RawMessage `json:"processing_locations,omitempty" db:"processing_locations"`
|
||||
Certifications json.RawMessage `json:"certifications,omitempty" db:"certifications"`
|
||||
|
||||
// Risk scoring
|
||||
InherentRiskScore *int `json:"inherent_risk_score,omitempty" db:"inherent_risk_score"`
|
||||
ResidualRiskScore *int `json:"residual_risk_score,omitempty" db:"residual_risk_score"`
|
||||
ManualRiskAdjustment *int `json:"manual_risk_adjustment,omitempty" db:"manual_risk_adjustment"`
|
||||
|
||||
// Review schedule
|
||||
ReviewFrequency string `json:"review_frequency,omitempty" db:"review_frequency"`
|
||||
LastReviewDate *time.Time `json:"last_review_date,omitempty" db:"last_review_date"`
|
||||
NextReviewDate *time.Time `json:"next_review_date,omitempty" db:"next_review_date"`
|
||||
|
||||
// Links to processing activities (JSONB)
|
||||
ProcessingActivityIDs json.RawMessage `json:"processing_activity_ids,omitempty" db:"processing_activity_ids"`
|
||||
|
||||
// Status & template
|
||||
Status VendorStatus `json:"status" db:"status"`
|
||||
TemplateID *string `json:"template_id,omitempty" db:"template_id"`
|
||||
|
||||
// Audit
|
||||
CreatedAt time.Time `json:"created_at" db:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at" db:"updated_at"`
|
||||
CreatedBy string `json:"created_by" db:"created_by"`
|
||||
}
|
||||
|
||||
// Contract represents a contract/AVV document associated with a vendor
|
||||
type Contract struct {
|
||||
ID uuid.UUID `json:"id" db:"id"`
|
||||
TenantID uuid.UUID `json:"tenant_id" db:"tenant_id"`
|
||||
VendorID uuid.UUID `json:"vendor_id" db:"vendor_id"`
|
||||
|
||||
// File metadata
|
||||
FileName string `json:"file_name" db:"file_name"`
|
||||
OriginalName string `json:"original_name" db:"original_name"`
|
||||
MimeType string `json:"mime_type" db:"mime_type"`
|
||||
FileSize *int64 `json:"file_size,omitempty" db:"file_size"`
|
||||
StoragePath string `json:"storage_path" db:"storage_path"`
|
||||
|
||||
// Document classification
|
||||
DocumentType DocumentType `json:"document_type" db:"document_type"`
|
||||
|
||||
// Contract details
|
||||
Parties json.RawMessage `json:"parties,omitempty" db:"parties"`
|
||||
EffectiveDate *time.Time `json:"effective_date,omitempty" db:"effective_date"`
|
||||
ExpirationDate *time.Time `json:"expiration_date,omitempty" db:"expiration_date"`
|
||||
AutoRenewal bool `json:"auto_renewal" db:"auto_renewal"`
|
||||
RenewalNoticePeriod string `json:"renewal_notice_period,omitempty" db:"renewal_notice_period"`
|
||||
|
||||
// Review
|
||||
ReviewStatus string `json:"review_status" db:"review_status"`
|
||||
ReviewCompletedAt *time.Time `json:"review_completed_at,omitempty" db:"review_completed_at"`
|
||||
ComplianceScore *int `json:"compliance_score,omitempty" db:"compliance_score"`
|
||||
|
||||
// Versioning
|
||||
Version string `json:"version" db:"version"`
|
||||
PreviousVersionID *string `json:"previous_version_id,omitempty" db:"previous_version_id"`
|
||||
|
||||
// Extracted content
|
||||
ExtractedText string `json:"extracted_text,omitempty" db:"extracted_text"`
|
||||
PageCount *int `json:"page_count,omitempty" db:"page_count"`
|
||||
|
||||
// Audit
|
||||
CreatedAt time.Time `json:"created_at" db:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at" db:"updated_at"`
|
||||
CreatedBy string `json:"created_by" db:"created_by"`
|
||||
}
|
||||
|
||||
// Finding represents a compliance finding from a contract review
|
||||
type Finding struct {
|
||||
ID uuid.UUID `json:"id" db:"id"`
|
||||
TenantID uuid.UUID `json:"tenant_id" db:"tenant_id"`
|
||||
ContractID *string `json:"contract_id,omitempty" db:"contract_id"`
|
||||
VendorID uuid.UUID `json:"vendor_id" db:"vendor_id"`
|
||||
|
||||
// Finding details
|
||||
FindingType FindingType `json:"finding_type" db:"finding_type"`
|
||||
Category string `json:"category" db:"category"`
|
||||
Severity string `json:"severity" db:"severity"`
|
||||
Title string `json:"title" db:"title"`
|
||||
Description string `json:"description" db:"description"`
|
||||
Recommendation string `json:"recommendation,omitempty" db:"recommendation"`
|
||||
|
||||
// Evidence (JSONB)
|
||||
Citations json.RawMessage `json:"citations,omitempty" db:"citations"`
|
||||
|
||||
// Resolution workflow
|
||||
Status FindingStatus `json:"status" db:"status"`
|
||||
Assignee string `json:"assignee,omitempty" db:"assignee"`
|
||||
DueDate *time.Time `json:"due_date,omitempty" db:"due_date"`
|
||||
Resolution string `json:"resolution,omitempty" db:"resolution"`
|
||||
ResolvedAt *time.Time `json:"resolved_at,omitempty" db:"resolved_at"`
|
||||
ResolvedBy *string `json:"resolved_by,omitempty" db:"resolved_by"`
|
||||
|
||||
// Audit
|
||||
CreatedAt time.Time `json:"created_at" db:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at" db:"updated_at"`
|
||||
}
|
||||
|
||||
// ControlInstance represents an applied control assessment for a specific vendor
|
||||
type ControlInstance struct {
|
||||
ID uuid.UUID `json:"id" db:"id"`
|
||||
TenantID uuid.UUID `json:"tenant_id" db:"tenant_id"`
|
||||
VendorID uuid.UUID `json:"vendor_id" db:"vendor_id"`
|
||||
|
||||
// Control reference
|
||||
ControlID string `json:"control_id" db:"control_id"`
|
||||
ControlDomain string `json:"control_domain" db:"control_domain"`
|
||||
|
||||
// Assessment
|
||||
Status ControlStatus `json:"status" db:"status"`
|
||||
EvidenceIDs json.RawMessage `json:"evidence_ids,omitempty" db:"evidence_ids"`
|
||||
Notes string `json:"notes,omitempty" db:"notes"`
|
||||
|
||||
// Assessment tracking
|
||||
LastAssessedAt *time.Time `json:"last_assessed_at,omitempty" db:"last_assessed_at"`
|
||||
LastAssessedBy *string `json:"last_assessed_by,omitempty" db:"last_assessed_by"`
|
||||
NextAssessmentDate *time.Time `json:"next_assessment_date,omitempty" db:"next_assessment_date"`
|
||||
|
||||
// Audit
|
||||
CreatedAt time.Time `json:"created_at" db:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at" db:"updated_at"`
|
||||
}
|
||||
|
||||
// Template represents a pre-filled vendor compliance template
|
||||
type Template struct {
|
||||
ID uuid.UUID `json:"id" db:"id"`
|
||||
TenantID *string `json:"tenant_id,omitempty" db:"tenant_id"`
|
||||
|
||||
// Template classification
|
||||
TemplateType string `json:"template_type" db:"template_type"`
|
||||
TemplateID string `json:"template_id" db:"template_id"`
|
||||
Category string `json:"category" db:"category"`
|
||||
|
||||
// Localized names & descriptions
|
||||
NameDE string `json:"name_de" db:"name_de"`
|
||||
NameEN string `json:"name_en" db:"name_en"`
|
||||
DescriptionDE string `json:"description_de" db:"description_de"`
|
||||
DescriptionEN string `json:"description_en" db:"description_en"`
|
||||
|
||||
// Template content (JSONB)
|
||||
TemplateData json.RawMessage `json:"template_data" db:"template_data"`
|
||||
|
||||
// Classification
|
||||
Industry string `json:"industry,omitempty" db:"industry"`
|
||||
Tags json.RawMessage `json:"tags,omitempty" db:"tags"`
|
||||
|
||||
// Flags
|
||||
IsSystem bool `json:"is_system" db:"is_system"`
|
||||
IsActive bool `json:"is_active" db:"is_active"`
|
||||
|
||||
// Usage tracking
|
||||
UsageCount int `json:"usage_count" db:"usage_count"`
|
||||
|
||||
// Audit
|
||||
CreatedAt time.Time `json:"created_at" db:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at" db:"updated_at"`
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Statistics
|
||||
// ============================================================================
|
||||
|
||||
// VendorStats contains aggregated vendor compliance statistics for a tenant
|
||||
type VendorStats struct {
|
||||
TotalVendors int `json:"total_vendors"`
|
||||
ByStatus map[string]int `json:"by_status"`
|
||||
ByRole map[string]int `json:"by_role"`
|
||||
ByRiskLevel map[string]int `json:"by_risk_level"`
|
||||
PendingReviews int `json:"pending_reviews"`
|
||||
ExpiredContracts int `json:"expired_contracts"`
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// API Request/Response Types
|
||||
// ============================================================================
|
||||
|
||||
// -- Vendor -------------------------------------------------------------------
|
||||
|
||||
// CreateVendorRequest is the API request for creating a vendor
|
||||
type CreateVendorRequest struct {
|
||||
Name string `json:"name" binding:"required"`
|
||||
LegalForm string `json:"legal_form,omitempty"`
|
||||
Country string `json:"country" binding:"required"`
|
||||
Address json.RawMessage `json:"address,omitempty"`
|
||||
Website string `json:"website,omitempty"`
|
||||
ContactName string `json:"contact_name,omitempty"`
|
||||
ContactEmail string `json:"contact_email,omitempty"`
|
||||
ContactPhone string `json:"contact_phone,omitempty"`
|
||||
ContactDepartment string `json:"contact_department,omitempty"`
|
||||
Role VendorRole `json:"role" binding:"required"`
|
||||
ServiceCategory string `json:"service_category,omitempty"`
|
||||
ServiceDescription string `json:"service_description,omitempty"`
|
||||
DataAccessLevel string `json:"data_access_level,omitempty"`
|
||||
ProcessingLocations json.RawMessage `json:"processing_locations,omitempty"`
|
||||
Certifications json.RawMessage `json:"certifications,omitempty"`
|
||||
ReviewFrequency string `json:"review_frequency,omitempty"`
|
||||
ProcessingActivityIDs json.RawMessage `json:"processing_activity_ids,omitempty"`
|
||||
TemplateID *string `json:"template_id,omitempty"`
|
||||
}
|
||||
|
||||
// UpdateVendorRequest is the API request for updating a vendor
|
||||
type UpdateVendorRequest struct {
|
||||
Name *string `json:"name,omitempty"`
|
||||
LegalForm *string `json:"legal_form,omitempty"`
|
||||
Country *string `json:"country,omitempty"`
|
||||
Address json.RawMessage `json:"address,omitempty"`
|
||||
Website *string `json:"website,omitempty"`
|
||||
ContactName *string `json:"contact_name,omitempty"`
|
||||
ContactEmail *string `json:"contact_email,omitempty"`
|
||||
ContactPhone *string `json:"contact_phone,omitempty"`
|
||||
ContactDepartment *string `json:"contact_department,omitempty"`
|
||||
Role *VendorRole `json:"role,omitempty"`
|
||||
ServiceCategory *string `json:"service_category,omitempty"`
|
||||
ServiceDescription *string `json:"service_description,omitempty"`
|
||||
DataAccessLevel *string `json:"data_access_level,omitempty"`
|
||||
ProcessingLocations json.RawMessage `json:"processing_locations,omitempty"`
|
||||
Certifications json.RawMessage `json:"certifications,omitempty"`
|
||||
InherentRiskScore *int `json:"inherent_risk_score,omitempty"`
|
||||
ResidualRiskScore *int `json:"residual_risk_score,omitempty"`
|
||||
ManualRiskAdjustment *int `json:"manual_risk_adjustment,omitempty"`
|
||||
ReviewFrequency *string `json:"review_frequency,omitempty"`
|
||||
LastReviewDate *time.Time `json:"last_review_date,omitempty"`
|
||||
NextReviewDate *time.Time `json:"next_review_date,omitempty"`
|
||||
ProcessingActivityIDs json.RawMessage `json:"processing_activity_ids,omitempty"`
|
||||
Status *VendorStatus `json:"status,omitempty"`
|
||||
TemplateID *string `json:"template_id,omitempty"`
|
||||
}
|
||||
|
||||
// -- Contract -----------------------------------------------------------------
|
||||
|
||||
// CreateContractRequest is the API request for creating a contract
|
||||
type CreateContractRequest struct {
|
||||
VendorID uuid.UUID `json:"vendor_id" binding:"required"`
|
||||
FileName string `json:"file_name" binding:"required"`
|
||||
OriginalName string `json:"original_name" binding:"required"`
|
||||
MimeType string `json:"mime_type" binding:"required"`
|
||||
FileSize *int64 `json:"file_size,omitempty"`
|
||||
StoragePath string `json:"storage_path" binding:"required"`
|
||||
DocumentType DocumentType `json:"document_type" binding:"required"`
|
||||
Parties json.RawMessage `json:"parties,omitempty"`
|
||||
EffectiveDate *time.Time `json:"effective_date,omitempty"`
|
||||
ExpirationDate *time.Time `json:"expiration_date,omitempty"`
|
||||
AutoRenewal bool `json:"auto_renewal"`
|
||||
RenewalNoticePeriod string `json:"renewal_notice_period,omitempty"`
|
||||
Version string `json:"version,omitempty"`
|
||||
PreviousVersionID *string `json:"previous_version_id,omitempty"`
|
||||
}
|
||||
|
||||
// UpdateContractRequest is the API request for updating a contract
|
||||
type UpdateContractRequest struct {
|
||||
DocumentType *DocumentType `json:"document_type,omitempty"`
|
||||
Parties json.RawMessage `json:"parties,omitempty"`
|
||||
EffectiveDate *time.Time `json:"effective_date,omitempty"`
|
||||
ExpirationDate *time.Time `json:"expiration_date,omitempty"`
|
||||
AutoRenewal *bool `json:"auto_renewal,omitempty"`
|
||||
RenewalNoticePeriod *string `json:"renewal_notice_period,omitempty"`
|
||||
ReviewStatus *string `json:"review_status,omitempty"`
|
||||
ReviewCompletedAt *time.Time `json:"review_completed_at,omitempty"`
|
||||
ComplianceScore *int `json:"compliance_score,omitempty"`
|
||||
Version *string `json:"version,omitempty"`
|
||||
ExtractedText *string `json:"extracted_text,omitempty"`
|
||||
PageCount *int `json:"page_count,omitempty"`
|
||||
}
|
||||
|
||||
// -- Finding ------------------------------------------------------------------
|
||||
|
||||
// CreateFindingRequest is the API request for creating a compliance finding
|
||||
type CreateFindingRequest struct {
|
||||
ContractID *string `json:"contract_id,omitempty"`
|
||||
VendorID uuid.UUID `json:"vendor_id" binding:"required"`
|
||||
FindingType FindingType `json:"finding_type" binding:"required"`
|
||||
Category string `json:"category" binding:"required"`
|
||||
Severity string `json:"severity" binding:"required"`
|
||||
Title string `json:"title" binding:"required"`
|
||||
Description string `json:"description" binding:"required"`
|
||||
Recommendation string `json:"recommendation,omitempty"`
|
||||
Citations json.RawMessage `json:"citations,omitempty"`
|
||||
Assignee string `json:"assignee,omitempty"`
|
||||
DueDate *time.Time `json:"due_date,omitempty"`
|
||||
}
|
||||
|
||||
// UpdateFindingRequest is the API request for updating a finding
|
||||
type UpdateFindingRequest struct {
|
||||
FindingType *FindingType `json:"finding_type,omitempty"`
|
||||
Category *string `json:"category,omitempty"`
|
||||
Severity *string `json:"severity,omitempty"`
|
||||
Title *string `json:"title,omitempty"`
|
||||
Description *string `json:"description,omitempty"`
|
||||
Recommendation *string `json:"recommendation,omitempty"`
|
||||
Citations json.RawMessage `json:"citations,omitempty"`
|
||||
Status *FindingStatus `json:"status,omitempty"`
|
||||
Assignee *string `json:"assignee,omitempty"`
|
||||
DueDate *time.Time `json:"due_date,omitempty"`
|
||||
Resolution *string `json:"resolution,omitempty"`
|
||||
}
|
||||
|
||||
// ResolveFindingRequest is the API request for resolving a finding
|
||||
type ResolveFindingRequest struct {
|
||||
Resolution string `json:"resolution" binding:"required"`
|
||||
}
|
||||
|
||||
// -- ControlInstance ----------------------------------------------------------
|
||||
|
||||
// UpdateControlInstanceRequest is the API request for updating a control instance
|
||||
type UpdateControlInstanceRequest struct {
|
||||
Status *ControlStatus `json:"status,omitempty"`
|
||||
EvidenceIDs json.RawMessage `json:"evidence_ids,omitempty"`
|
||||
Notes *string `json:"notes,omitempty"`
|
||||
NextAssessmentDate *time.Time `json:"next_assessment_date,omitempty"`
|
||||
}
|
||||
|
||||
// -- Template -----------------------------------------------------------------
|
||||
|
||||
// CreateTemplateRequest is the API request for creating a vendor template
|
||||
type CreateTemplateRequest struct {
|
||||
TemplateType string `json:"template_type" binding:"required"`
|
||||
TemplateID string `json:"template_id" binding:"required"`
|
||||
Category string `json:"category" binding:"required"`
|
||||
NameDE string `json:"name_de" binding:"required"`
|
||||
NameEN string `json:"name_en" binding:"required"`
|
||||
DescriptionDE string `json:"description_de,omitempty"`
|
||||
DescriptionEN string `json:"description_en,omitempty"`
|
||||
TemplateData json.RawMessage `json:"template_data" binding:"required"`
|
||||
Industry string `json:"industry,omitempty"`
|
||||
Tags json.RawMessage `json:"tags,omitempty"`
|
||||
IsSystem bool `json:"is_system"`
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// List / Filter Types
|
||||
// ============================================================================
|
||||
|
||||
// VendorFilters defines filters for listing vendors
|
||||
type VendorFilters struct {
|
||||
Status VendorStatus
|
||||
Role VendorRole
|
||||
Search string
|
||||
Limit int
|
||||
Offset int
|
||||
}
|
||||
|
||||
// ContractFilters defines filters for listing contracts
|
||||
type ContractFilters struct {
|
||||
VendorID *uuid.UUID
|
||||
DocumentType DocumentType
|
||||
ReviewStatus string
|
||||
Limit int
|
||||
Offset int
|
||||
}
|
||||
|
||||
// FindingFilters defines filters for listing findings
|
||||
type FindingFilters struct {
|
||||
VendorID *uuid.UUID
|
||||
ContractID *string
|
||||
Status FindingStatus
|
||||
FindingType FindingType
|
||||
Severity string
|
||||
Limit int
|
||||
Offset int
|
||||
}
|
||||
|
||||
// VendorListResponse is the API response for listing vendors
|
||||
type VendorListResponse struct {
|
||||
Vendors []Vendor `json:"vendors"`
|
||||
Total int `json:"total"`
|
||||
}
|
||||
|
||||
// ContractListResponse is the API response for listing contracts
|
||||
type ContractListResponse struct {
|
||||
Contracts []Contract `json:"contracts"`
|
||||
Total int `json:"total"`
|
||||
}
|
||||
|
||||
// FindingListResponse is the API response for listing findings
|
||||
type FindingListResponse struct {
|
||||
Findings []Finding `json:"findings"`
|
||||
Total int `json:"total"`
|
||||
}
|
||||
1116
ai-compliance-sdk/internal/vendor/store.go
vendored
1116
ai-compliance-sdk/internal/vendor/store.go
vendored
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user