Compare commits

..

1 Commits

Author SHA1 Message Date
m
c5c3f41e08 feat: production hardening — slog, rate limiting, integration tests, seed data (Phase 4)
- Structured logging: replace log.* with log/slog JSON output across backend
- Request logger middleware: logs method, path, status, duration for all non-health requests
- Rate limiting: token bucket (5 req/min, burst 10) on AI endpoints (/api/ai/*)
- Integration tests: full critical path test (auth -> create case -> add deadline -> dashboard)
- Seed demo data: 1 tenant, 5 cases with deadlines/appointments/parties/events
- docker-compose.yml: add all required env vars (DATABASE_URL, SUPABASE_*, ANTHROPIC_API_KEY)
- .env.example: document all env vars including DATABASE_URL and CalDAV note
2026-03-25 14:32:27 +01:00
17 changed files with 694 additions and 750 deletions

View File

@@ -3,11 +3,16 @@
# Backend
PORT=8080
DATABASE_URL=postgresql://user:pass@host:5432/dbname
# Supabase (required for database access)
SUPABASE_URL=
# Supabase (required for database + auth)
SUPABASE_URL=https://your-project.supabase.co
SUPABASE_ANON_KEY=
SUPABASE_SERVICE_KEY=
SUPABASE_JWT_SECRET=
# Claude API (required for AI features)
ANTHROPIC_API_KEY=
# CalDAV (configured per-tenant in tenant settings, not env vars)
# See tenant.settings.caldav JSON field

View File

@@ -1,25 +1,31 @@
package main
import (
"log"
"log/slog"
"net/http"
"os"
"mgit.msbls.de/m/KanzlAI-mGMT/internal/auth"
"mgit.msbls.de/m/KanzlAI-mGMT/internal/config"
"mgit.msbls.de/m/KanzlAI-mGMT/internal/db"
"mgit.msbls.de/m/KanzlAI-mGMT/internal/logging"
"mgit.msbls.de/m/KanzlAI-mGMT/internal/router"
"mgit.msbls.de/m/KanzlAI-mGMT/internal/services"
)
func main() {
logging.Setup()
cfg, err := config.Load()
if err != nil {
log.Fatalf("Failed to load config: %v", err)
slog.Error("failed to load config", "error", err)
os.Exit(1)
}
database, err := db.Connect(cfg.DatabaseURL)
if err != nil {
log.Fatalf("Failed to connect to database: %v", err)
slog.Error("failed to connect to database", "error", err)
os.Exit(1)
}
defer database.Close()
@@ -32,8 +38,9 @@ func main() {
handler := router.New(database, authMW, cfg, calDAVSvc)
log.Printf("Starting KanzlAI API server on :%s", cfg.Port)
slog.Info("starting KanzlAI API server", "port", cfg.Port)
if err := http.ListenAndServe(":"+cfg.Port, handler); err != nil {
log.Fatal(err)
slog.Error("server failed", "error", err)
os.Exit(1)
}
}

View File

@@ -196,46 +196,6 @@ func (h *TenantHandler) RemoveMember(w http.ResponseWriter, r *http.Request) {
jsonResponse(w, map[string]string{"status": "removed"}, http.StatusOK)
}
// UpdateSettings handles PUT /api/tenants/{id}/settings
func (h *TenantHandler) UpdateSettings(w http.ResponseWriter, r *http.Request) {
userID, ok := auth.UserFromContext(r.Context())
if !ok {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
tenantID, err := uuid.Parse(r.PathValue("id"))
if err != nil {
jsonError(w, "invalid tenant ID", http.StatusBadRequest)
return
}
// Only owners and admins can update settings
role, err := h.svc.GetUserRole(r.Context(), userID, tenantID)
if err != nil {
jsonError(w, err.Error(), http.StatusInternalServerError)
return
}
if role != "owner" && role != "admin" {
jsonError(w, "only owners and admins can update settings", http.StatusForbidden)
return
}
var settings json.RawMessage
if err := json.NewDecoder(r.Body).Decode(&settings); err != nil {
jsonError(w, "invalid request body", http.StatusBadRequest)
return
}
tenant, err := h.svc.UpdateSettings(r.Context(), tenantID, settings)
if err != nil {
jsonError(w, err.Error(), http.StatusInternalServerError)
return
}
jsonResponse(w, tenant, http.StatusOK)
}
// ListMembers handles GET /api/tenants/{id}/members
func (h *TenantHandler) ListMembers(w http.ResponseWriter, r *http.Request) {
userID, ok := auth.UserFromContext(r.Context())

View File

@@ -0,0 +1,273 @@
package internal_test
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"testing"
"time"
"mgit.msbls.de/m/KanzlAI-mGMT/internal/auth"
"mgit.msbls.de/m/KanzlAI-mGMT/internal/config"
"mgit.msbls.de/m/KanzlAI-mGMT/internal/db"
"mgit.msbls.de/m/KanzlAI-mGMT/internal/router"
"github.com/golang-jwt/jwt/v5"
"github.com/google/uuid"
)
// testServer sets up the full router with a real DB connection.
// Requires DATABASE_URL and SUPABASE_JWT_SECRET env vars.
func testServer(t *testing.T) (http.Handler, func()) {
t.Helper()
dbURL := os.Getenv("DATABASE_URL")
if dbURL == "" {
t.Skip("DATABASE_URL not set, skipping integration test")
}
jwtSecret := os.Getenv("SUPABASE_JWT_SECRET")
if jwtSecret == "" {
jwtSecret = "test-jwt-secret-for-integration-tests"
os.Setenv("SUPABASE_JWT_SECRET", jwtSecret)
}
database, err := db.Connect(dbURL)
if err != nil {
t.Fatalf("connecting to database: %v", err)
}
cfg := &config.Config{
Port: "0",
DatabaseURL: dbURL,
SupabaseJWTSecret: jwtSecret,
}
authMW := auth.NewMiddleware(jwtSecret, database)
handler := router.New(database, authMW, cfg, nil)
return handler, func() { database.Close() }
}
// createTestJWT creates a JWT for the given user ID, signed with the test secret.
func createTestJWT(t *testing.T, userID uuid.UUID) string {
t.Helper()
secret := os.Getenv("SUPABASE_JWT_SECRET")
if secret == "" {
secret = "test-jwt-secret-for-integration-tests"
}
claims := jwt.MapClaims{
"sub": userID.String(),
"aud": "authenticated",
"exp": time.Now().Add(1 * time.Hour).Unix(),
"iat": time.Now().Unix(),
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
signed, err := token.SignedString([]byte(secret))
if err != nil {
t.Fatalf("signing JWT: %v", err)
}
return signed
}
// setupTestTenant creates a temporary tenant and user_tenant for testing.
// Returns tenantID and userID. Cleans up on test completion.
func setupTestTenant(t *testing.T, handler http.Handler) (tenantID, userID uuid.UUID) {
t.Helper()
dbURL := os.Getenv("DATABASE_URL")
database, err := db.Connect(dbURL)
if err != nil {
t.Fatalf("connecting to database for setup: %v", err)
}
defer database.Close()
tenantID = uuid.New()
userID = uuid.New()
_, err = database.Exec(`INSERT INTO tenants (id, name, slug) VALUES ($1, $2, $3)`,
tenantID, "Integration Test Kanzlei "+tenantID.String()[:8], "test-"+tenantID.String()[:8])
if err != nil {
t.Fatalf("creating test tenant: %v", err)
}
// Create a user in auth.users so JWT auth works
_, err = database.Exec(`INSERT INTO auth.users (id, instance_id, role, aud, email, encrypted_password, email_confirmed_at, created_at, updated_at, confirmation_token, recovery_token)
VALUES ($1, '00000000-0000-0000-0000-000000000000', 'authenticated', 'authenticated', $2, '', NOW(), NOW(), NOW(), '', '')`,
userID, fmt.Sprintf("test-%s@kanzlai.test", userID.String()[:8]))
if err != nil {
t.Fatalf("creating test user: %v", err)
}
_, err = database.Exec(`INSERT INTO user_tenants (user_id, tenant_id, role) VALUES ($1, $2, 'owner')`,
userID, tenantID)
if err != nil {
t.Fatalf("creating user_tenant: %v", err)
}
t.Cleanup(func() {
cleanupDB, _ := db.Connect(dbURL)
if cleanupDB != nil {
cleanupDB.Exec(`DELETE FROM case_events WHERE tenant_id = $1`, tenantID)
cleanupDB.Exec(`DELETE FROM deadlines WHERE tenant_id = $1`, tenantID)
cleanupDB.Exec(`DELETE FROM appointments WHERE tenant_id = $1`, tenantID)
cleanupDB.Exec(`DELETE FROM parties WHERE tenant_id = $1`, tenantID)
cleanupDB.Exec(`DELETE FROM documents WHERE tenant_id = $1`, tenantID)
cleanupDB.Exec(`DELETE FROM cases WHERE tenant_id = $1`, tenantID)
cleanupDB.Exec(`DELETE FROM user_tenants WHERE tenant_id = $1`, tenantID)
cleanupDB.Exec(`DELETE FROM tenants WHERE id = $1`, tenantID)
cleanupDB.Exec(`DELETE FROM auth.users WHERE id = $1`, userID)
cleanupDB.Close()
}
})
return tenantID, userID
}
func TestHealthEndpoint(t *testing.T) {
handler, cleanup := testServer(t)
defer cleanup()
req := httptest.NewRequest("GET", "/health", nil)
w := httptest.NewRecorder()
handler.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
}
var resp map[string]string
json.Unmarshal(w.Body.Bytes(), &resp)
if resp["status"] != "ok" {
t.Fatalf("expected status ok, got %v", resp)
}
}
func TestCriticalPath_CreateCase_AddDeadline_Dashboard(t *testing.T) {
handler, cleanup := testServer(t)
defer cleanup()
_, userID := setupTestTenant(t, handler)
token := createTestJWT(t, userID)
// Step 1: Create a case
caseBody := `{"case_number":"TEST/001","title":"Integration Test — Patentverletzung","case_type":"patent","court":"UPC München"}`
req := httptest.NewRequest("POST", "/api/cases", bytes.NewBufferString(caseBody))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+token)
w := httptest.NewRecorder()
handler.ServeHTTP(w, req)
if w.Code != http.StatusCreated {
t.Fatalf("create case: expected 201, got %d: %s", w.Code, w.Body.String())
}
var createdCase map[string]interface{}
json.Unmarshal(w.Body.Bytes(), &createdCase)
caseID, ok := createdCase["id"].(string)
if !ok || caseID == "" {
t.Fatalf("create case: missing ID in response: %v", createdCase)
}
t.Logf("Created case: %s", caseID)
// Step 2: List cases — verify our case is there
req = httptest.NewRequest("GET", "/api/cases", nil)
req.Header.Set("Authorization", "Bearer "+token)
w = httptest.NewRecorder()
handler.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("list cases: expected 200, got %d: %s", w.Code, w.Body.String())
}
var caseList map[string]interface{}
json.Unmarshal(w.Body.Bytes(), &caseList)
total := caseList["total"].(float64)
if total < 1 {
t.Fatalf("list cases: expected at least 1 case, got %.0f", total)
}
// Step 3: Add a deadline to the case
dueDate := time.Now().AddDate(0, 0, 14).Format("2006-01-02")
warnDate := time.Now().AddDate(0, 0, 10).Format("2006-01-02")
deadlineBody := fmt.Sprintf(`{"title":"Klageerwiderung einreichen","due_date":"%s","warning_date":"%s","source":"manual"}`, dueDate, warnDate)
req = httptest.NewRequest("POST", "/api/cases/"+caseID+"/deadlines", bytes.NewBufferString(deadlineBody))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+token)
w = httptest.NewRecorder()
handler.ServeHTTP(w, req)
if w.Code != http.StatusCreated {
t.Fatalf("create deadline: expected 201, got %d: %s", w.Code, w.Body.String())
}
var createdDeadline map[string]interface{}
json.Unmarshal(w.Body.Bytes(), &createdDeadline)
deadlineID, ok := createdDeadline["id"].(string)
if !ok || deadlineID == "" {
t.Fatalf("create deadline: missing ID in response: %v", createdDeadline)
}
t.Logf("Created deadline: %s", deadlineID)
// Step 4: Verify deadline appears in case deadlines
req = httptest.NewRequest("GET", "/api/cases/"+caseID+"/deadlines", nil)
req.Header.Set("Authorization", "Bearer "+token)
w = httptest.NewRecorder()
handler.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("list deadlines: expected 200, got %d: %s", w.Code, w.Body.String())
}
var deadlines []interface{}
json.Unmarshal(w.Body.Bytes(), &deadlines)
if len(deadlines) < 1 {
t.Fatalf("list deadlines: expected at least 1, got %d", len(deadlines))
}
// Step 5: Fetch dashboard — should include our case and deadline
req = httptest.NewRequest("GET", "/api/dashboard", nil)
req.Header.Set("Authorization", "Bearer "+token)
w = httptest.NewRecorder()
handler.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("dashboard: expected 200, got %d: %s", w.Code, w.Body.String())
}
var dashboard map[string]interface{}
json.Unmarshal(w.Body.Bytes(), &dashboard)
// Verify dashboard has expected sections
for _, key := range []string{"deadline_summary", "case_summary", "upcoming_deadlines"} {
if _, exists := dashboard[key]; !exists {
t.Errorf("dashboard: missing key %q in response", key)
}
}
// Verify case_summary shows at least 1 active case
if cs, ok := dashboard["case_summary"].(map[string]interface{}); ok {
if active, ok := cs["active"].(float64); ok && active < 1 {
t.Errorf("dashboard: expected at least 1 active case, got %.0f", active)
}
}
t.Logf("Full critical path passed: auth -> create case -> add deadline -> dashboard")
}
func TestUnauthenticatedAccess(t *testing.T) {
handler, cleanup := testServer(t)
defer cleanup()
// Accessing API without token should return 401
req := httptest.NewRequest("GET", "/api/cases", nil)
w := httptest.NewRecorder()
handler.ServeHTTP(w, req)
if w.Code != http.StatusUnauthorized {
t.Fatalf("expected 401, got %d: %s", w.Code, w.Body.String())
}
}

View File

@@ -0,0 +1,14 @@
package logging
import (
"log/slog"
"os"
)
// Setup initializes the global slog logger with JSON output for production.
func Setup() {
handler := slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
Level: slog.LevelInfo,
})
slog.SetDefault(slog.New(handler))
}

View File

@@ -0,0 +1,98 @@
package middleware
import (
"log/slog"
"net/http"
"sync"
"time"
)
// TokenBucket implements a simple per-IP token bucket rate limiter.
type TokenBucket struct {
mu sync.Mutex
buckets map[string]*bucket
rate float64 // tokens per second
burst int // max tokens
}
type bucket struct {
tokens float64
lastTime time.Time
}
// NewTokenBucket creates a rate limiter allowing rate requests per second with burst capacity.
func NewTokenBucket(rate float64, burst int) *TokenBucket {
tb := &TokenBucket{
buckets: make(map[string]*bucket),
rate: rate,
burst: burst,
}
// Periodically clean up stale buckets
go tb.cleanup()
return tb
}
func (tb *TokenBucket) allow(key string) bool {
tb.mu.Lock()
defer tb.mu.Unlock()
b, ok := tb.buckets[key]
if !ok {
b = &bucket{tokens: float64(tb.burst), lastTime: time.Now()}
tb.buckets[key] = b
}
now := time.Now()
elapsed := now.Sub(b.lastTime).Seconds()
b.tokens += elapsed * tb.rate
if b.tokens > float64(tb.burst) {
b.tokens = float64(tb.burst)
}
b.lastTime = now
if b.tokens < 1 {
return false
}
b.tokens--
return true
}
func (tb *TokenBucket) cleanup() {
ticker := time.NewTicker(5 * time.Minute)
defer ticker.Stop()
for range ticker.C {
tb.mu.Lock()
cutoff := time.Now().Add(-10 * time.Minute)
for key, b := range tb.buckets {
if b.lastTime.Before(cutoff) {
delete(tb.buckets, key)
}
}
tb.mu.Unlock()
}
}
// Limit wraps an http.Handler with rate limiting.
func (tb *TokenBucket) Limit(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ip := r.Header.Get("X-Forwarded-For")
if ip == "" {
ip = r.RemoteAddr
}
if !tb.allow(ip) {
slog.Warn("rate limit exceeded", "ip", ip, "path", r.URL.Path)
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Retry-After", "10")
w.WriteHeader(http.StatusTooManyRequests)
w.Write([]byte(`{"error":"rate limit exceeded, try again later"}`))
return
}
next.ServeHTTP(w, r)
})
}
// LimitFunc wraps an http.HandlerFunc with rate limiting.
func (tb *TokenBucket) LimitFunc(next http.HandlerFunc) http.HandlerFunc {
limited := tb.Limit(http.HandlerFunc(next))
return limited.ServeHTTP
}

View File

@@ -0,0 +1,70 @@
package middleware
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestTokenBucket_AllowsBurst(t *testing.T) {
tb := NewTokenBucket(1.0, 5) // 1/sec, burst 5
handler := tb.LimitFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
// Should allow burst of 5 requests
for i := 0; i < 5; i++ {
req := httptest.NewRequest("GET", "/test", nil)
w := httptest.NewRecorder()
handler.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("request %d: expected 200, got %d", i+1, w.Code)
}
}
// 6th request should be rate limited
req := httptest.NewRequest("GET", "/test", nil)
w := httptest.NewRecorder()
handler.ServeHTTP(w, req)
if w.Code != http.StatusTooManyRequests {
t.Fatalf("request 6: expected 429, got %d", w.Code)
}
}
func TestTokenBucket_DifferentIPs(t *testing.T) {
tb := NewTokenBucket(1.0, 2) // 1/sec, burst 2
handler := tb.LimitFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
// Exhaust IP1's bucket
for i := 0; i < 2; i++ {
req := httptest.NewRequest("GET", "/test", nil)
req.Header.Set("X-Forwarded-For", "1.2.3.4")
w := httptest.NewRecorder()
handler.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("ip1 request %d: expected 200, got %d", i+1, w.Code)
}
}
// IP1 should now be limited
req := httptest.NewRequest("GET", "/test", nil)
req.Header.Set("X-Forwarded-For", "1.2.3.4")
w := httptest.NewRecorder()
handler.ServeHTTP(w, req)
if w.Code != http.StatusTooManyRequests {
t.Fatalf("ip1 request 3: expected 429, got %d", w.Code)
}
// IP2 should still work
req = httptest.NewRequest("GET", "/test", nil)
req.Header.Set("X-Forwarded-For", "5.6.7.8")
w = httptest.NewRecorder()
handler.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("ip2 request 1: expected 200, got %d", w.Code)
}
}

View File

@@ -2,13 +2,16 @@ package router
import (
"encoding/json"
"log/slog"
"net/http"
"time"
"github.com/jmoiron/sqlx"
"mgit.msbls.de/m/KanzlAI-mGMT/internal/auth"
"mgit.msbls.de/m/KanzlAI-mGMT/internal/config"
"mgit.msbls.de/m/KanzlAI-mGMT/internal/handlers"
"mgit.msbls.de/m/KanzlAI-mGMT/internal/middleware"
"mgit.msbls.de/m/KanzlAI-mGMT/internal/services"
)
@@ -60,7 +63,6 @@ func New(db *sqlx.DB, authMW *auth.Middleware, cfg *config.Config, calDAVSvc *se
api.HandleFunc("POST /api/tenants", tenantH.CreateTenant)
api.HandleFunc("GET /api/tenants", tenantH.ListTenants)
api.HandleFunc("GET /api/tenants/{id}", tenantH.GetTenant)
api.HandleFunc("PUT /api/tenants/{id}/settings", tenantH.UpdateSettings)
api.HandleFunc("POST /api/tenants/{id}/invite", tenantH.InviteUser)
api.HandleFunc("DELETE /api/tenants/{id}/members/{uid}", tenantH.RemoveMember)
api.HandleFunc("GET /api/tenants/{id}/members", tenantH.ListMembers)
@@ -113,10 +115,11 @@ func New(db *sqlx.DB, authMW *auth.Middleware, cfg *config.Config, calDAVSvc *se
scoped.HandleFunc("GET /api/documents/{docId}/meta", docH.GetMeta)
scoped.HandleFunc("DELETE /api/documents/{docId}", docH.Delete)
// AI endpoints
// AI endpoints (rate limited: 5 req/min burst 10 per IP)
if aiH != nil {
scoped.HandleFunc("POST /api/ai/extract-deadlines", aiH.ExtractDeadlines)
scoped.HandleFunc("POST /api/ai/summarize-case", aiH.SummarizeCase)
aiLimiter := middleware.NewTokenBucket(5.0/60.0, 10)
scoped.HandleFunc("POST /api/ai/extract-deadlines", aiLimiter.LimitFunc(aiH.ExtractDeadlines))
scoped.HandleFunc("POST /api/ai/summarize-case", aiLimiter.LimitFunc(aiH.SummarizeCase))
}
// CalDAV sync endpoints
@@ -131,7 +134,7 @@ func New(db *sqlx.DB, authMW *auth.Middleware, cfg *config.Config, calDAVSvc *se
mux.Handle("/api/", authMW.RequireAuth(api))
return mux
return requestLogger(mux)
}
func handleHealth(db *sqlx.DB) http.HandlerFunc {
@@ -146,3 +149,34 @@ func handleHealth(db *sqlx.DB) http.HandlerFunc {
}
}
type statusWriter struct {
http.ResponseWriter
status int
}
func (w *statusWriter) WriteHeader(code int) {
w.status = code
w.ResponseWriter.WriteHeader(code)
}
func requestLogger(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Skip health checks to reduce noise
if r.URL.Path == "/health" {
next.ServeHTTP(w, r)
return
}
sw := &statusWriter{ResponseWriter: w, status: http.StatusOK}
start := time.Now()
next.ServeHTTP(sw, r)
slog.Info("request",
"method", r.Method,
"path", r.URL.Path,
"status", sw.status,
"duration_ms", time.Since(start).Milliseconds(),
)
})
}

View File

@@ -4,7 +4,7 @@ import (
"context"
"encoding/json"
"fmt"
"log"
"log/slog"
"strings"
"sync"
"time"
@@ -83,14 +83,14 @@ func (s *CalDAVService) Start() {
s.wg.Go(func() {
s.backgroundLoop()
})
log.Println("CalDAV sync service started")
slog.Info("CalDAV sync service started")
}
// Stop gracefully stops the background sync.
func (s *CalDAVService) Stop() {
close(s.stopCh)
s.wg.Wait()
log.Println("CalDAV sync service stopped")
slog.Info("CalDAV sync service stopped")
}
// backgroundLoop polls tenants at their configured interval.
@@ -113,7 +113,7 @@ func (s *CalDAVService) backgroundLoop() {
func (s *CalDAVService) syncAllTenants() {
configs, err := s.loadAllTenantConfigs()
if err != nil {
log.Printf("CalDAV: failed to load tenant configs: %v", err)
slog.Error("CalDAV: failed to load tenant configs", "error", err)
return
}
@@ -137,7 +137,7 @@ func (s *CalDAVService) syncAllTenants() {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
if _, err := s.SyncTenant(ctx, tid, c); err != nil {
log.Printf("CalDAV: sync failed for tenant %s: %v", tid, err)
slog.Error("CalDAV: sync failed", "tenant_id", tid, "error", err)
}
}(tenantID, cfg)
}
@@ -649,7 +649,7 @@ func (s *CalDAVService) logConflictEvent(ctx context.Context, tenantID, caseID u
VALUES ($1, $2, $3, 'caldav_conflict', $4, $5, $6, NOW(), NOW())`,
uuid.New(), tenantID, caseID, "CalDAV sync conflict", msg, metadata)
if err != nil {
log.Printf("CalDAV: failed to log conflict event: %v", err)
slog.Error("CalDAV: failed to log conflict event", "error", err)
}
}

View File

@@ -3,7 +3,6 @@ package services
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"github.com/google/uuid"
@@ -174,21 +173,6 @@ func (s *TenantService) InviteByEmail(ctx context.Context, tenantID uuid.UUID, e
return &ut, nil
}
// UpdateSettings merges new settings into the tenant's existing settings JSONB.
func (s *TenantService) UpdateSettings(ctx context.Context, tenantID uuid.UUID, settings json.RawMessage) (*models.Tenant, error) {
var tenant models.Tenant
err := s.db.QueryRowxContext(ctx,
`UPDATE tenants SET settings = COALESCE(settings, '{}'::jsonb) || $1::jsonb, updated_at = NOW()
WHERE id = $2
RETURNING id, name, slug, settings, created_at, updated_at`,
settings, tenantID,
).StructScan(&tenant)
if err != nil {
return nil, fmt.Errorf("update settings: %w", err)
}
return &tenant, nil
}
// RemoveMember removes a user from a tenant. Cannot remove the last owner.
func (s *TenantService) RemoveMember(ctx context.Context, tenantID, userID uuid.UUID) error {
// Check if the user being removed is an owner

167
backend/seed/demo_data.sql Normal file
View File

@@ -0,0 +1,167 @@
-- KanzlAI Demo Data
-- Creates 1 test tenant, 5 cases with deadlines and appointments
-- Run with: psql $DATABASE_URL -f demo_data.sql
SET search_path TO kanzlai, public;
-- Demo tenant
INSERT INTO tenants (id, name, slug, settings) VALUES
('a0000000-0000-0000-0000-000000000001', 'Kanzlei Siebels & Partner', 'siebels-partner', '{}')
ON CONFLICT (id) DO NOTHING;
-- Link both users to the demo tenant
INSERT INTO user_tenants (user_id, tenant_id, role) VALUES
('1da9374d-a8a6-49fc-a2ec-5ddfa91d522d', 'a0000000-0000-0000-0000-000000000001', 'owner'),
('ac6c9501-3757-4a6d-8b97-2cff4288382b', 'a0000000-0000-0000-0000-000000000001', 'member')
ON CONFLICT DO NOTHING;
-- ============================================================
-- Case 1: Patentverletzung (patent infringement) — active
-- ============================================================
INSERT INTO cases (id, tenant_id, case_number, title, case_type, court, court_ref, status) VALUES
('c0000000-0000-0000-0000-000000000001',
'a0000000-0000-0000-0000-000000000001',
'2026/001', 'TechCorp GmbH ./. InnovatAG — Patentverletzung EP 1234567',
'patent', 'UPC München (Lokalkammer)', 'UPC_CFI-123/2026',
'active');
INSERT INTO parties (id, tenant_id, case_id, name, role, representative) VALUES
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000001',
'TechCorp GmbH', 'claimant', 'RA Dr. Siebels'),
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000001',
'InnovatAG', 'defendant', 'RA Müller');
INSERT INTO deadlines (id, tenant_id, case_id, title, due_date, warning_date, status, source) VALUES
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000001',
'Klageerwiderung einreichen', CURRENT_DATE + INTERVAL '3 days', CURRENT_DATE + INTERVAL '1 day', 'pending', 'manual'),
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000001',
'Beweisangebote nachreichen', CURRENT_DATE + INTERVAL '14 days', CURRENT_DATE + INTERVAL '10 days', 'pending', 'manual'),
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000001',
'Schriftsatz Anspruch 3', CURRENT_DATE - INTERVAL '2 days', CURRENT_DATE - INTERVAL '5 days', 'pending', 'manual');
INSERT INTO appointments (id, tenant_id, case_id, title, start_at, end_at, location, appointment_type) VALUES
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000001',
'Mündliche Verhandlung', CURRENT_DATE + INTERVAL '21 days' + TIME '10:00', CURRENT_DATE + INTERVAL '21 days' + TIME '12:00',
'UPC München, Saal 4', 'hearing');
-- ============================================================
-- Case 2: Markenrecht (trademark) — active
-- ============================================================
INSERT INTO cases (id, tenant_id, case_number, title, case_type, court, court_ref, status) VALUES
('c0000000-0000-0000-0000-000000000002',
'a0000000-0000-0000-0000-000000000001',
'2026/002', 'BrandHouse ./. CopyShop UG — Markenverletzung DE 30201234',
'trademark', 'LG Hamburg', '315 O 78/26',
'active');
INSERT INTO parties (id, tenant_id, case_id, name, role, representative) VALUES
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000002',
'BrandHouse SE', 'claimant', 'RA Dr. Siebels'),
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000002',
'CopyShop UG', 'defendant', 'RA Weber');
INSERT INTO deadlines (id, tenant_id, case_id, title, due_date, warning_date, status, source) VALUES
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000002',
'Antrag einstweilige Verfügung', CURRENT_DATE + INTERVAL '5 days', CURRENT_DATE + INTERVAL '2 days', 'pending', 'manual'),
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000002',
'Abmahnung Fristablauf', CURRENT_DATE + INTERVAL '30 days', CURRENT_DATE + INTERVAL '25 days', 'pending', 'manual');
INSERT INTO appointments (id, tenant_id, case_id, title, start_at, end_at, location, appointment_type) VALUES
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000002',
'Mandantenbesprechung BrandHouse', CURRENT_DATE + INTERVAL '2 days' + TIME '14:00', CURRENT_DATE + INTERVAL '2 days' + TIME '15:30',
'Kanzlei, Besprechungsraum 1', 'consultation');
-- ============================================================
-- Case 3: Arbeitsgericht (labor law) — active
-- ============================================================
INSERT INTO cases (id, tenant_id, case_number, title, case_type, court, court_ref, status) VALUES
('c0000000-0000-0000-0000-000000000003',
'a0000000-0000-0000-0000-000000000001',
'2026/003', 'Schmidt ./. AutoWerk Bayern GmbH — Kündigungsschutz',
'labor', 'ArbG München', '12 Ca 456/26',
'active');
INSERT INTO parties (id, tenant_id, case_id, name, role, representative) VALUES
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000003',
'Klaus Schmidt', 'claimant', 'RA Dr. Siebels'),
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000003',
'AutoWerk Bayern GmbH', 'defendant', 'RA Fischer');
INSERT INTO deadlines (id, tenant_id, case_id, title, due_date, warning_date, status, source) VALUES
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000003',
'Kündigungsschutzklage einreichen (3-Wochen-Frist)', CURRENT_DATE + INTERVAL '7 days', CURRENT_DATE + INTERVAL '4 days', 'pending', 'manual'),
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000003',
'Stellungnahme Arbeitgeber', CURRENT_DATE + INTERVAL '28 days', CURRENT_DATE + INTERVAL '21 days', 'pending', 'manual');
INSERT INTO appointments (id, tenant_id, case_id, title, start_at, end_at, location, appointment_type) VALUES
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000003',
'Güteverhandlung', CURRENT_DATE + INTERVAL '35 days' + TIME '09:00', CURRENT_DATE + INTERVAL '35 days' + TIME '10:00',
'ArbG München, Saal 12', 'hearing');
-- ============================================================
-- Case 4: Mietrecht (tenancy) — active
-- ============================================================
INSERT INTO cases (id, tenant_id, case_number, title, case_type, court, court_ref, status) VALUES
('c0000000-0000-0000-0000-000000000004',
'a0000000-0000-0000-0000-000000000001',
'2026/004', 'Hausverwaltung Zentral ./. Meier — Mietrückstand',
'civil', 'AG München', '432 C 1234/26',
'active');
INSERT INTO parties (id, tenant_id, case_id, name, role, representative) VALUES
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000004',
'Hausverwaltung Zentral GmbH', 'claimant', 'RA Dr. Siebels'),
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000004',
'Thomas Meier', 'defendant', NULL);
INSERT INTO deadlines (id, tenant_id, case_id, title, due_date, warning_date, status, source) VALUES
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000004',
'Mahnbescheid beantragen', CURRENT_DATE + INTERVAL '10 days', CURRENT_DATE + INTERVAL '7 days', 'pending', 'manual'),
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000004',
'Räumungsfrist prüfen', CURRENT_DATE + INTERVAL '60 days', CURRENT_DATE + INTERVAL '50 days', 'pending', 'manual');
INSERT INTO appointments (id, tenant_id, case_id, title, start_at, end_at, location, appointment_type) VALUES
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000004',
'Besprechung Hausverwaltung', CURRENT_DATE + INTERVAL '4 days' + TIME '11:00', CURRENT_DATE + INTERVAL '4 days' + TIME '12:00',
'Kanzlei, Besprechungsraum 2', 'meeting');
-- ============================================================
-- Case 5: Erbrecht (inheritance) — closed
-- ============================================================
INSERT INTO cases (id, tenant_id, case_number, title, case_type, court, court_ref, status) VALUES
('c0000000-0000-0000-0000-000000000005',
'a0000000-0000-0000-0000-000000000001',
'2025/042', 'Nachlass Wagner — Erbauseinandersetzung',
'civil', 'AG Starnberg', '3 VI 891/25',
'closed');
INSERT INTO parties (id, tenant_id, case_id, name, role, representative) VALUES
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000005',
'Maria Wagner', 'claimant', 'RA Dr. Siebels'),
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000005',
'Peter Wagner', 'defendant', 'RA Braun');
INSERT INTO deadlines (id, tenant_id, case_id, title, due_date, warning_date, status, source, completed_at) VALUES
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000005',
'Erbscheinsantrag einreichen', CURRENT_DATE - INTERVAL '30 days', CURRENT_DATE - INTERVAL '37 days', 'completed', 'manual', CURRENT_DATE - INTERVAL '32 days');
-- ============================================================
-- Case events for realistic activity feed
-- ============================================================
INSERT INTO case_events (id, tenant_id, case_id, event_type, title, description, created_at, updated_at) VALUES
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000001',
'case_created', 'Akte angelegt', 'Patentverletzungsklage TechCorp ./. InnovatAG eröffnet', NOW() - INTERVAL '10 days', NOW() - INTERVAL '10 days'),
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000001',
'party_added', 'Partei hinzugefügt', 'TechCorp GmbH als Kläger eingetragen', NOW() - INTERVAL '10 days', NOW() - INTERVAL '10 days'),
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000002',
'case_created', 'Akte angelegt', 'Markenrechtsstreit BrandHouse ./. CopyShop eröffnet', NOW() - INTERVAL '7 days', NOW() - INTERVAL '7 days'),
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000003',
'case_created', 'Akte angelegt', 'Kündigungsschutzklage Schmidt eröffnet', NOW() - INTERVAL '5 days', NOW() - INTERVAL '5 days'),
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000004',
'case_created', 'Akte angelegt', 'Mietrückstand Hausverwaltung ./. Meier eröffnet', NOW() - INTERVAL '3 days', NOW() - INTERVAL '3 days'),
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000001',
'status_changed', 'Fristablauf überschritten', 'Schriftsatz Anspruch 3 ist überfällig', NOW() - INTERVAL '1 day', NOW() - INTERVAL '1 day'),
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000005',
'case_created', 'Akte angelegt', 'Erbauseinandersetzung Wagner eröffnet', NOW() - INTERVAL '60 days', NOW() - INTERVAL '60 days'),
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000005',
'status_changed', 'Akte geschlossen', 'Erbscheinsverfahren abgeschlossen', NOW() - INTERVAL '20 days', NOW() - INTERVAL '20 days');

View File

@@ -6,6 +6,12 @@ services:
- "8080"
environment:
- PORT=8080
- DATABASE_URL=${DATABASE_URL}
- SUPABASE_URL=${SUPABASE_URL}
- SUPABASE_ANON_KEY=${SUPABASE_ANON_KEY}
- SUPABASE_SERVICE_KEY=${SUPABASE_SERVICE_KEY}
- SUPABASE_JWT_SECRET=${SUPABASE_JWT_SECRET}
- ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY}
healthcheck:
test: ["CMD", "wget", "--spider", "-q", "http://localhost:8080/health"]
interval: 30s
@@ -23,6 +29,8 @@ services:
condition: service_healthy
environment:
- API_URL=http://backend:8080
- NEXT_PUBLIC_SUPABASE_URL=${SUPABASE_URL}
- NEXT_PUBLIC_SUPABASE_ANON_KEY=${SUPABASE_ANON_KEY}
healthcheck:
test: ["CMD", "node", "-e", "fetch('http://localhost:3000').then(r=>{if(!r.ok)throw r.status;process.exit(0)}).catch(()=>process.exit(1))"]
interval: 30s

View File

@@ -1,116 +0,0 @@
"use client";
import { useQuery } from "@tanstack/react-query";
import { Settings, Calendar, Users } from "lucide-react";
import Link from "next/link";
import { api } from "@/lib/api";
import type { Tenant } from "@/lib/types";
import { CalDAVSettings } from "@/components/settings/CalDAVSettings";
import { SkeletonCard } from "@/components/ui/Skeleton";
import { EmptyState } from "@/components/ui/EmptyState";
export default function EinstellungenPage() {
const tenantId =
typeof window !== "undefined"
? localStorage.getItem("kanzlai_tenant_id")
: null;
const {
data: tenant,
isLoading,
error,
refetch,
} = useQuery({
queryKey: ["tenant-current", tenantId],
queryFn: () => api.get<Tenant>(`/api/tenants/${tenantId}`),
enabled: !!tenantId,
});
return (
<div className="mx-auto max-w-3xl space-y-6 p-4 sm:p-6">
<div className="flex items-center justify-between">
<h1 className="text-lg font-semibold text-neutral-900">
Einstellungen
</h1>
<Link
href="/einstellungen/team"
className="inline-flex items-center gap-1.5 rounded-md border border-neutral-200 bg-white px-3 py-1.5 text-sm font-medium text-neutral-700 hover:bg-neutral-50"
>
<Users className="h-3.5 w-3.5" />
Team verwalten
</Link>
</div>
{/* Tenant Info */}
{isLoading ? (
<>
<SkeletonCard />
<SkeletonCard />
</>
) : error ? (
<EmptyState
icon={Settings}
title="Fehler beim Laden"
description="Einstellungen konnten nicht geladen werden."
action={
<button
onClick={() => refetch()}
className="rounded-md bg-neutral-900 px-3 py-1.5 text-sm font-medium text-white hover:bg-neutral-800"
>
Erneut versuchen
</button>
}
/>
) : tenant ? (
<>
{/* Kanzlei Info */}
<section className="rounded-xl border border-neutral-200 bg-white p-5">
<div className="flex items-center gap-2.5 border-b border-neutral-100 pb-3">
<Settings className="h-4 w-4 text-neutral-500" />
<h2 className="text-sm font-semibold text-neutral-900">
Kanzlei
</h2>
</div>
<div className="mt-4 grid gap-3 sm:grid-cols-2">
<div>
<p className="text-xs text-neutral-500">Name</p>
<p className="text-sm font-medium text-neutral-900">
{tenant.name}
</p>
</div>
<div>
<p className="text-xs text-neutral-500">Slug</p>
<p className="text-sm font-medium text-neutral-900">
{tenant.slug}
</p>
</div>
<div>
<p className="text-xs text-neutral-500">Erstellt am</p>
<p className="text-sm text-neutral-700">
{new Date(tenant.created_at).toLocaleDateString("de-DE", {
day: "2-digit",
month: "2-digit",
year: "numeric",
})}
</p>
</div>
</div>
</section>
{/* CalDAV Settings */}
<section className="rounded-xl border border-neutral-200 bg-white p-5">
<div className="flex items-center gap-2.5 border-b border-neutral-100 pb-3">
<Calendar className="h-4 w-4 text-neutral-500" />
<h2 className="text-sm font-semibold text-neutral-900">
CalDAV-Synchronisierung
</h2>
</div>
<div className="mt-4">
<CalDAVSettings tenant={tenant} />
</div>
</section>
</>
) : null}
</div>
);
}

View File

@@ -1,40 +0,0 @@
"use client";
import Link from "next/link";
import { ArrowLeft, Users } from "lucide-react";
import { TeamSettings } from "@/components/settings/TeamSettings";
export default function TeamPage() {
return (
<div className="mx-auto max-w-3xl space-y-6 p-4 sm:p-6">
<div className="flex items-center gap-3">
<Link
href="/einstellungen"
className="rounded-md p-1.5 text-neutral-400 hover:bg-neutral-100 hover:text-neutral-600"
>
<ArrowLeft className="h-4 w-4" />
</Link>
<div className="flex items-center gap-2.5">
<Users className="h-4 w-4 text-neutral-500" />
<h1 className="text-lg font-semibold text-neutral-900">
Team verwalten
</h1>
</div>
</div>
<section className="rounded-xl border border-neutral-200 bg-white p-5">
<div className="border-b border-neutral-100 pb-3">
<h2 className="text-sm font-semibold text-neutral-900">
Mitglieder
</h2>
<p className="mt-0.5 text-xs text-neutral-500">
Benutzer einladen und Rollen verwalten
</p>
</div>
<div className="mt-4">
<TeamSettings />
</div>
</section>
</div>
);
}

View File

@@ -1,329 +0,0 @@
"use client";
import { useState, useEffect } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import {
RefreshCw,
CheckCircle2,
AlertCircle,
Clock,
ArrowUpDown,
} from "lucide-react";
import { api } from "@/lib/api";
import type {
Tenant,
CalDAVConfig,
CalDAVSyncResponse,
} from "@/lib/types";
const SYNC_INTERVALS = [
{ value: 5, label: "5 Minuten" },
{ value: 15, label: "15 Minuten" },
{ value: 30, label: "30 Minuten" },
{ value: 60, label: "1 Stunde" },
{ value: 120, label: "2 Stunden" },
{ value: 360, label: "6 Stunden" },
];
const emptyConfig: CalDAVConfig = {
url: "",
username: "",
password: "",
calendar_path: "",
sync_enabled: false,
sync_interval_minutes: 15,
};
export function CalDAVSettings({ tenant }: { tenant: Tenant }) {
const queryClient = useQueryClient();
const existing = (tenant.settings as Record<string, unknown>)?.caldav as
| Partial<CalDAVConfig>
| undefined;
const [config, setConfig] = useState<CalDAVConfig>({
...emptyConfig,
...existing,
});
const [showPassword, setShowPassword] = useState(false);
// Reset form when tenant changes
useEffect(() => {
const caldav = (tenant.settings as Record<string, unknown>)?.caldav as
| Partial<CalDAVConfig>
| undefined;
setConfig({ ...emptyConfig, ...caldav });
}, [tenant]);
// Fetch sync status
const { data: syncStatus } = useQuery({
queryKey: ["caldav-status"],
queryFn: () => api.get<CalDAVSyncResponse>("/api/caldav/status"),
refetchInterval: 30_000,
});
// Save settings
const saveMutation = useMutation({
mutationFn: (cfg: CalDAVConfig) => {
const tenantId =
typeof window !== "undefined"
? localStorage.getItem("kanzlai_tenant_id")
: null;
return api.put<Tenant>(`/api/tenants/${tenantId}/settings`, {
caldav: cfg,
});
},
onSuccess: (updated) => {
queryClient.setQueryData(["tenant-current"], updated);
toast.success("CalDAV-Einstellungen gespeichert");
},
onError: () => {
toast.error("Fehler beim Speichern der CalDAV-Einstellungen");
},
});
// Trigger sync
const syncMutation = useMutation({
mutationFn: () => api.post<CalDAVSyncResponse>("/api/caldav/sync"),
onSuccess: (result) => {
queryClient.invalidateQueries({ queryKey: ["caldav-status"] });
if (result.status === "ok") {
toast.success(
`Synchronisierung abgeschlossen: ${result.sync.items_pushed} gesendet, ${result.sync.items_pulled} empfangen`
);
} else {
toast.error("Synchronisierung mit Fehlern abgeschlossen");
}
},
onError: () => {
toast.error("Fehler bei der Synchronisierung");
},
});
const handleSave = (e: React.FormEvent) => {
e.preventDefault();
saveMutation.mutate(config);
};
const hasConfig = config.url && config.username && config.password;
return (
<div className="space-y-6">
{/* CalDAV Configuration Form */}
<form onSubmit={handleSave} className="space-y-4">
<div className="grid gap-4 sm:grid-cols-2">
<div className="sm:col-span-2">
<label className="mb-1 block text-sm font-medium text-neutral-700">
CalDAV-Server URL
</label>
<input
type="url"
value={config.url}
onChange={(e) =>
setConfig((c) => ({ ...c, url: e.target.value }))
}
placeholder="https://dav.example.com/dav"
className="w-full rounded-md border border-neutral-200 px-3 py-1.5 text-sm outline-none focus:border-neutral-400 focus:ring-1 focus:ring-neutral-400"
/>
</div>
<div>
<label className="mb-1 block text-sm font-medium text-neutral-700">
Benutzername
</label>
<input
type="text"
value={config.username}
onChange={(e) =>
setConfig((c) => ({ ...c, username: e.target.value }))
}
placeholder="user@example.com"
className="w-full rounded-md border border-neutral-200 px-3 py-1.5 text-sm outline-none focus:border-neutral-400 focus:ring-1 focus:ring-neutral-400"
/>
</div>
<div>
<label className="mb-1 block text-sm font-medium text-neutral-700">
Passwort
</label>
<div className="relative">
<input
type={showPassword ? "text" : "password"}
value={config.password}
onChange={(e) =>
setConfig((c) => ({ ...c, password: e.target.value }))
}
placeholder="••••••••"
className="w-full rounded-md border border-neutral-200 px-3 py-1.5 pr-16 text-sm outline-none focus:border-neutral-400 focus:ring-1 focus:ring-neutral-400"
/>
<button
type="button"
onClick={() => setShowPassword(!showPassword)}
className="absolute right-2 top-1/2 -translate-y-1/2 text-xs text-neutral-500 hover:text-neutral-700"
>
{showPassword ? "Verbergen" : "Anzeigen"}
</button>
</div>
</div>
<div className="sm:col-span-2">
<label className="mb-1 block text-sm font-medium text-neutral-700">
Kalender-Pfad
</label>
<input
type="text"
value={config.calendar_path}
onChange={(e) =>
setConfig((c) => ({ ...c, calendar_path: e.target.value }))
}
placeholder="/dav/calendars/user/default/"
className="w-full rounded-md border border-neutral-200 px-3 py-1.5 text-sm outline-none focus:border-neutral-400 focus:ring-1 focus:ring-neutral-400"
/>
<p className="mt-1 text-xs text-neutral-400">
Pfad zum Kalender auf dem CalDAV-Server
</p>
</div>
</div>
{/* Sync Settings */}
<div className="flex flex-col gap-4 border-t border-neutral-200 pt-4 sm:flex-row sm:items-center sm:justify-between">
<label className="flex items-center gap-2.5">
<input
type="checkbox"
checked={config.sync_enabled}
onChange={(e) =>
setConfig((c) => ({ ...c, sync_enabled: e.target.checked }))
}
className="h-4 w-4 rounded border-neutral-300 text-neutral-900 focus:ring-neutral-400"
/>
<span className="text-sm font-medium text-neutral-700">
Automatische Synchronisierung
</span>
</label>
<div className="flex items-center gap-2">
<label className="text-sm text-neutral-500">Intervall:</label>
<select
value={config.sync_interval_minutes}
onChange={(e) =>
setConfig((c) => ({
...c,
sync_interval_minutes: Number(e.target.value),
}))
}
disabled={!config.sync_enabled}
className="rounded-md border border-neutral-200 px-2 py-1 text-sm outline-none focus:border-neutral-400 focus:ring-1 focus:ring-neutral-400 disabled:opacity-50"
>
{SYNC_INTERVALS.map((opt) => (
<option key={opt.value} value={opt.value}>
{opt.label}
</option>
))}
</select>
</div>
</div>
<div className="flex items-center gap-3 border-t border-neutral-200 pt-4">
<button
type="submit"
disabled={saveMutation.isPending}
className="rounded-md bg-neutral-900 px-4 py-1.5 text-sm font-medium text-white hover:bg-neutral-800 disabled:opacity-50"
>
{saveMutation.isPending ? "Speichern..." : "Speichern"}
</button>
{hasConfig && (
<button
type="button"
onClick={() => syncMutation.mutate()}
disabled={syncMutation.isPending}
className="inline-flex items-center gap-1.5 rounded-md border border-neutral-200 bg-white px-4 py-1.5 text-sm font-medium text-neutral-700 hover:bg-neutral-50 disabled:opacity-50"
>
<RefreshCw
className={`h-3.5 w-3.5 ${syncMutation.isPending ? "animate-spin" : ""}`}
/>
{syncMutation.isPending
? "Synchronisiere..."
: "Jetzt synchronisieren"}
</button>
)}
</div>
</form>
{/* Sync Status */}
{syncStatus && syncStatus.last_sync_at !== null && (
<SyncStatusDisplay data={syncStatus} />
)}
</div>
);
}
function SyncStatusDisplay({ data }: { data: CalDAVSyncResponse }) {
const hasErrors = data.sync?.errors && data.sync.errors.length > 0;
const lastSync = data.sync?.last_sync_at
? new Date(data.sync.last_sync_at)
: null;
return (
<div
className={`rounded-lg border p-4 ${
hasErrors
? "border-red-200 bg-red-50"
: "border-emerald-200 bg-emerald-50"
}`}
>
<div className="flex items-start gap-3">
{hasErrors ? (
<AlertCircle className="mt-0.5 h-4 w-4 shrink-0 text-red-600" />
) : (
<CheckCircle2 className="mt-0.5 h-4 w-4 shrink-0 text-emerald-600" />
)}
<div className="min-w-0 flex-1">
<p
className={`text-sm font-medium ${hasErrors ? "text-red-800" : "text-emerald-800"}`}
>
{hasErrors
? "Letzte Synchronisierung mit Fehlern"
: "Letzte Synchronisierung erfolgreich"}
</p>
<div className="mt-2 flex flex-wrap gap-x-4 gap-y-1 text-xs">
{lastSync && (
<span className="inline-flex items-center gap-1 text-neutral-600">
<Clock className="h-3 w-3" />
{lastSync.toLocaleDateString("de-DE", {
day: "2-digit",
month: "2-digit",
year: "numeric",
})}{" "}
{lastSync.toLocaleTimeString("de-DE", {
hour: "2-digit",
minute: "2-digit",
})}
</span>
)}
<span className="inline-flex items-center gap-1 text-neutral-600">
<ArrowUpDown className="h-3 w-3" />
{data.sync.items_pushed} gesendet, {data.sync.items_pulled}{" "}
empfangen
</span>
{data.sync.sync_duration && (
<span className="text-neutral-400">
Dauer: {data.sync.sync_duration}
</span>
)}
</div>
{hasErrors && (
<div className="mt-2 space-y-1">
{data.sync.errors!.map((err, i) => (
<p key={i} className="text-xs text-red-700">
{err}
</p>
))}
</div>
)}
</div>
</div>
</div>
);
}

View File

@@ -1,167 +0,0 @@
"use client";
import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { UserPlus, Trash2, Shield, Crown, User } from "lucide-react";
import { api } from "@/lib/api";
import type { UserTenant } from "@/lib/types";
import { Skeleton } from "@/components/ui/Skeleton";
import { EmptyState } from "@/components/ui/EmptyState";
const ROLE_LABELS: Record<string, { label: string; icon: typeof Crown }> = {
owner: { label: "Eigentümer", icon: Crown },
admin: { label: "Administrator", icon: Shield },
member: { label: "Mitglied", icon: User },
};
export function TeamSettings() {
const queryClient = useQueryClient();
const tenantId =
typeof window !== "undefined"
? localStorage.getItem("kanzlai_tenant_id")
: null;
const [email, setEmail] = useState("");
const [role, setRole] = useState("member");
const {
data: members,
isLoading,
error,
} = useQuery({
queryKey: ["tenant-members", tenantId],
queryFn: () =>
api.get<UserTenant[]>(`/api/tenants/${tenantId}/members`),
enabled: !!tenantId,
});
const inviteMutation = useMutation({
mutationFn: (data: { email: string; role: string }) =>
api.post(`/api/tenants/${tenantId}/invite`, data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["tenant-members"] });
setEmail("");
setRole("member");
toast.success("Benutzer eingeladen");
},
onError: (err: { error?: string }) => {
toast.error(err.error || "Fehler beim Einladen");
},
});
const removeMutation = useMutation({
mutationFn: (userId: string) =>
api.delete(`/api/tenants/${tenantId}/members/${userId}`),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["tenant-members"] });
toast.success("Mitglied entfernt");
},
onError: (err: { error?: string }) => {
toast.error(err.error || "Fehler beim Entfernen");
},
});
const handleInvite = (e: React.FormEvent) => {
e.preventDefault();
if (!email.trim()) return;
inviteMutation.mutate({ email: email.trim(), role });
};
if (isLoading) {
return (
<div className="space-y-3">
<Skeleton className="h-10 w-full" />
<Skeleton className="h-10 w-full" />
<Skeleton className="h-10 w-full" />
</div>
);
}
if (error) {
return (
<EmptyState
icon={User}
title="Fehler beim Laden"
description="Team-Mitglieder konnten nicht geladen werden."
/>
);
}
return (
<div className="space-y-6">
{/* Invite Form */}
<form onSubmit={handleInvite} className="flex flex-col gap-3 sm:flex-row">
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="name@example.com"
className="flex-1 rounded-md border border-neutral-200 px-3 py-1.5 text-sm outline-none focus:border-neutral-400 focus:ring-1 focus:ring-neutral-400"
/>
<select
value={role}
onChange={(e) => setRole(e.target.value)}
className="rounded-md border border-neutral-200 px-2 py-1.5 text-sm outline-none focus:border-neutral-400 focus:ring-1 focus:ring-neutral-400"
>
<option value="member">Mitglied</option>
<option value="admin">Administrator</option>
</select>
<button
type="submit"
disabled={inviteMutation.isPending || !email.trim()}
className="inline-flex items-center gap-1.5 rounded-md bg-neutral-900 px-4 py-1.5 text-sm font-medium text-white hover:bg-neutral-800 disabled:opacity-50"
>
<UserPlus className="h-3.5 w-3.5" />
{inviteMutation.isPending ? "Einladen..." : "Einladen"}
</button>
</form>
{/* Members List */}
{members && members.length > 0 ? (
<div className="overflow-hidden rounded-md border border-neutral-200">
{members.map((member, i) => {
const roleInfo = ROLE_LABELS[member.role] || ROLE_LABELS.member;
const RoleIcon = roleInfo.icon;
return (
<div
key={member.user_id}
className={`flex items-center justify-between px-4 py-3 ${
i < members.length - 1 ? "border-b border-neutral-100" : ""
}`}
>
<div className="flex items-center gap-3">
<div className="flex h-8 w-8 items-center justify-center rounded-full bg-neutral-100">
<RoleIcon className="h-4 w-4 text-neutral-500" />
</div>
<div>
<p className="text-sm font-medium text-neutral-900">
{member.user_id.slice(0, 8)}...
</p>
<p className="text-xs text-neutral-500">{roleInfo.label}</p>
</div>
</div>
{member.role !== "owner" && (
<button
onClick={() => removeMutation.mutate(member.user_id)}
disabled={removeMutation.isPending}
className="rounded-md p-1.5 text-neutral-400 hover:bg-red-50 hover:text-red-600 disabled:opacity-50"
title="Mitglied entfernen"
>
<Trash2 className="h-4 w-4" />
</button>
)}
</div>
);
})}
</div>
) : (
<EmptyState
icon={User}
title="Noch keine Mitglieder"
description="Laden Sie Teammitglieder per E-Mail ein."
/>
)}
</div>
);
}

View File

@@ -152,30 +152,6 @@ export interface CalculateResponse {
deadlines: CalculatedDeadline[];
}
export interface CalDAVConfig {
url: string;
username: string;
password: string;
calendar_path: string;
sync_enabled: boolean;
sync_interval_minutes: number;
}
export interface CalDAVSyncStatus {
tenant_id: string;
last_sync_at: string;
items_pushed: number;
items_pulled: number;
errors?: string[];
sync_duration: string;
}
export interface CalDAVSyncResponse {
status: string;
sync: CalDAVSyncStatus;
last_sync_at?: null;
}
export interface ApiError {
error: string;
status: number;