Compare commits

..

3 Commits

Author SHA1 Message Date
m
fdb4ac55a1 feat: frontend AI tab — KI-Strategie, KI-Entwurf, Aehnliche Faelle
New "KI" tab on case detail page with three sub-panels:
- KI-Strategie: one-click strategic analysis with next steps, risks, timeline
- KI-Entwurf: document drafting with template selection, language, instructions
- Aehnliche Faelle: UPC similar case search with relevance scores

Components: CaseStrategy, DocumentDrafter, SimilarCaseFinder
Types: StrategyRecommendation, DocumentDraft, SimilarCase, etc.
2026-03-30 11:26:01 +02:00
m
dd683281e0 feat: AI-powered features — document drafting, case strategy, similar case finder (P2)
Backend:
- DraftDocument: Claude generates legal documents from case data + template type
  (14 template types: Klageschrift, UPC claims, Abmahnung, etc.)
- CaseStrategy: Opus-powered strategic analysis with next steps, risk assessment,
  and timeline optimization (structured tool output)
- FindSimilarCases: queries youpc.org Supabase for UPC cases, Claude ranks by
  relevance with explanations and key holdings

Endpoints: POST /api/ai/draft-document, /case-strategy, /similar-cases
All rate-limited (5 req/min) and permission-gated (PermAIExtraction).
YouPC database connection is optional (YOUPC_DATABASE_URL env var).
2026-03-30 11:25:52 +02:00
m
bfd5e354ad fix: resolve merge conflicts from P0 role-based + audit trail branches
Combine role-based permissions (VerifyAccess/GetUserRole) with audit trail
(IP/user-agent context capture) in auth middleware and tenant resolver.
2026-03-30 11:25:41 +02:00
22 changed files with 1712 additions and 1656 deletions

View File

@@ -5,6 +5,9 @@ import (
"net/http"
"os"
"github.com/jmoiron/sqlx"
_ "github.com/lib/pq"
"mgit.msbls.de/m/KanzlAI-mGMT/internal/auth"
"mgit.msbls.de/m/KanzlAI-mGMT/internal/config"
"mgit.msbls.de/m/KanzlAI-mGMT/internal/db"
@@ -31,6 +34,21 @@ func main() {
authMW := auth.NewMiddleware(cfg.SupabaseJWTSecret, database)
// Optional: connect to youpc.org database for similar case finder
var youpcDB *sqlx.DB
if cfg.YouPCDatabaseURL != "" {
youpcDB, err = sqlx.Connect("postgres", cfg.YouPCDatabaseURL)
if err != nil {
slog.Warn("failed to connect to youpc.org database — similar case finder disabled", "error", err)
youpcDB = nil
} else {
youpcDB.SetMaxOpenConns(5)
youpcDB.SetMaxIdleConns(2)
defer youpcDB.Close()
slog.Info("connected to youpc.org database for similar case finder")
}
}
// Start CalDAV sync service
calDAVSvc := services.NewCalDAVService(database)
calDAVSvc.Start()
@@ -41,7 +59,7 @@ func main() {
notifSvc.Start()
defer notifSvc.Stop()
handler := router.New(database, authMW, cfg, calDAVSvc, notifSvc)
handler := router.New(database, authMW, cfg, calDAVSvc, notifSvc, youpcDB)
slog.Info("starting KanzlAI API server", "port", cfg.Port)
if err := http.ListenAndServe(":"+cfg.Port, handler); err != nil {

View File

@@ -11,9 +11,9 @@ type contextKey string
const (
userIDKey contextKey = "user_id"
tenantIDKey contextKey = "tenant_id"
userRoleKey contextKey = "user_role"
ipKey contextKey = "ip_address"
userAgentKey contextKey = "user_agent"
userRoleKey contextKey = "user_role"
)
func ContextWithUserID(ctx context.Context, userID uuid.UUID) context.Context {
@@ -34,6 +34,15 @@ func TenantFromContext(ctx context.Context) (uuid.UUID, bool) {
return id, ok
}
func ContextWithUserRole(ctx context.Context, role string) context.Context {
return context.WithValue(ctx, userRoleKey, role)
}
func UserRoleFromContext(ctx context.Context) string {
role, _ := ctx.Value(userRoleKey).(string)
return role
}
func ContextWithRequestInfo(ctx context.Context, ip, userAgent string) context.Context {
ctx = context.WithValue(ctx, ipKey, ip)
ctx = context.WithValue(ctx, userAgentKey, userAgent)
@@ -53,12 +62,3 @@ func UserAgentFromContext(ctx context.Context) *string {
}
return nil
}
func ContextWithUserRole(ctx context.Context, role string) context.Context {
return context.WithValue(ctx, userRoleKey, role)
}
func UserRoleFromContext(ctx context.Context) string {
role, _ := ctx.Value(userRoleKey).(string)
return role
}

View File

@@ -43,7 +43,8 @@ func (m *Middleware) RequireAuth(next http.Handler) http.Handler {
}
ctx = ContextWithRequestInfo(ctx, ip, r.UserAgent())
// Tenant and role resolution handled by TenantResolver middleware for scoped routes.
// Tenant resolution is handled by TenantResolver middleware for scoped routes.
// Tenant management routes handle their own access control.
next.ServeHTTP(w, r.WithContext(ctx))
})
}

View File

@@ -12,6 +12,7 @@ import (
// Defined as an interface to avoid circular dependency with services.
type TenantLookup interface {
FirstTenantForUser(ctx context.Context, userID uuid.UUID) (*uuid.UUID, error)
VerifyAccess(ctx context.Context, userID, tenantID uuid.UUID) (bool, error)
GetUserRole(ctx context.Context, userID, tenantID uuid.UUID) (string, error)
}
@@ -34,7 +35,6 @@ func (tr *TenantResolver) Resolve(next http.Handler) http.Handler {
}
var tenantID uuid.UUID
ctx := r.Context()
if header := r.Header.Get("X-Tenant-ID"); header != "" {
parsed, err := uuid.Parse(header)
@@ -56,9 +56,9 @@ func (tr *TenantResolver) Resolve(next http.Handler) http.Handler {
}
tenantID = parsed
ctx = ContextWithUserRole(ctx, role)
r = r.WithContext(ContextWithUserRole(r.Context(), role))
} else {
// Default to user's first tenant
// Default to user's first tenant (role already set by middleware)
first, err := tr.lookup.FirstTenantForUser(r.Context(), userID)
if err != nil {
slog.Error("failed to resolve default tenant", "error", err, "user_id", userID)
@@ -70,18 +70,9 @@ func (tr *TenantResolver) Resolve(next http.Handler) http.Handler {
return
}
tenantID = *first
// Look up role for default tenant
role, err := tr.lookup.GetUserRole(r.Context(), userID, tenantID)
if err != nil {
slog.Error("failed to get user role", "error", err, "user_id", userID, "tenant_id", tenantID)
http.Error(w, `{"error":"internal error"}`, http.StatusInternalServerError)
return
}
ctx = ContextWithUserRole(ctx, role)
}
ctx = ContextWithTenantID(ctx, tenantID)
ctx := ContextWithTenantID(r.Context(), tenantID)
next.ServeHTTP(w, r.WithContext(ctx))
})
}

View File

@@ -10,32 +10,43 @@ import (
)
type mockTenantLookup struct {
tenantID *uuid.UUID
role string
err error
tenantID *uuid.UUID
err error
hasAccess bool
accessErr error
role string
noAccess bool // when true, GetUserRole returns ""
}
func (m *mockTenantLookup) FirstTenantForUser(ctx context.Context, userID uuid.UUID) (*uuid.UUID, error) {
return m.tenantID, m.err
}
func (m *mockTenantLookup) VerifyAccess(ctx context.Context, userID, tenantID uuid.UUID) (bool, error) {
return m.hasAccess, m.accessErr
}
func (m *mockTenantLookup) GetUserRole(ctx context.Context, userID, tenantID uuid.UUID) (string, error) {
return m.role, m.err
if m.noAccess {
return "", m.err
}
if m.role != "" {
return m.role, m.err
}
return "associate", m.err
}
func TestTenantResolver_FromHeader(t *testing.T) {
tenantID := uuid.New()
tr := NewTenantResolver(&mockTenantLookup{role: "partner"})
tr := NewTenantResolver(&mockTenantLookup{role: "partner", hasAccess: true})
var gotTenantID uuid.UUID
var gotRole string
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id, ok := TenantFromContext(r.Context())
if !ok {
t.Fatal("tenant ID not in context")
}
gotTenantID = id
gotRole = UserRoleFromContext(r.Context())
w.WriteHeader(http.StatusOK)
})
@@ -52,14 +63,11 @@ func TestTenantResolver_FromHeader(t *testing.T) {
if gotTenantID != tenantID {
t.Errorf("expected tenant %s, got %s", tenantID, gotTenantID)
}
if gotRole != "partner" {
t.Errorf("expected role partner, got %s", gotRole)
}
}
func TestTenantResolver_FromHeader_NoAccess(t *testing.T) {
tenantID := uuid.New()
tr := NewTenantResolver(&mockTenantLookup{role: ""})
tr := NewTenantResolver(&mockTenantLookup{noAccess: true})
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Fatal("next should not be called")
@@ -79,7 +87,7 @@ func TestTenantResolver_FromHeader_NoAccess(t *testing.T) {
func TestTenantResolver_DefaultsToFirst(t *testing.T) {
tenantID := uuid.New()
tr := NewTenantResolver(&mockTenantLookup{tenantID: &tenantID, role: "associate"})
tr := NewTenantResolver(&mockTenantLookup{tenantID: &tenantID})
var gotTenantID uuid.UUID
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

View File

@@ -14,6 +14,7 @@ type Config struct {
SupabaseJWTSecret string
AnthropicAPIKey string
FrontendOrigin string
YouPCDatabaseURL string // read-only connection to youpc.org Supabase for similar case finder
}
func Load() (*Config, error) {
@@ -26,6 +27,7 @@ func Load() (*Config, error) {
SupabaseJWTSecret: os.Getenv("SUPABASE_JWT_SECRET"),
AnthropicAPIKey: os.Getenv("ANTHROPIC_API_KEY"),
FrontendOrigin: getEnv("FRONTEND_ORIGIN", "https://kanzlai.msbls.de"),
YouPCDatabaseURL: os.Getenv("YOUPC_DATABASE_URL"),
}
if cfg.DatabaseURL == "" {

View File

@@ -5,6 +5,8 @@ import (
"io"
"net/http"
"github.com/google/uuid"
"mgit.msbls.de/m/KanzlAI-mGMT/internal/auth"
"mgit.msbls.de/m/KanzlAI-mGMT/internal/services"
)
@@ -115,3 +117,139 @@ func (h *AIHandler) SummarizeCase(w http.ResponseWriter, r *http.Request) {
"summary": summary,
})
}
// DraftDocument handles POST /api/ai/draft-document
// Accepts JSON {"case_id": "uuid", "template_type": "string", "instructions": "string", "language": "de|en|fr"}.
func (h *AIHandler) DraftDocument(w http.ResponseWriter, r *http.Request) {
tenantID, ok := auth.TenantFromContext(r.Context())
if !ok {
writeError(w, http.StatusForbidden, "missing tenant")
return
}
var body struct {
CaseID string `json:"case_id"`
TemplateType string `json:"template_type"`
Instructions string `json:"instructions"`
Language string `json:"language"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
writeError(w, http.StatusBadRequest, "invalid request body")
return
}
if body.CaseID == "" {
writeError(w, http.StatusBadRequest, "case_id is required")
return
}
if body.TemplateType == "" {
writeError(w, http.StatusBadRequest, "template_type is required")
return
}
caseID, err := parseUUID(body.CaseID)
if err != nil {
writeError(w, http.StatusBadRequest, "invalid case_id")
return
}
if len(body.Instructions) > maxDescriptionLen {
writeError(w, http.StatusBadRequest, "instructions exceeds maximum length")
return
}
draft, err := h.ai.DraftDocument(r.Context(), tenantID, caseID, body.TemplateType, body.Instructions, body.Language)
if err != nil {
internalError(w, "AI document drafting failed", err)
return
}
writeJSON(w, http.StatusOK, draft)
}
// CaseStrategy handles POST /api/ai/case-strategy
// Accepts JSON {"case_id": "uuid"}.
func (h *AIHandler) CaseStrategy(w http.ResponseWriter, r *http.Request) {
tenantID, ok := auth.TenantFromContext(r.Context())
if !ok {
writeError(w, http.StatusForbidden, "missing tenant")
return
}
var body struct {
CaseID string `json:"case_id"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
writeError(w, http.StatusBadRequest, "invalid request body")
return
}
if body.CaseID == "" {
writeError(w, http.StatusBadRequest, "case_id is required")
return
}
caseID, err := parseUUID(body.CaseID)
if err != nil {
writeError(w, http.StatusBadRequest, "invalid case_id")
return
}
strategy, err := h.ai.CaseStrategy(r.Context(), tenantID, caseID)
if err != nil {
internalError(w, "AI case strategy analysis failed", err)
return
}
writeJSON(w, http.StatusOK, strategy)
}
// SimilarCases handles POST /api/ai/similar-cases
// Accepts JSON {"case_id": "uuid", "description": "string"}.
func (h *AIHandler) SimilarCases(w http.ResponseWriter, r *http.Request) {
tenantID, ok := auth.TenantFromContext(r.Context())
if !ok {
writeError(w, http.StatusForbidden, "missing tenant")
return
}
var body struct {
CaseID string `json:"case_id"`
Description string `json:"description"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
writeError(w, http.StatusBadRequest, "invalid request body")
return
}
if body.CaseID == "" && body.Description == "" {
writeError(w, http.StatusBadRequest, "either case_id or description is required")
return
}
if len(body.Description) > maxDescriptionLen {
writeError(w, http.StatusBadRequest, "description exceeds maximum length")
return
}
var caseID uuid.UUID
if body.CaseID != "" {
var err error
caseID, err = parseUUID(body.CaseID)
if err != nil {
writeError(w, http.StatusBadRequest, "invalid case_id")
return
}
}
cases, err := h.ai.FindSimilarCases(r.Context(), tenantID, caseID, body.Description)
if err != nil {
internalError(w, "AI similar case search failed", err)
return
}
writeJSON(w, http.StatusOK, map[string]any{
"cases": cases,
"count": len(cases),
})
}

View File

@@ -1,127 +0,0 @@
package handlers
import (
"encoding/json"
"net/http"
"github.com/google/uuid"
"mgit.msbls.de/m/KanzlAI-mGMT/internal/auth"
"mgit.msbls.de/m/KanzlAI-mGMT/internal/services"
)
// DetermineHandlers holds handlers for deadline determination endpoints
type DetermineHandlers struct {
determine *services.DetermineService
deadlines *services.DeadlineService
}
// NewDetermineHandlers creates determine handlers
func NewDetermineHandlers(determine *services.DetermineService, deadlines *services.DeadlineService) *DetermineHandlers {
return &DetermineHandlers{determine: determine, deadlines: deadlines}
}
// GetTimeline handles GET /api/proceeding-types/{code}/timeline
// Returns the full event tree for a proceeding type (no date calculations)
func (h *DetermineHandlers) GetTimeline(w http.ResponseWriter, r *http.Request) {
code := r.PathValue("code")
if code == "" {
writeError(w, http.StatusBadRequest, "proceeding type code required")
return
}
timeline, pt, err := h.determine.GetTimeline(code)
if err != nil {
writeError(w, http.StatusNotFound, "proceeding type not found")
return
}
writeJSON(w, http.StatusOK, map[string]any{
"proceeding_type": pt,
"timeline": timeline,
})
}
// Determine handles POST /api/deadlines/determine
// Calculates the full timeline with cascading dates and conditional logic
func (h *DetermineHandlers) Determine(w http.ResponseWriter, r *http.Request) {
var req services.DetermineRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "invalid request body")
return
}
if req.ProceedingType == "" || req.TriggerEventDate == "" {
writeError(w, http.StatusBadRequest, "proceeding_type and trigger_event_date are required")
return
}
resp, err := h.determine.Determine(req)
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
writeJSON(w, http.StatusOK, resp)
}
// BatchCreate handles POST /api/cases/{caseID}/deadlines/batch
// Creates multiple deadlines on a case from determined timeline
func (h *DetermineHandlers) BatchCreate(w http.ResponseWriter, r *http.Request) {
tenantID, ok := auth.TenantFromContext(r.Context())
if !ok {
writeError(w, http.StatusForbidden, "missing tenant")
return
}
caseID, err := parsePathUUID(r, "caseID")
if err != nil {
writeError(w, http.StatusBadRequest, "invalid case ID")
return
}
var req struct {
Deadlines []struct {
Title string `json:"title"`
DueDate string `json:"due_date"`
OriginalDueDate *string `json:"original_due_date,omitempty"`
RuleID *uuid.UUID `json:"rule_id,omitempty"`
RuleCode *string `json:"rule_code,omitempty"`
Notes *string `json:"notes,omitempty"`
} `json:"deadlines"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "invalid request body")
return
}
if len(req.Deadlines) == 0 {
writeError(w, http.StatusBadRequest, "at least one deadline is required")
return
}
var created int
for _, d := range req.Deadlines {
if d.Title == "" || d.DueDate == "" {
continue
}
input := services.CreateDeadlineInput{
CaseID: caseID,
Title: d.Title,
DueDate: d.DueDate,
Source: "determined",
RuleID: d.RuleID,
Notes: d.Notes,
}
_, err := h.deadlines.Create(r.Context(), tenantID, input)
if err != nil {
internalError(w, "failed to create deadline", err)
return
}
created++
}
writeJSON(w, http.StatusCreated, map[string]any{
"created": created,
})
}

View File

@@ -26,8 +26,6 @@ type DeadlineRule struct {
AltDurationValue *int `db:"alt_duration_value" json:"alt_duration_value,omitempty"`
AltDurationUnit *string `db:"alt_duration_unit" json:"alt_duration_unit,omitempty"`
AltRuleCode *string `db:"alt_rule_code" json:"alt_rule_code,omitempty"`
IsSpawn bool `db:"is_spawn" json:"is_spawn"`
SpawnLabel *string `db:"spawn_label" json:"spawn_label,omitempty"`
IsActive bool `db:"is_active" json:"is_active"`
CreatedAt time.Time `db:"created_at" json:"created_at"`
UpdatedAt time.Time `db:"updated_at" json:"updated_at"`

View File

@@ -15,7 +15,7 @@ import (
"mgit.msbls.de/m/KanzlAI-mGMT/internal/services"
)
func New(db *sqlx.DB, authMW *auth.Middleware, cfg *config.Config, calDAVSvc *services.CalDAVService, notifSvc *services.NotificationService) http.Handler {
func New(db *sqlx.DB, authMW *auth.Middleware, cfg *config.Config, calDAVSvc *services.CalDAVService, notifSvc *services.NotificationService, youpcDB ...*sqlx.DB) http.Handler {
mux := http.NewServeMux()
// Services
@@ -28,7 +28,6 @@ func New(db *sqlx.DB, authMW *auth.Middleware, cfg *config.Config, calDAVSvc *se
deadlineSvc := services.NewDeadlineService(db, auditSvc)
deadlineRuleSvc := services.NewDeadlineRuleService(db)
calculator := services.NewDeadlineCalculator(holidaySvc)
determineSvc := services.NewDetermineService(db, calculator)
storageCli := services.NewStorageClient(cfg.SupabaseURL, cfg.SupabaseServiceKey)
documentSvc := services.NewDocumentService(db, storageCli, auditSvc)
assignmentSvc := services.NewCaseAssignmentService(db)
@@ -36,7 +35,11 @@ func New(db *sqlx.DB, authMW *auth.Middleware, cfg *config.Config, calDAVSvc *se
// AI service (optional — only if API key is configured)
var aiH *handlers.AIHandler
if cfg.AnthropicAPIKey != "" {
aiSvc := services.NewAIService(cfg.AnthropicAPIKey, db)
var ydb *sqlx.DB
if len(youpcDB) > 0 {
ydb = youpcDB[0]
}
aiSvc := services.NewAIService(cfg.AnthropicAPIKey, db, ydb)
aiH = handlers.NewAIHandler(aiSvc)
}
@@ -61,7 +64,6 @@ func New(db *sqlx.DB, authMW *auth.Middleware, cfg *config.Config, calDAVSvc *se
deadlineH := handlers.NewDeadlineHandlers(deadlineSvc)
ruleH := handlers.NewDeadlineRuleHandlers(deadlineRuleSvc)
calcH := handlers.NewCalculateHandlers(calculator, deadlineRuleSvc)
determineH := handlers.NewDetermineHandlers(determineSvc, deadlineSvc)
dashboardH := handlers.NewDashboardHandler(dashboardSvc)
noteH := handlers.NewNoteHandler(noteSvc)
eventH := handlers.NewCaseEventHandler(db)
@@ -108,7 +110,7 @@ func New(db *sqlx.DB, authMW *auth.Middleware, cfg *config.Config, calDAVSvc *se
scoped.HandleFunc("GET /api/cases", caseH.List)
scoped.HandleFunc("POST /api/cases", perm(auth.PermCreateCase, caseH.Create))
scoped.HandleFunc("GET /api/cases/{id}", caseH.Get)
scoped.HandleFunc("PUT /api/cases/{id}", caseH.Update)
scoped.HandleFunc("PUT /api/cases/{id}", caseH.Update) // case-level access checked in handler
scoped.HandleFunc("DELETE /api/cases/{id}", perm(auth.PermCreateCase, caseH.Delete))
// Parties — same access as case editing
@@ -134,11 +136,6 @@ func New(db *sqlx.DB, authMW *auth.Middleware, cfg *config.Config, calDAVSvc *se
// Deadline calculator — all can use
scoped.HandleFunc("POST /api/deadlines/calculate", calcH.Calculate)
// Deadline determination — full timeline calculation with conditions
scoped.HandleFunc("GET /api/proceeding-types/{code}/timeline", determineH.GetTimeline)
scoped.HandleFunc("POST /api/deadlines/determine", determineH.Determine)
scoped.HandleFunc("POST /api/cases/{caseID}/deadlines/batch", perm(auth.PermManageDeadlines, determineH.BatchCreate))
// Appointments — all can manage (PermManageAppointments granted to all)
scoped.HandleFunc("GET /api/appointments/{id}", apptH.Get)
scoped.HandleFunc("GET /api/appointments", apptH.List)
@@ -171,13 +168,16 @@ func New(db *sqlx.DB, authMW *auth.Middleware, cfg *config.Config, calDAVSvc *se
scoped.HandleFunc("POST /api/cases/{id}/documents", perm(auth.PermUploadDocuments, docH.Upload))
scoped.HandleFunc("GET /api/documents/{docId}", docH.Download)
scoped.HandleFunc("GET /api/documents/{docId}/meta", docH.GetMeta)
scoped.HandleFunc("DELETE /api/documents/{docId}", docH.Delete)
scoped.HandleFunc("DELETE /api/documents/{docId}", docH.Delete) // permission check inside handler
// AI endpoints (rate limited: 5 req/min burst 10 per IP)
if aiH != nil {
aiLimiter := middleware.NewTokenBucket(5.0/60.0, 10)
scoped.HandleFunc("POST /api/ai/extract-deadlines", perm(auth.PermAIExtraction, aiLimiter.LimitFunc(aiH.ExtractDeadlines)))
scoped.HandleFunc("POST /api/ai/summarize-case", perm(auth.PermAIExtraction, aiLimiter.LimitFunc(aiH.SummarizeCase)))
scoped.HandleFunc("POST /api/ai/draft-document", perm(auth.PermAIExtraction, aiLimiter.LimitFunc(aiH.DraftDocument)))
scoped.HandleFunc("POST /api/ai/case-strategy", perm(auth.PermAIExtraction, aiLimiter.LimitFunc(aiH.CaseStrategy)))
scoped.HandleFunc("POST /api/ai/similar-cases", perm(auth.PermAIExtraction, aiLimiter.LimitFunc(aiH.SimilarCases)))
}
// Notifications

View File

@@ -5,6 +5,7 @@ import (
"encoding/base64"
"encoding/json"
"fmt"
"strings"
"time"
"github.com/anthropics/anthropic-sdk-go"
@@ -18,11 +19,12 @@ import (
type AIService struct {
client anthropic.Client
db *sqlx.DB
youpcDB *sqlx.DB // read-only connection to youpc.org for similar case finder (may be nil)
}
func NewAIService(apiKey string, db *sqlx.DB) *AIService {
func NewAIService(apiKey string, db *sqlx.DB, youpcDB *sqlx.DB) *AIService {
client := anthropic.NewClient(option.WithAPIKey(apiKey))
return &AIService{client: client, db: db}
return &AIService{client: client, db: db, youpcDB: youpcDB}
}
// ExtractedDeadline represents a deadline extracted by AI from a document.
@@ -281,3 +283,726 @@ func (s *AIService) SummarizeCase(ctx context.Context, tenantID, caseID uuid.UUI
return summary, nil
}
// --- Document Drafting ---
// DocumentDraft represents an AI-generated document draft.
type DocumentDraft struct {
Title string `json:"title"`
Content string `json:"content"`
Language string `json:"language"`
}
// templateDescriptions maps template type IDs to descriptions for Claude.
var templateDescriptions = map[string]string{
"klageschrift": "Klageschrift (Statement of Claim) — formal complaint initiating legal proceedings",
"klageerwiderung": "Klageerwiderung (Statement of Defence) — formal response to a statement of claim",
"abmahnung": "Abmahnung (Cease and Desist Letter) — formal warning letter demanding cessation of an activity",
"schriftsatz": "Schriftsatz (Legal Brief) — formal legal submission to the court",
"berufung": "Berufungsschrift (Appeal Brief) — formal appeal against a court decision",
"antrag": "Antrag (Motion/Application) — formal application or motion to the court",
"stellungnahme": "Stellungnahme (Statement/Position Paper) — formal response or position paper",
"gutachten": "Gutachten (Legal Opinion/Expert Report) — detailed legal analysis or opinion",
"vertrag": "Vertrag (Contract/Agreement) — legal contract or agreement between parties",
"vollmacht": "Vollmacht (Power of Attorney) — formal authorization document",
"upc_claim": "UPC Statement of Claim — claim filed at the Unified Patent Court",
"upc_defence": "UPC Statement of Defence — defence filed at the Unified Patent Court",
"upc_counterclaim": "UPC Counterclaim for Revocation — counterclaim for patent revocation at the UPC",
"upc_injunction": "UPC Application for Provisional Measures — application for injunctive relief at the UPC",
}
const draftDocumentSystemPrompt = `You are an expert legal document drafter for German and UPC (Unified Patent Court) patent litigation.
You draft professional legal documents in the requested language, following proper legal formatting conventions.
Guidelines:
- Use proper legal structure with numbered sections and paragraphs
- Include standard legal formalities (headers, salutations, signatures block)
- Reference relevant legal provisions (BGB, ZPO, UPC Rules of Procedure, etc.)
- Use precise legal terminology appropriate for the jurisdiction
- Include placeholders in [BRACKETS] for information that needs to be filled in
- Base the content on the provided case data and instructions
- Output the document as clean text with proper formatting`
// DraftDocument generates an AI-drafted legal document based on case data and a template type.
func (s *AIService) DraftDocument(ctx context.Context, tenantID, caseID uuid.UUID, templateType, instructions, language string) (*DocumentDraft, error) {
if language == "" {
language = "de"
}
langLabel := "German"
if language == "en" {
langLabel = "English"
} else if language == "fr" {
langLabel = "French"
}
// Load case data
var c models.Case
if err := s.db.GetContext(ctx, &c,
"SELECT * FROM cases WHERE id = $1 AND tenant_id = $2", caseID, tenantID); err != nil {
return nil, fmt.Errorf("loading case: %w", err)
}
// Load parties
var parties []models.Party
_ = s.db.SelectContext(ctx, &parties,
"SELECT * FROM parties WHERE case_id = $1 AND tenant_id = $2", caseID, tenantID)
// Load recent events
var events []models.CaseEvent
_ = s.db.SelectContext(ctx, &events,
"SELECT * FROM case_events WHERE case_id = $1 AND tenant_id = $2 ORDER BY created_at DESC LIMIT 15",
caseID, tenantID)
// Load active deadlines
var deadlines []models.Deadline
_ = s.db.SelectContext(ctx, &deadlines,
"SELECT * FROM deadlines WHERE case_id = $1 AND tenant_id = $2 AND status = 'active' ORDER BY due_date ASC LIMIT 10",
caseID, tenantID)
// Load documents metadata for context
var documents []models.Document
_ = s.db.SelectContext(ctx, &documents,
"SELECT id, title, doc_type, created_at FROM documents WHERE case_id = $1 AND tenant_id = $2 ORDER BY created_at DESC LIMIT 10",
caseID, tenantID)
// Build context
var b strings.Builder
b.WriteString(fmt.Sprintf("Case: %s — %s\nStatus: %s\n", c.CaseNumber, c.Title, c.Status))
if c.Court != nil {
b.WriteString(fmt.Sprintf("Court: %s\n", *c.Court))
}
if c.CourtRef != nil {
b.WriteString(fmt.Sprintf("Court Reference: %s\n", *c.CourtRef))
}
if c.CaseType != nil {
b.WriteString(fmt.Sprintf("Type: %s\n", *c.CaseType))
}
if len(parties) > 0 {
b.WriteString("\nParties:\n")
for _, p := range parties {
role := "unknown role"
if p.Role != nil {
role = *p.Role
}
b.WriteString(fmt.Sprintf("- %s (%s)", p.Name, role))
if p.Representative != nil {
b.WriteString(fmt.Sprintf(" — represented by %s", *p.Representative))
}
b.WriteString("\n")
}
}
if len(events) > 0 {
b.WriteString("\nRecent Events:\n")
for _, e := range events {
b.WriteString(fmt.Sprintf("- [%s] %s", e.CreatedAt.Format("2006-01-02"), e.Title))
if e.Description != nil {
b.WriteString(fmt.Sprintf(": %s", *e.Description))
}
b.WriteString("\n")
}
}
if len(deadlines) > 0 {
b.WriteString("\nUpcoming Deadlines:\n")
for _, d := range deadlines {
b.WriteString(fmt.Sprintf("- %s: due %s\n", d.Title, d.DueDate))
}
}
templateDesc, ok := templateDescriptions[templateType]
if !ok {
templateDesc = templateType
}
prompt := fmt.Sprintf(`Draft a %s for this case in %s.
Document type: %s
Case context:
%s
Additional instructions from the lawyer:
%s
Generate the complete document now.`, templateDesc, langLabel, templateDesc, b.String(), instructions)
msg, err := s.client.Messages.New(ctx, anthropic.MessageNewParams{
Model: anthropic.ModelClaudeSonnet4_20250514,
MaxTokens: 8192,
System: []anthropic.TextBlockParam{
{Text: draftDocumentSystemPrompt},
},
Messages: []anthropic.MessageParam{
anthropic.NewUserMessage(anthropic.NewTextBlock(prompt)),
},
})
if err != nil {
return nil, fmt.Errorf("claude API call: %w", err)
}
var content string
for _, block := range msg.Content {
if block.Type == "text" {
content += block.Text
}
}
if content == "" {
return nil, fmt.Errorf("empty response from Claude")
}
title := fmt.Sprintf("%s — %s", templateDesc, c.CaseNumber)
return &DocumentDraft{
Title: title,
Content: content,
Language: language,
}, nil
}
// --- Case Strategy ---
// StrategyRecommendation represents an AI-generated case strategy analysis.
type StrategyRecommendation struct {
Summary string `json:"summary"`
NextSteps []StrategyStep `json:"next_steps"`
RiskAssessment []RiskItem `json:"risk_assessment"`
Timeline []TimelineItem `json:"timeline"`
}
type StrategyStep struct {
Priority string `json:"priority"` // high, medium, low
Action string `json:"action"`
Reasoning string `json:"reasoning"`
Deadline string `json:"deadline,omitempty"`
}
type RiskItem struct {
Level string `json:"level"` // high, medium, low
Risk string `json:"risk"`
Mitigation string `json:"mitigation"`
}
type TimelineItem struct {
Date string `json:"date"`
Event string `json:"event"`
Importance string `json:"importance"` // critical, important, routine
}
type strategyToolInput struct {
Summary string `json:"summary"`
NextSteps []StrategyStep `json:"next_steps"`
RiskAssessment []RiskItem `json:"risk_assessment"`
Timeline []TimelineItem `json:"timeline"`
}
var caseStrategyTool = anthropic.ToolParam{
Name: "case_strategy",
Description: anthropic.String("Provide strategic case analysis with next steps, risk assessment, and timeline optimization."),
InputSchema: anthropic.ToolInputSchemaParam{
Properties: map[string]any{
"summary": map[string]any{
"type": "string",
"description": "Executive summary of the case situation and strategic outlook (2-4 sentences)",
},
"next_steps": map[string]any{
"type": "array",
"description": "Recommended next actions in priority order",
"items": map[string]any{
"type": "object",
"properties": map[string]any{
"priority": map[string]any{
"type": "string",
"enum": []string{"high", "medium", "low"},
},
"action": map[string]any{
"type": "string",
"description": "Specific recommended action",
},
"reasoning": map[string]any{
"type": "string",
"description": "Why this action is recommended",
},
"deadline": map[string]any{
"type": "string",
"description": "Suggested deadline in YYYY-MM-DD format, if applicable",
},
},
"required": []string{"priority", "action", "reasoning"},
},
},
"risk_assessment": map[string]any{
"type": "array",
"description": "Key risks and mitigation strategies",
"items": map[string]any{
"type": "object",
"properties": map[string]any{
"level": map[string]any{
"type": "string",
"enum": []string{"high", "medium", "low"},
},
"risk": map[string]any{
"type": "string",
"description": "Description of the risk",
},
"mitigation": map[string]any{
"type": "string",
"description": "Recommended mitigation strategy",
},
},
"required": []string{"level", "risk", "mitigation"},
},
},
"timeline": map[string]any{
"type": "array",
"description": "Optimized timeline of upcoming milestones and events",
"items": map[string]any{
"type": "object",
"properties": map[string]any{
"date": map[string]any{
"type": "string",
"description": "Date in YYYY-MM-DD format",
},
"event": map[string]any{
"type": "string",
"description": "Description of the milestone or event",
},
"importance": map[string]any{
"type": "string",
"enum": []string{"critical", "important", "routine"},
},
},
"required": []string{"date", "event", "importance"},
},
},
},
Required: []string{"summary", "next_steps", "risk_assessment", "timeline"},
},
}
const caseStrategySystemPrompt = `You are a senior litigation strategist specializing in German law and UPC (Unified Patent Court) patent proceedings.
Analyze the case thoroughly and provide:
1. An executive summary of the current strategic position
2. Prioritized next steps with clear reasoning
3. Risk assessment with mitigation strategies
4. An optimized timeline of upcoming milestones
Consider:
- Procedural deadlines and their implications
- Strength of the parties' positions based on available information
- Potential settlement opportunities
- Cost-efficiency of different strategic approaches
- UPC-specific procedural peculiarities if applicable (bifurcation, preliminary injunctions, etc.)
Be practical and actionable. Avoid generic advice — tailor recommendations to the specific case data provided.`
// CaseStrategy analyzes a case and returns strategic recommendations.
func (s *AIService) CaseStrategy(ctx context.Context, tenantID, caseID uuid.UUID) (*StrategyRecommendation, error) {
// Load case
var c models.Case
if err := s.db.GetContext(ctx, &c,
"SELECT * FROM cases WHERE id = $1 AND tenant_id = $2", caseID, tenantID); err != nil {
return nil, fmt.Errorf("loading case: %w", err)
}
// Load parties
var parties []models.Party
_ = s.db.SelectContext(ctx, &parties,
"SELECT * FROM parties WHERE case_id = $1 AND tenant_id = $2", caseID, tenantID)
// Load all events
var events []models.CaseEvent
_ = s.db.SelectContext(ctx, &events,
"SELECT * FROM case_events WHERE case_id = $1 AND tenant_id = $2 ORDER BY created_at DESC LIMIT 25",
caseID, tenantID)
// Load all deadlines (active + completed for context)
var deadlines []models.Deadline
_ = s.db.SelectContext(ctx, &deadlines,
"SELECT * FROM deadlines WHERE case_id = $1 AND tenant_id = $2 ORDER BY due_date ASC LIMIT 20",
caseID, tenantID)
// Load documents metadata
var documents []models.Document
_ = s.db.SelectContext(ctx, &documents,
"SELECT id, title, doc_type, created_at FROM documents WHERE case_id = $1 AND tenant_id = $2 ORDER BY created_at DESC LIMIT 15",
caseID, tenantID)
// Build comprehensive context
var b strings.Builder
b.WriteString(fmt.Sprintf("Case: %s — %s\nStatus: %s\n", c.CaseNumber, c.Title, c.Status))
if c.Court != nil {
b.WriteString(fmt.Sprintf("Court: %s\n", *c.Court))
}
if c.CourtRef != nil {
b.WriteString(fmt.Sprintf("Court Reference: %s\n", *c.CourtRef))
}
if c.CaseType != nil {
b.WriteString(fmt.Sprintf("Type: %s\n", *c.CaseType))
}
if len(parties) > 0 {
b.WriteString("\nParties:\n")
for _, p := range parties {
role := "unknown"
if p.Role != nil {
role = *p.Role
}
b.WriteString(fmt.Sprintf("- %s (%s)", p.Name, role))
if p.Representative != nil {
b.WriteString(fmt.Sprintf(" — represented by %s", *p.Representative))
}
b.WriteString("\n")
}
}
if len(events) > 0 {
b.WriteString("\nCase Events (chronological):\n")
for _, e := range events {
b.WriteString(fmt.Sprintf("- [%s] %s", e.CreatedAt.Format("2006-01-02"), e.Title))
if e.Description != nil {
b.WriteString(fmt.Sprintf(": %s", *e.Description))
}
b.WriteString("\n")
}
}
if len(deadlines) > 0 {
b.WriteString("\nDeadlines:\n")
for _, d := range deadlines {
b.WriteString(fmt.Sprintf("- %s: due %s (status: %s)\n", d.Title, d.DueDate, d.Status))
}
}
if len(documents) > 0 {
b.WriteString("\nDocuments on file:\n")
for _, d := range documents {
docType := ""
if d.DocType != nil {
docType = fmt.Sprintf(" [%s]", *d.DocType)
}
b.WriteString(fmt.Sprintf("- %s%s (%s)\n", d.Title, docType, d.CreatedAt.Format("2006-01-02")))
}
}
msg, err := s.client.Messages.New(ctx, anthropic.MessageNewParams{
Model: anthropic.ModelClaudeOpus4_6,
MaxTokens: 4096,
System: []anthropic.TextBlockParam{
{Text: caseStrategySystemPrompt},
},
Messages: []anthropic.MessageParam{
anthropic.NewUserMessage(anthropic.NewTextBlock("Analyze this case and provide strategic recommendations:\n\n" + b.String())),
},
Tools: []anthropic.ToolUnionParam{
{OfTool: &caseStrategyTool},
},
ToolChoice: anthropic.ToolChoiceParamOfTool("case_strategy"),
})
if err != nil {
return nil, fmt.Errorf("claude API call: %w", err)
}
for _, block := range msg.Content {
if block.Type == "tool_use" && block.Name == "case_strategy" {
var input strategyToolInput
if err := json.Unmarshal(block.Input, &input); err != nil {
return nil, fmt.Errorf("parsing strategy output: %w", err)
}
result := &StrategyRecommendation{
Summary: input.Summary,
NextSteps: input.NextSteps,
RiskAssessment: input.RiskAssessment,
Timeline: input.Timeline,
}
// Cache in database
strategyJSON, _ := json.Marshal(result)
_, _ = s.db.ExecContext(ctx,
"UPDATE cases SET ai_summary = $1, updated_at = $2 WHERE id = $3 AND tenant_id = $4",
string(strategyJSON), time.Now(), caseID, tenantID)
return result, nil
}
}
return nil, fmt.Errorf("no tool_use block in response")
}
// --- Similar Case Finder ---
// SimilarCase represents a UPC case found to be similar.
type SimilarCase struct {
CaseNumber string `json:"case_number"`
Title string `json:"title"`
Court string `json:"court"`
Date string `json:"date"`
Relevance float64 `json:"relevance"` // 0.0-1.0
Explanation string `json:"explanation"` // why this case is similar
KeyHoldings string `json:"key_holdings"` // relevant holdings
URL string `json:"url,omitempty"` // link to youpc.org
}
// youpcCase represents a case from the youpc.org database.
type youpcCase struct {
ID string `db:"id" json:"id"`
CaseNumber *string `db:"case_number" json:"case_number"`
Title *string `db:"title" json:"title"`
Court *string `db:"court" json:"court"`
DecisionDate *string `db:"decision_date" json:"decision_date"`
CaseType *string `db:"case_type" json:"case_type"`
Outcome *string `db:"outcome" json:"outcome"`
PatentNumbers *string `db:"patent_numbers" json:"patent_numbers"`
Summary *string `db:"summary" json:"summary"`
Claimant *string `db:"claimant" json:"claimant"`
Defendant *string `db:"defendant" json:"defendant"`
}
type similarCaseToolInput struct {
Cases []struct {
CaseID string `json:"case_id"`
Relevance float64 `json:"relevance"`
Explanation string `json:"explanation"`
KeyHoldings string `json:"key_holdings"`
} `json:"cases"`
}
var similarCaseTool = anthropic.ToolParam{
Name: "rank_similar_cases",
Description: anthropic.String("Rank the provided UPC cases by relevance to the query case and explain why each is similar."),
InputSchema: anthropic.ToolInputSchemaParam{
Properties: map[string]any{
"cases": map[string]any{
"type": "array",
"description": "UPC cases ranked by relevance (most relevant first)",
"items": map[string]any{
"type": "object",
"properties": map[string]any{
"case_id": map[string]any{
"type": "string",
"description": "The ID of the UPC case from the provided list",
},
"relevance": map[string]any{
"type": "number",
"minimum": 0,
"maximum": 1,
"description": "Relevance score from 0.0 to 1.0",
},
"explanation": map[string]any{
"type": "string",
"description": "Why this case is relevant — what legal issues, parties, patents, or procedural aspects are similar",
},
"key_holdings": map[string]any{
"type": "string",
"description": "Key holdings or legal principles from this case that are relevant",
},
},
"required": []string{"case_id", "relevance", "explanation", "key_holdings"},
},
},
},
Required: []string{"cases"},
},
}
const similarCaseSystemPrompt = `You are a UPC (Unified Patent Court) case law expert.
Given a case description and a list of UPC cases from the database, rank the cases by relevance and explain why each one is similar or relevant.
Consider:
- Similar patents or technology areas
- Same parties or representatives
- Similar legal issues (infringement, validity, injunctions, etc.)
- Similar procedural situations
- Relevant legal principles that could apply
Only include cases that are genuinely relevant (relevance > 0.3). Order by relevance descending.`
// FindSimilarCases searches the youpc.org database for similar UPC cases.
func (s *AIService) FindSimilarCases(ctx context.Context, tenantID, caseID uuid.UUID, description string) ([]SimilarCase, error) {
if s.youpcDB == nil {
return nil, fmt.Errorf("youpc.org database not configured")
}
// Build query context from the case (if provided) or description
var queryText string
if caseID != uuid.Nil {
var c models.Case
if err := s.db.GetContext(ctx, &c,
"SELECT * FROM cases WHERE id = $1 AND tenant_id = $2", caseID, tenantID); err != nil {
return nil, fmt.Errorf("loading case: %w", err)
}
var parties []models.Party
_ = s.db.SelectContext(ctx, &parties,
"SELECT * FROM parties WHERE case_id = $1 AND tenant_id = $2", caseID, tenantID)
var b strings.Builder
b.WriteString(fmt.Sprintf("Case: %s — %s\n", c.CaseNumber, c.Title))
if c.CaseType != nil {
b.WriteString(fmt.Sprintf("Type: %s\n", *c.CaseType))
}
if c.Court != nil {
b.WriteString(fmt.Sprintf("Court: %s\n", *c.Court))
}
for _, p := range parties {
role := ""
if p.Role != nil {
role = *p.Role
}
b.WriteString(fmt.Sprintf("Party: %s (%s)\n", p.Name, role))
}
if description != "" {
b.WriteString(fmt.Sprintf("\nAdditional context: %s\n", description))
}
queryText = b.String()
} else if description != "" {
queryText = description
} else {
return nil, fmt.Errorf("either case_id or description must be provided")
}
// Query youpc.org database for candidate cases
// Search by text similarity across case titles, summaries, party names
var candidates []youpcCase
err := s.youpcDB.SelectContext(ctx, &candidates, `
SELECT
id,
case_number,
title,
court,
decision_date,
case_type,
outcome,
patent_numbers,
summary,
claimant,
defendant
FROM mlex.cases
ORDER BY decision_date DESC NULLS LAST
LIMIT 50
`)
if err != nil {
return nil, fmt.Errorf("querying youpc.org cases: %w", err)
}
if len(candidates) == 0 {
return []SimilarCase{}, nil
}
// Build candidate list for Claude
var candidateText strings.Builder
for _, c := range candidates {
candidateText.WriteString(fmt.Sprintf("ID: %s\n", c.ID))
if c.CaseNumber != nil {
candidateText.WriteString(fmt.Sprintf("Case Number: %s\n", *c.CaseNumber))
}
if c.Title != nil {
candidateText.WriteString(fmt.Sprintf("Title: %s\n", *c.Title))
}
if c.Court != nil {
candidateText.WriteString(fmt.Sprintf("Court: %s\n", *c.Court))
}
if c.DecisionDate != nil {
candidateText.WriteString(fmt.Sprintf("Decision Date: %s\n", *c.DecisionDate))
}
if c.CaseType != nil {
candidateText.WriteString(fmt.Sprintf("Type: %s\n", *c.CaseType))
}
if c.Outcome != nil {
candidateText.WriteString(fmt.Sprintf("Outcome: %s\n", *c.Outcome))
}
if c.PatentNumbers != nil {
candidateText.WriteString(fmt.Sprintf("Patents: %s\n", *c.PatentNumbers))
}
if c.Claimant != nil {
candidateText.WriteString(fmt.Sprintf("Claimant: %s\n", *c.Claimant))
}
if c.Defendant != nil {
candidateText.WriteString(fmt.Sprintf("Defendant: %s\n", *c.Defendant))
}
if c.Summary != nil {
candidateText.WriteString(fmt.Sprintf("Summary: %s\n", *c.Summary))
}
candidateText.WriteString("---\n")
}
prompt := fmt.Sprintf(`Find UPC cases relevant to this matter:
%s
Here are the UPC cases from the database to evaluate:
%s
Rank only the genuinely relevant cases by similarity.`, queryText, candidateText.String())
msg, err := s.client.Messages.New(ctx, anthropic.MessageNewParams{
Model: anthropic.ModelClaudeSonnet4_20250514,
MaxTokens: 4096,
System: []anthropic.TextBlockParam{
{Text: similarCaseSystemPrompt},
},
Messages: []anthropic.MessageParam{
anthropic.NewUserMessage(anthropic.NewTextBlock(prompt)),
},
Tools: []anthropic.ToolUnionParam{
{OfTool: &similarCaseTool},
},
ToolChoice: anthropic.ToolChoiceParamOfTool("rank_similar_cases"),
})
if err != nil {
return nil, fmt.Errorf("claude API call: %w", err)
}
for _, block := range msg.Content {
if block.Type == "tool_use" && block.Name == "rank_similar_cases" {
var input similarCaseToolInput
if err := json.Unmarshal(block.Input, &input); err != nil {
return nil, fmt.Errorf("parsing similar cases output: %w", err)
}
// Build lookup map for candidate data
candidateMap := make(map[string]youpcCase)
for _, c := range candidates {
candidateMap[c.ID] = c
}
var results []SimilarCase
for _, ranked := range input.Cases {
if ranked.Relevance < 0.3 {
continue
}
c, ok := candidateMap[ranked.CaseID]
if !ok {
continue
}
sc := SimilarCase{
Relevance: ranked.Relevance,
Explanation: ranked.Explanation,
KeyHoldings: ranked.KeyHoldings,
}
if c.CaseNumber != nil {
sc.CaseNumber = *c.CaseNumber
}
if c.Title != nil {
sc.Title = *c.Title
}
if c.Court != nil {
sc.Court = *c.Court
}
if c.DecisionDate != nil {
sc.Date = *c.DecisionDate
}
if c.CaseNumber != nil {
sc.URL = fmt.Sprintf("https://youpc.org/cases/%s", *c.CaseNumber)
}
results = append(results, sc)
}
return results, nil
}
}
return nil, fmt.Errorf("no tool_use block in response")
}

View File

@@ -8,12 +8,6 @@ import (
"mgit.msbls.de/m/KanzlAI-mGMT/internal/models"
)
const ruleColumns = `id, proceeding_type_id, parent_id, code, name, description,
primary_party, event_type, is_mandatory, duration_value, duration_unit,
timing, rule_code, deadline_notes, sequence_order, condition_rule_id,
alt_duration_value, alt_duration_unit, alt_rule_code,
is_spawn, spawn_label, is_active, created_at, updated_at`
// DeadlineRuleService handles deadline rule queries
type DeadlineRuleService struct {
db *sqlx.DB
@@ -31,13 +25,21 @@ func (s *DeadlineRuleService) List(proceedingTypeID *int) ([]models.DeadlineRule
if proceedingTypeID != nil {
err = s.db.Select(&rules,
`SELECT `+ruleColumns+`
`SELECT id, proceeding_type_id, parent_id, code, name, description,
primary_party, event_type, is_mandatory, duration_value, duration_unit,
timing, rule_code, deadline_notes, sequence_order, condition_rule_id,
alt_duration_value, alt_duration_unit, alt_rule_code, is_active,
created_at, updated_at
FROM deadline_rules
WHERE proceeding_type_id = $1 AND is_active = true
ORDER BY sequence_order`, *proceedingTypeID)
} else {
err = s.db.Select(&rules,
`SELECT `+ruleColumns+`
`SELECT id, proceeding_type_id, parent_id, code, name, description,
primary_party, event_type, is_mandatory, duration_value, duration_unit,
timing, rule_code, deadline_notes, sequence_order, condition_rule_id,
alt_duration_value, alt_duration_unit, alt_rule_code, is_active,
created_at, updated_at
FROM deadline_rules
WHERE is_active = true
ORDER BY proceeding_type_id, sequence_order`)
@@ -70,7 +72,11 @@ func (s *DeadlineRuleService) GetRuleTree(proceedingTypeCode string) ([]RuleTree
// Get all rules for this proceeding type
var rules []models.DeadlineRule
err = s.db.Select(&rules,
`SELECT `+ruleColumns+`
`SELECT id, proceeding_type_id, parent_id, code, name, description,
primary_party, event_type, is_mandatory, duration_value, duration_unit,
timing, rule_code, deadline_notes, sequence_order, condition_rule_id,
alt_duration_value, alt_duration_unit, alt_rule_code, is_active,
created_at, updated_at
FROM deadline_rules
WHERE proceeding_type_id = $1 AND is_active = true
ORDER BY sequence_order`, pt.ID)
@@ -81,36 +87,6 @@ func (s *DeadlineRuleService) GetRuleTree(proceedingTypeCode string) ([]RuleTree
return buildTree(rules), nil
}
// GetFullTimeline returns the full event tree for a proceeding type using a recursive CTE.
// Unlike GetRuleTree, this follows parent_id across proceeding types (includes cross-type spawns).
func (s *DeadlineRuleService) GetFullTimeline(proceedingTypeCode string) ([]models.DeadlineRule, *models.ProceedingType, error) {
var pt models.ProceedingType
err := s.db.Get(&pt,
`SELECT id, code, name, description, jurisdiction, default_color, sort_order, is_active
FROM proceeding_types
WHERE code = $1 AND is_active = true`, proceedingTypeCode)
if err != nil {
return nil, nil, fmt.Errorf("resolving proceeding type %q: %w", proceedingTypeCode, err)
}
var rules []models.DeadlineRule
err = s.db.Select(&rules, `
WITH RECURSIVE tree AS (
SELECT * FROM deadline_rules
WHERE proceeding_type_id = $1 AND parent_id IS NULL AND is_active = true
UNION ALL
SELECT dr.* FROM deadline_rules dr
JOIN tree t ON dr.parent_id = t.id
WHERE dr.is_active = true
)
SELECT `+ruleColumns+` FROM tree ORDER BY sequence_order`, pt.ID)
if err != nil {
return nil, nil, fmt.Errorf("fetching timeline for type %q: %w", proceedingTypeCode, err)
}
return rules, &pt, nil
}
// GetByIDs returns deadline rules by their IDs
func (s *DeadlineRuleService) GetByIDs(ids []string) ([]models.DeadlineRule, error) {
if len(ids) == 0 {
@@ -118,7 +94,11 @@ func (s *DeadlineRuleService) GetByIDs(ids []string) ([]models.DeadlineRule, err
}
query, args, err := sqlx.In(
`SELECT `+ruleColumns+`
`SELECT id, proceeding_type_id, parent_id, code, name, description,
primary_party, event_type, is_mandatory, duration_value, duration_unit,
timing, rule_code, deadline_notes, sequence_order, condition_rule_id,
alt_duration_value, alt_duration_unit, alt_rule_code, is_active,
created_at, updated_at
FROM deadline_rules
WHERE id IN (?) AND is_active = true
ORDER BY sequence_order`, ids)
@@ -139,7 +119,11 @@ func (s *DeadlineRuleService) GetByIDs(ids []string) ([]models.DeadlineRule, err
func (s *DeadlineRuleService) GetRulesForProceedingType(proceedingTypeID int) ([]models.DeadlineRule, error) {
var rules []models.DeadlineRule
err := s.db.Select(&rules,
`SELECT `+ruleColumns+`
`SELECT id, proceeding_type_id, parent_id, code, name, description,
primary_party, event_type, is_mandatory, duration_value, duration_unit,
timing, rule_code, deadline_notes, sequence_order, condition_rule_id,
alt_duration_value, alt_duration_unit, alt_rule_code, is_active,
created_at, updated_at
FROM deadline_rules
WHERE proceeding_type_id = $1 AND is_active = true
ORDER BY sequence_order`, proceedingTypeID)

View File

@@ -1,236 +0,0 @@
package services
import (
"fmt"
"time"
"github.com/jmoiron/sqlx"
"mgit.msbls.de/m/KanzlAI-mGMT/internal/models"
)
// DetermineService handles event-driven deadline determination.
// It walks the proceeding event tree and calculates cascading dates.
type DetermineService struct {
rules *DeadlineRuleService
calculator *DeadlineCalculator
}
// NewDetermineService creates a new determine service
func NewDetermineService(db *sqlx.DB, calculator *DeadlineCalculator) *DetermineService {
return &DetermineService{
rules: NewDeadlineRuleService(db),
calculator: calculator,
}
}
// TimelineEvent represents a calculated event in the proceeding timeline
type TimelineEvent struct {
ID string `json:"id"`
Code string `json:"code,omitempty"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
PrimaryParty string `json:"primary_party,omitempty"`
EventType string `json:"event_type,omitempty"`
IsMandatory bool `json:"is_mandatory"`
DurationValue int `json:"duration_value"`
DurationUnit string `json:"duration_unit"`
RuleCode string `json:"rule_code,omitempty"`
DeadlineNotes string `json:"deadline_notes,omitempty"`
IsSpawn bool `json:"is_spawn"`
SpawnLabel string `json:"spawn_label,omitempty"`
HasCondition bool `json:"has_condition"`
ConditionRuleID string `json:"condition_rule_id,omitempty"`
AltRuleCode string `json:"alt_rule_code,omitempty"`
AltDurationValue *int `json:"alt_duration_value,omitempty"`
AltDurationUnit string `json:"alt_duration_unit,omitempty"`
Date string `json:"date,omitempty"`
OriginalDate string `json:"original_date,omitempty"`
WasAdjusted bool `json:"was_adjusted"`
Children []TimelineEvent `json:"children,omitempty"`
}
// DetermineRequest is the input for POST /api/deadlines/determine
type DetermineRequest struct {
ProceedingType string `json:"proceeding_type"`
TriggerEventDate string `json:"trigger_event_date"`
Conditions map[string]bool `json:"conditions"`
}
// DetermineResponse is the output of the determine endpoint
type DetermineResponse struct {
ProceedingType string `json:"proceeding_type"`
ProceedingName string `json:"proceeding_name"`
ProceedingColor string `json:"proceeding_color"`
TriggerDate string `json:"trigger_event_date"`
Timeline []TimelineEvent `json:"timeline"`
TotalDeadlines int `json:"total_deadlines"`
}
// GetTimeline returns the proceeding event tree (without date calculations)
func (s *DetermineService) GetTimeline(proceedingTypeCode string) ([]TimelineEvent, *models.ProceedingType, error) {
rules, pt, err := s.rules.GetFullTimeline(proceedingTypeCode)
if err != nil {
return nil, nil, err
}
tree := buildTimelineTree(rules)
return tree, pt, nil
}
// Determine calculates the full timeline with cascading dates
func (s *DetermineService) Determine(req DetermineRequest) (*DetermineResponse, error) {
timeline, pt, err := s.GetTimeline(req.ProceedingType)
if err != nil {
return nil, fmt.Errorf("loading timeline: %w", err)
}
triggerDate, err := time.Parse("2006-01-02", req.TriggerEventDate)
if err != nil {
return nil, fmt.Errorf("invalid trigger_event_date: %w", err)
}
conditions := req.Conditions
if conditions == nil {
conditions = make(map[string]bool)
}
total := s.calculateDates(timeline, triggerDate, conditions)
return &DetermineResponse{
ProceedingType: pt.Code,
ProceedingName: pt.Name,
ProceedingColor: pt.DefaultColor,
TriggerDate: req.TriggerEventDate,
Timeline: timeline,
TotalDeadlines: total,
}, nil
}
// calculateDates walks the tree and calculates dates for each node
func (s *DetermineService) calculateDates(events []TimelineEvent, parentDate time.Time, conditions map[string]bool) int {
total := 0
for i := range events {
ev := &events[i]
// Skip inactive spawns: if this is a spawn node and conditions don't include it, skip
if ev.IsSpawn && !conditions[ev.ID] {
continue
}
durationValue := ev.DurationValue
durationUnit := ev.DurationUnit
ruleCode := ev.RuleCode
// Apply conditional logic
if ev.HasCondition && ev.ConditionRuleID != "" {
if conditions[ev.ConditionRuleID] {
if ev.AltDurationValue != nil {
durationValue = *ev.AltDurationValue
}
if ev.AltDurationUnit != "" {
durationUnit = ev.AltDurationUnit
}
if ev.AltRuleCode != "" {
ruleCode = ev.AltRuleCode
}
}
}
// Calculate this node's date
if durationValue > 0 {
rule := models.DeadlineRule{
DurationValue: durationValue,
DurationUnit: durationUnit,
}
adjusted, original, wasAdjusted := s.calculator.CalculateEndDate(parentDate, rule)
ev.Date = adjusted.Format("2006-01-02")
ev.OriginalDate = original.Format("2006-01-02")
ev.WasAdjusted = wasAdjusted
} else {
ev.Date = parentDate.Format("2006-01-02")
ev.OriginalDate = parentDate.Format("2006-01-02")
}
ev.RuleCode = ruleCode
total++
// Recurse: children's dates cascade from this node's date
if len(ev.Children) > 0 {
childDate, _ := time.Parse("2006-01-02", ev.Date)
total += s.calculateDates(ev.Children, childDate, conditions)
}
}
return total
}
// buildTimelineTree converts flat rules to a tree of TimelineEvents
func buildTimelineTree(rules []models.DeadlineRule) []TimelineEvent {
nodeMap := make(map[string]*TimelineEvent, len(rules))
var roots []TimelineEvent
// Create event nodes
for _, r := range rules {
ev := ruleToEvent(r)
nodeMap[r.ID.String()] = &ev
}
// Build tree by parent_id
for _, r := range rules {
ev := nodeMap[r.ID.String()]
if r.ParentID != nil {
parentKey := r.ParentID.String()
if parent, ok := nodeMap[parentKey]; ok {
parent.Children = append(parent.Children, *ev)
continue
}
}
roots = append(roots, *ev)
}
return roots
}
func ruleToEvent(r models.DeadlineRule) TimelineEvent {
ev := TimelineEvent{
ID: r.ID.String(),
Name: r.Name,
IsMandatory: r.IsMandatory,
DurationValue: r.DurationValue,
DurationUnit: r.DurationUnit,
IsSpawn: r.IsSpawn,
HasCondition: r.ConditionRuleID != nil,
}
if r.Code != nil {
ev.Code = *r.Code
}
if r.Description != nil {
ev.Description = *r.Description
}
if r.PrimaryParty != nil {
ev.PrimaryParty = *r.PrimaryParty
}
if r.EventType != nil {
ev.EventType = *r.EventType
}
if r.RuleCode != nil {
ev.RuleCode = *r.RuleCode
}
if r.DeadlineNotes != nil {
ev.DeadlineNotes = *r.DeadlineNotes
}
if r.SpawnLabel != nil {
ev.SpawnLabel = *r.SpawnLabel
}
if r.ConditionRuleID != nil {
ev.ConditionRuleID = r.ConditionRuleID.String()
}
if r.AltRuleCode != nil {
ev.AltRuleCode = *r.AltRuleCode
}
ev.AltDurationValue = r.AltDurationValue
if r.AltDurationUnit != nil {
ev.AltDurationUnit = *r.AltDurationUnit
}
return ev
}

View File

@@ -1,466 +0,0 @@
-- UPC Proceeding Timeline: Full event tree with conditional deadlines
-- Ported from youpc.org migrations 039 + 040
-- Run against kanzlai schema in flexsiebels Supabase instance
-- ========================================
-- 1. Add is_spawn + spawn_label columns
-- ========================================
ALTER TABLE deadline_rules
ADD COLUMN IF NOT EXISTS is_spawn BOOLEAN DEFAULT false,
ADD COLUMN IF NOT EXISTS spawn_label TEXT;
-- ========================================
-- 2. Clear existing UPC rules (fresh seed)
-- ========================================
DELETE FROM deadline_rules WHERE proceeding_type_id IN (
SELECT id FROM proceeding_types WHERE code IN ('INF', 'REV', 'CCR', 'APM', 'APP', 'AMD')
);
-- ========================================
-- 3. Ensure all proceeding types exist
-- ========================================
INSERT INTO proceeding_types (code, name, description, is_active, sort_order, default_color)
VALUES
('INF', 'Infringement', 'Patent infringement proceedings', true, 1, '#3b82f6'),
('REV', 'Revocation', 'Standalone revocation proceedings', true, 2, '#ef4444'),
('CCR', 'Counterclaim for Revocation', 'Counterclaim for revocation within infringement', true, 3, '#ef4444'),
('APM', 'Provisional Measures', 'Application for preliminary injunction', true, 4, '#f59e0b'),
('APP', 'Appeal', 'Appeal to the Court of Appeal', true, 5, '#8b5cf6'),
('AMD', 'Application to Amend Patent', 'Sub-proceeding for patent amendment during revocation', true, 6, '#10b981')
ON CONFLICT (code) DO UPDATE SET
name = EXCLUDED.name,
description = EXCLUDED.description,
default_color = EXCLUDED.default_color,
sort_order = EXCLUDED.sort_order,
is_active = EXCLUDED.is_active;
-- ========================================
-- 4. Seed all proceeding events
-- ========================================
DO $$
DECLARE
v_inf INTEGER;
v_rev INTEGER;
v_ccr INTEGER;
v_apm INTEGER;
v_app INTEGER;
v_amd INTEGER;
-- INF event IDs
v_inf_soc UUID;
v_inf_sod UUID;
v_inf_reply UUID;
v_inf_rejoin UUID;
v_inf_interim UUID;
v_inf_oral UUID;
v_inf_decision UUID;
v_inf_prelim UUID;
-- CCR event IDs
v_ccr_root UUID;
v_ccr_defence UUID;
v_ccr_reply UUID;
v_ccr_rejoin UUID;
v_ccr_interim UUID;
v_ccr_oral UUID;
v_ccr_decision UUID;
-- REV event IDs
v_rev_app UUID;
v_rev_defence UUID;
v_rev_reply UUID;
v_rev_rejoin UUID;
v_rev_interim UUID;
v_rev_oral UUID;
v_rev_decision UUID;
-- PI event IDs
v_pi_app UUID;
v_pi_resp UUID;
v_pi_oral UUID;
-- APP event IDs
v_app_notice UUID;
v_app_grounds UUID;
v_app_response UUID;
v_app_oral UUID;
BEGIN
SELECT id INTO v_inf FROM proceeding_types WHERE code = 'INF';
SELECT id INTO v_rev FROM proceeding_types WHERE code = 'REV';
SELECT id INTO v_ccr FROM proceeding_types WHERE code = 'CCR';
SELECT id INTO v_apm FROM proceeding_types WHERE code = 'APM';
SELECT id INTO v_app FROM proceeding_types WHERE code = 'APP';
SELECT id INTO v_amd FROM proceeding_types WHERE code = 'AMD';
-- ========================================
-- INFRINGEMENT PROCEEDINGS
-- ========================================
-- Root: Statement of Claim
v_inf_soc := gen_random_uuid();
INSERT INTO deadline_rules (id, proceeding_type_id, parent_id, code, name, description,
primary_party, event_type, is_mandatory, duration_value, duration_unit,
rule_code, deadline_notes, is_spawn, spawn_label, sequence_order, is_active)
VALUES (v_inf_soc, v_inf, NULL, 'inf.soc', 'Statement of Claim',
'Claimant files the statement of claim with the Registry',
'claimant', 'filing', true, 0, 'months', NULL, NULL, false, NULL, 0, true);
-- Preliminary Objection (from SoC)
v_inf_prelim := gen_random_uuid();
INSERT INTO deadline_rules (id, proceeding_type_id, parent_id, code, name, description,
primary_party, event_type, is_mandatory, duration_value, duration_unit,
rule_code, deadline_notes, is_spawn, spawn_label, sequence_order, is_active)
VALUES (v_inf_prelim, v_inf, v_inf_soc, 'inf.prelim', 'Preliminary Objection',
'Defendant raises preliminary objection (jurisdiction, admissibility)',
'defendant', 'filing', false, 1, 'months', 'R.19',
'Rarely triggers separate decision; usually decided with main case',
false, NULL, 1, true);
-- Statement of Defence (from SoC)
v_inf_sod := gen_random_uuid();
INSERT INTO deadline_rules (id, proceeding_type_id, parent_id, code, name, description,
primary_party, event_type, is_mandatory, duration_value, duration_unit,
rule_code, deadline_notes, is_spawn, spawn_label, sequence_order, is_active)
VALUES (v_inf_sod, v_inf, v_inf_soc, 'inf.sod', 'Statement of Defence',
'Defendant files the statement of defence',
'defendant', 'filing', true, 3, 'months', 'RoP.023', NULL,
false, NULL, 2, true);
-- Reply to Defence (from SoD) — CONDITIONAL: rule code changes if CCR
v_inf_reply := gen_random_uuid();
INSERT INTO deadline_rules (id, proceeding_type_id, parent_id, code, name, description,
primary_party, event_type, is_mandatory, duration_value, duration_unit,
rule_code, deadline_notes, is_spawn, spawn_label, sequence_order, is_active)
VALUES (v_inf_reply, v_inf, v_inf_sod, 'inf.reply', 'Reply to Defence',
'Claimant''s reply to the statement of defence (includes Defence to Counterclaim if CCR active)',
'claimant', 'filing', true, 2, 'months', 'RoP.029b', NULL,
false, NULL, 1, true);
-- Rejoinder (from Reply) — CONDITIONAL: duration changes if CCR
v_inf_rejoin := gen_random_uuid();
INSERT INTO deadline_rules (id, proceeding_type_id, parent_id, code, name, description,
primary_party, event_type, is_mandatory, duration_value, duration_unit,
rule_code, deadline_notes, is_spawn, spawn_label, sequence_order, is_active)
VALUES (v_inf_rejoin, v_inf, v_inf_reply, 'inf.rejoin', 'Rejoinder',
'Defendant''s rejoinder to the reply',
'defendant', 'filing', true, 1, 'months', 'RoP.029c', NULL,
false, NULL, 0, true);
-- Interim Conference
v_inf_interim := gen_random_uuid();
INSERT INTO deadline_rules (id, proceeding_type_id, parent_id, code, name, description,
primary_party, event_type, is_mandatory, duration_value, duration_unit,
rule_code, deadline_notes, is_spawn, spawn_label, sequence_order, is_active)
VALUES (v_inf_interim, v_inf, v_inf_rejoin, 'inf.interim', 'Interim Conference',
'Interim conference with the judge-rapporteur',
'court', 'hearing', true, 0, 'months', NULL, NULL, false, NULL, 0, true);
-- Oral Hearing
v_inf_oral := gen_random_uuid();
INSERT INTO deadline_rules (id, proceeding_type_id, parent_id, code, name, description,
primary_party, event_type, is_mandatory, duration_value, duration_unit,
rule_code, deadline_notes, is_spawn, spawn_label, sequence_order, is_active)
VALUES (v_inf_oral, v_inf, v_inf_interim, 'inf.oral', 'Oral Hearing',
'Oral hearing before the panel',
'court', 'hearing', true, 0, 'months', NULL, NULL, false, NULL, 0, true);
-- Decision
v_inf_decision := gen_random_uuid();
INSERT INTO deadline_rules (id, proceeding_type_id, parent_id, code, name, description,
primary_party, event_type, is_mandatory, duration_value, duration_unit,
rule_code, deadline_notes, is_spawn, spawn_label, sequence_order, is_active)
VALUES (v_inf_decision, v_inf, v_inf_oral, 'inf.decision', 'Decision',
'Panel delivers its decision',
'court', 'decision', true, 0, 'months', NULL, NULL, false, NULL, 0, true);
-- Appeal (spawn from Decision — cross-type to APP)
INSERT INTO deadline_rules (id, proceeding_type_id, parent_id, code, name, description,
primary_party, event_type, is_mandatory, duration_value, duration_unit,
rule_code, deadline_notes, is_spawn, spawn_label, sequence_order, is_active)
VALUES (gen_random_uuid(), v_app, v_inf_decision, 'inf.appeal', 'Appeal',
'Appeal against infringement decision to Court of Appeal',
'both', 'filing', true, 2, 'months', 'RoP.220.1', NULL,
true, 'Appeal filed', 0, true);
-- ========================================
-- COUNTERCLAIM FOR REVOCATION (spawn from SoD)
-- ========================================
v_ccr_root := gen_random_uuid();
INSERT INTO deadline_rules (id, proceeding_type_id, parent_id, code, name, description,
primary_party, event_type, is_mandatory, duration_value, duration_unit,
rule_code, deadline_notes, is_spawn, spawn_label, sequence_order, is_active)
VALUES (v_ccr_root, v_ccr, v_inf_sod, 'ccr.counterclaim', 'Counterclaim for Revocation',
'Defendant files counterclaim challenging patent validity (included in SoD)',
'defendant', 'filing', true, 0, 'months', NULL, NULL,
true, 'Includes counterclaim for revocation', 0, true);
-- Defence to Counterclaim
v_ccr_defence := gen_random_uuid();
INSERT INTO deadline_rules (id, proceeding_type_id, parent_id, code, name, description,
primary_party, event_type, is_mandatory, duration_value, duration_unit,
rule_code, deadline_notes, is_spawn, spawn_label, sequence_order, is_active)
VALUES (v_ccr_defence, v_ccr, v_ccr_root, 'ccr.defence', 'Defence to Counterclaim',
'Patent proprietor files defence to revocation counterclaim',
'claimant', 'filing', true, 3, 'months', 'RoP.050', NULL,
false, NULL, 0, true);
-- Reply in CCR
v_ccr_reply := gen_random_uuid();
INSERT INTO deadline_rules (id, proceeding_type_id, parent_id, code, name, description,
primary_party, event_type, is_mandatory, duration_value, duration_unit,
rule_code, deadline_notes, is_spawn, spawn_label, sequence_order, is_active)
VALUES (v_ccr_reply, v_ccr, v_ccr_defence, 'ccr.reply', 'Reply in CCR',
'Reply in the counterclaim for revocation',
'defendant', 'filing', true, 2, 'months', NULL,
'Timing overlaps with infringement Rejoinder',
false, NULL, 1, true);
-- Rejoinder in CCR
v_ccr_rejoin := gen_random_uuid();
INSERT INTO deadline_rules (id, proceeding_type_id, parent_id, code, name, description,
primary_party, event_type, is_mandatory, duration_value, duration_unit,
rule_code, deadline_notes, is_spawn, spawn_label, sequence_order, is_active)
VALUES (v_ccr_rejoin, v_ccr, v_ccr_reply, 'ccr.rejoin', 'Rejoinder in CCR',
'Rejoinder in the counterclaim for revocation',
'claimant', 'filing', true, 2, 'months', NULL, NULL,
false, NULL, 0, true);
-- Interim Conference
v_ccr_interim := gen_random_uuid();
INSERT INTO deadline_rules (id, proceeding_type_id, parent_id, code, name, description,
primary_party, event_type, is_mandatory, duration_value, duration_unit,
rule_code, deadline_notes, is_spawn, spawn_label, sequence_order, is_active)
VALUES (v_ccr_interim, v_ccr, v_ccr_rejoin, 'ccr.interim', 'Interim Conference',
'Interim conference covering revocation issues',
'court', 'hearing', true, 0, 'months', NULL,
'May be combined with infringement IC',
false, NULL, 0, true);
-- Oral Hearing
v_ccr_oral := gen_random_uuid();
INSERT INTO deadline_rules (id, proceeding_type_id, parent_id, code, name, description,
primary_party, event_type, is_mandatory, duration_value, duration_unit,
rule_code, deadline_notes, is_spawn, spawn_label, sequence_order, is_active)
VALUES (v_ccr_oral, v_ccr, v_ccr_interim, 'ccr.oral', 'Oral Hearing',
'Oral hearing on validity',
'court', 'hearing', true, 0, 'months', NULL, NULL,
false, NULL, 0, true);
-- Decision
v_ccr_decision := gen_random_uuid();
INSERT INTO deadline_rules (id, proceeding_type_id, parent_id, code, name, description,
primary_party, event_type, is_mandatory, duration_value, duration_unit,
rule_code, deadline_notes, is_spawn, spawn_label, sequence_order, is_active)
VALUES (v_ccr_decision, v_ccr, v_ccr_oral, 'ccr.decision', 'Decision',
'Decision on validity of the patent',
'court', 'decision', true, 0, 'months', NULL, NULL,
false, NULL, 0, true);
-- Appeal from CCR
INSERT INTO deadline_rules (id, proceeding_type_id, parent_id, code, name, description,
primary_party, event_type, is_mandatory, duration_value, duration_unit,
rule_code, deadline_notes, is_spawn, spawn_label, sequence_order, is_active)
VALUES (gen_random_uuid(), v_app, v_ccr_decision, 'ccr.appeal', 'Appeal',
'Appeal against revocation decision to Court of Appeal',
'both', 'filing', true, 2, 'months', 'RoP.220.1', NULL,
true, 'Appeal filed', 0, true);
-- Application to Amend Patent (spawn from Defence to CCR)
INSERT INTO deadline_rules (id, proceeding_type_id, parent_id, code, name, description,
primary_party, event_type, is_mandatory, duration_value, duration_unit,
rule_code, deadline_notes, is_spawn, spawn_label, sequence_order, is_active)
VALUES (gen_random_uuid(), v_amd, v_ccr_defence, 'ccr.amend', 'Application to Amend Patent',
'Patent proprietor applies to amend the patent during revocation proceedings',
'claimant', 'filing', false, 0, 'months', NULL, NULL,
true, 'Includes application to amend patent', 2, true);
-- ========================================
-- STANDALONE REVOCATION
-- ========================================
v_rev_app := gen_random_uuid();
INSERT INTO deadline_rules (id, proceeding_type_id, parent_id, code, name, description,
primary_party, event_type, is_mandatory, duration_value, duration_unit,
rule_code, deadline_notes, is_spawn, spawn_label, sequence_order, is_active)
VALUES (v_rev_app, v_rev, NULL, 'rev.app', 'Application for Revocation',
'Applicant files standalone application for revocation of the patent',
'claimant', 'filing', true, 0, 'months', NULL, NULL,
false, NULL, 0, true);
v_rev_defence := gen_random_uuid();
INSERT INTO deadline_rules (id, proceeding_type_id, parent_id, code, name, description,
primary_party, event_type, is_mandatory, duration_value, duration_unit,
rule_code, deadline_notes, is_spawn, spawn_label, sequence_order, is_active)
VALUES (v_rev_defence, v_rev, v_rev_app, 'rev.defence', 'Defence to Revocation',
'Patent proprietor files defence to revocation application',
'defendant', 'filing', true, 3, 'months', NULL, NULL,
false, NULL, 0, true);
v_rev_reply := gen_random_uuid();
INSERT INTO deadline_rules (id, proceeding_type_id, parent_id, code, name, description,
primary_party, event_type, is_mandatory, duration_value, duration_unit,
rule_code, deadline_notes, is_spawn, spawn_label, sequence_order, is_active)
VALUES (v_rev_reply, v_rev, v_rev_defence, 'rev.reply', 'Reply',
'Reply in standalone revocation proceedings',
'claimant', 'filing', true, 2, 'months', NULL, NULL,
false, NULL, 1, true);
v_rev_rejoin := gen_random_uuid();
INSERT INTO deadline_rules (id, proceeding_type_id, parent_id, code, name, description,
primary_party, event_type, is_mandatory, duration_value, duration_unit,
rule_code, deadline_notes, is_spawn, spawn_label, sequence_order, is_active)
VALUES (v_rev_rejoin, v_rev, v_rev_reply, 'rev.rejoin', 'Rejoinder',
'Rejoinder in standalone revocation proceedings',
'defendant', 'filing', true, 2, 'months', NULL, NULL,
false, NULL, 0, true);
v_rev_interim := gen_random_uuid();
INSERT INTO deadline_rules (id, proceeding_type_id, parent_id, code, name, description,
primary_party, event_type, is_mandatory, duration_value, duration_unit,
rule_code, deadline_notes, is_spawn, spawn_label, sequence_order, is_active)
VALUES (v_rev_interim, v_rev, v_rev_rejoin, 'rev.interim', 'Interim Conference',
'Interim conference with the judge-rapporteur',
'court', 'hearing', true, 0, 'months', NULL, NULL,
false, NULL, 0, true);
v_rev_oral := gen_random_uuid();
INSERT INTO deadline_rules (id, proceeding_type_id, parent_id, code, name, description,
primary_party, event_type, is_mandatory, duration_value, duration_unit,
rule_code, deadline_notes, is_spawn, spawn_label, sequence_order, is_active)
VALUES (v_rev_oral, v_rev, v_rev_interim, 'rev.oral', 'Oral Hearing',
'Oral hearing on validity in standalone revocation',
'court', 'hearing', true, 0, 'months', NULL, NULL,
false, NULL, 0, true);
v_rev_decision := gen_random_uuid();
INSERT INTO deadline_rules (id, proceeding_type_id, parent_id, code, name, description,
primary_party, event_type, is_mandatory, duration_value, duration_unit,
rule_code, deadline_notes, is_spawn, spawn_label, sequence_order, is_active)
VALUES (v_rev_decision, v_rev, v_rev_oral, 'rev.decision', 'Decision',
'Decision on patent validity',
'court', 'decision', true, 0, 'months', NULL, NULL,
false, NULL, 0, true);
-- Appeal from REV
INSERT INTO deadline_rules (id, proceeding_type_id, parent_id, code, name, description,
primary_party, event_type, is_mandatory, duration_value, duration_unit,
rule_code, deadline_notes, is_spawn, spawn_label, sequence_order, is_active)
VALUES (gen_random_uuid(), v_app, v_rev_decision, 'rev.appeal', 'Appeal',
'Appeal against revocation decision to Court of Appeal',
'both', 'filing', true, 2, 'months', 'RoP.220.1', NULL,
true, 'Appeal filed', 0, true);
-- Application to Amend Patent from REV Defence
INSERT INTO deadline_rules (id, proceeding_type_id, parent_id, code, name, description,
primary_party, event_type, is_mandatory, duration_value, duration_unit,
rule_code, deadline_notes, is_spawn, spawn_label, sequence_order, is_active)
VALUES (gen_random_uuid(), v_amd, v_rev_defence, 'rev.amend', 'Application to Amend Patent',
'Patent proprietor applies to amend the patent',
'claimant', 'filing', false, 0, 'months', NULL, NULL,
true, 'Includes application to amend patent', 2, true);
-- ========================================
-- PRELIMINARY INJUNCTION
-- ========================================
v_pi_app := gen_random_uuid();
INSERT INTO deadline_rules (id, proceeding_type_id, parent_id, code, name, description,
primary_party, event_type, is_mandatory, duration_value, duration_unit,
rule_code, deadline_notes, is_spawn, spawn_label, sequence_order, is_active)
VALUES (v_pi_app, v_apm, NULL, 'pi.app', 'Application for Provisional Measures',
'Claimant files application for preliminary injunction',
'claimant', 'filing', true, 0, 'months', NULL, NULL,
false, NULL, 0, true);
v_pi_resp := gen_random_uuid();
INSERT INTO deadline_rules (id, proceeding_type_id, parent_id, code, name, description,
primary_party, event_type, is_mandatory, duration_value, duration_unit,
rule_code, deadline_notes, is_spawn, spawn_label, sequence_order, is_active)
VALUES (v_pi_resp, v_apm, v_pi_app, 'pi.response', 'Response to PI Application',
'Defendant files response to preliminary injunction application',
'defendant', 'filing', true, 0, 'months', NULL,
'Deadline set by court',
false, NULL, 0, true);
v_pi_oral := gen_random_uuid();
INSERT INTO deadline_rules (id, proceeding_type_id, parent_id, code, name, description,
primary_party, event_type, is_mandatory, duration_value, duration_unit,
rule_code, deadline_notes, is_spawn, spawn_label, sequence_order, is_active)
VALUES (v_pi_oral, v_apm, v_pi_resp, 'pi.oral', 'Oral Hearing',
'Oral hearing on provisional measures',
'court', 'hearing', true, 0, 'months', NULL, NULL,
false, NULL, 0, true);
INSERT INTO deadline_rules (id, proceeding_type_id, parent_id, code, name, description,
primary_party, event_type, is_mandatory, duration_value, duration_unit,
rule_code, deadline_notes, is_spawn, spawn_label, sequence_order, is_active)
VALUES (gen_random_uuid(), v_apm, v_pi_oral, 'pi.order', 'Order on Provisional Measures',
'Court issues order on preliminary injunction',
'court', 'decision', true, 0, 'months', NULL, NULL,
false, NULL, 0, true);
-- ========================================
-- APPEAL (standalone)
-- ========================================
v_app_notice := gen_random_uuid();
INSERT INTO deadline_rules (id, proceeding_type_id, parent_id, code, name, description,
primary_party, event_type, is_mandatory, duration_value, duration_unit,
rule_code, deadline_notes, is_spawn, spawn_label, sequence_order, is_active)
VALUES (v_app_notice, v_app, NULL, 'app.notice', 'Notice of Appeal',
'Appellant files notice of appeal with the Court of Appeal',
'both', 'filing', true, 0, 'months', NULL, NULL,
false, NULL, 0, true);
v_app_grounds := gen_random_uuid();
INSERT INTO deadline_rules (id, proceeding_type_id, parent_id, code, name, description,
primary_party, event_type, is_mandatory, duration_value, duration_unit,
rule_code, deadline_notes, is_spawn, spawn_label, sequence_order, is_active)
VALUES (v_app_grounds, v_app, v_app_notice, 'app.grounds', 'Statement of Grounds of Appeal',
'Appellant files statement of grounds',
'both', 'filing', true, 2, 'months', 'RoP.220.1', NULL,
false, NULL, 0, true);
v_app_response := gen_random_uuid();
INSERT INTO deadline_rules (id, proceeding_type_id, parent_id, code, name, description,
primary_party, event_type, is_mandatory, duration_value, duration_unit,
rule_code, deadline_notes, is_spawn, spawn_label, sequence_order, is_active)
VALUES (v_app_response, v_app, v_app_grounds, 'app.response', 'Response to Appeal',
'Respondent files response to the appeal',
'both', 'filing', true, 2, 'months', NULL, NULL,
false, NULL, 0, true);
v_app_oral := gen_random_uuid();
INSERT INTO deadline_rules (id, proceeding_type_id, parent_id, code, name, description,
primary_party, event_type, is_mandatory, duration_value, duration_unit,
rule_code, deadline_notes, is_spawn, spawn_label, sequence_order, is_active)
VALUES (v_app_oral, v_app, v_app_response, 'app.oral', 'Oral Hearing',
'Oral hearing before the Court of Appeal',
'court', 'hearing', true, 0, 'months', NULL, NULL,
false, NULL, 0, true);
INSERT INTO deadline_rules (id, proceeding_type_id, parent_id, code, name, description,
primary_party, event_type, is_mandatory, duration_value, duration_unit,
rule_code, deadline_notes, is_spawn, spawn_label, sequence_order, is_active)
VALUES (gen_random_uuid(), v_app, v_app_oral, 'app.decision', 'Decision',
'Court of Appeal delivers its decision',
'court', 'decision', true, 0, 'months', NULL, NULL,
false, NULL, 0, true);
-- ========================================
-- 5. Set conditional deadlines (from 040)
-- ========================================
-- Reply to Defence: rule code changes when CCR is active
-- Default: RoP.029b | With CCR: RoP.029a
UPDATE deadline_rules
SET condition_rule_id = v_ccr_root,
alt_rule_code = 'RoP.029a'
WHERE id = v_inf_reply;
-- Rejoinder: duration changes when CCR is active
-- Default: 1 month RoP.029c | With CCR: 2 months RoP.029d
UPDATE deadline_rules
SET condition_rule_id = v_ccr_root,
alt_duration_value = 2,
alt_duration_unit = 'months',
alt_rule_code = 'RoP.029d'
WHERE id = v_inf_rejoin;
END $$;

View File

@@ -0,0 +1,51 @@
"use client";
import { useState } from "react";
import { useParams } from "next/navigation";
import { Brain, FileText, Search } from "lucide-react";
import { CaseStrategy } from "@/components/ai/CaseStrategy";
import { DocumentDrafter } from "@/components/ai/DocumentDrafter";
import { SimilarCaseFinder } from "@/components/ai/SimilarCaseFinder";
type AITab = "strategy" | "draft" | "similar";
const TABS: { id: AITab; label: string; icon: typeof Brain }[] = [
{ id: "strategy", label: "KI-Strategie", icon: Brain },
{ id: "draft", label: "KI-Entwurf", icon: FileText },
{ id: "similar", label: "Aehnliche Faelle", icon: Search },
];
export default function CaseAIPage() {
const { id } = useParams<{ id: string }>();
const [activeTab, setActiveTab] = useState<AITab>("strategy");
return (
<div>
{/* Sub-tabs */}
<div className="mb-6 flex gap-1 rounded-lg border border-neutral-200 bg-neutral-50 p-1">
{TABS.map((tab) => {
const isActive = activeTab === tab.id;
return (
<button
key={tab.id}
onClick={() => setActiveTab(tab.id)}
className={`inline-flex flex-1 items-center justify-center gap-1.5 rounded-md px-3 py-2 text-sm font-medium transition-colors ${
isActive
? "bg-white text-neutral-900 shadow-sm"
: "text-neutral-500 hover:text-neutral-700"
}`}
>
<tab.icon className="h-4 w-4" />
{tab.label}
</button>
);
})}
</div>
{/* Content */}
{activeTab === "strategy" && <CaseStrategy caseId={id} />}
{activeTab === "draft" && <DocumentDrafter caseId={id} />}
{activeTab === "similar" && <SimilarCaseFinder caseId={id} />}
</div>
);
}

View File

@@ -17,6 +17,7 @@ import {
StickyNote,
AlertTriangle,
ScrollText,
Brain,
} from "lucide-react";
import { format } from "date-fns";
import { de } from "date-fns/locale";
@@ -48,6 +49,7 @@ const TABS = [
{ segment: "mitarbeiter", label: "Mitarbeiter", icon: UserCheck },
{ segment: "notizen", label: "Notizen", icon: StickyNote },
{ segment: "protokoll", label: "Protokoll", icon: ScrollText },
{ segment: "ki", label: "KI", icon: Brain },
] as const;
const TAB_LABELS: Record<string, string> = {
@@ -58,6 +60,7 @@ const TAB_LABELS: Record<string, string> = {
mitarbeiter: "Mitarbeiter",
notizen: "Notizen",
protokoll: "Protokoll",
ki: "KI",
};
function CaseDetailSkeleton() {

View File

@@ -1,61 +1,28 @@
"use client";
import { DeadlineCalculator } from "@/components/deadlines/DeadlineCalculator";
import { DeadlineWizard } from "@/components/deadlines/DeadlineWizard";
import { ArrowLeft } from "lucide-react";
import Link from "next/link";
import { useState } from "react";
export default function FristenrechnerPage() {
const [mode, setMode] = useState<"wizard" | "quick">("wizard");
return (
<div className="animate-fade-in space-y-4">
<div className="flex items-start justify-between">
<div>
<Link
href="/fristen"
className="mb-2 inline-flex items-center gap-1 text-sm text-neutral-500 transition-colors hover:text-neutral-700"
>
<ArrowLeft className="h-3.5 w-3.5" />
Zurueck zu Fristen
</Link>
<h1 className="text-lg font-semibold text-neutral-900">
Fristenbestimmung
</h1>
<p className="mt-0.5 text-sm text-neutral-500">
{mode === "wizard"
? "Vollstaendige Verfahrens-Timeline mit automatischer Fristenberechnung"
: "Schnellberechnung einzelner Fristen nach Verfahrensart"}
</p>
</div>
{/* Mode toggle */}
<div className="flex rounded-md border border-neutral-200 bg-neutral-50 p-0.5">
<button
onClick={() => setMode("wizard")}
className={`rounded px-3 py-1 text-xs font-medium transition-colors ${
mode === "wizard"
? "bg-white text-neutral-900 shadow-sm"
: "text-neutral-500 hover:text-neutral-700"
}`}
>
Verfahren
</button>
<button
onClick={() => setMode("quick")}
className={`rounded px-3 py-1 text-xs font-medium transition-colors ${
mode === "quick"
? "bg-white text-neutral-900 shadow-sm"
: "text-neutral-500 hover:text-neutral-700"
}`}
>
Schnell
</button>
</div>
<div>
<Link
href="/fristen"
className="mb-2 inline-flex items-center gap-1 text-sm text-neutral-500 transition-colors hover:text-neutral-700"
>
<ArrowLeft className="h-3.5 w-3.5" />
Zurück zu Fristen
</Link>
<h1 className="text-lg font-semibold text-neutral-900">
Fristenrechner
</h1>
<p className="mt-0.5 text-sm text-neutral-500">
Berechnen Sie Fristen basierend auf Verfahrensart und Auslösedatum
</p>
</div>
{mode === "wizard" ? <DeadlineWizard /> : <DeadlineCalculator />}
<DeadlineCalculator />
</div>
);
}

View File

@@ -0,0 +1,226 @@
"use client";
import { useMutation } from "@tanstack/react-query";
import { api } from "@/lib/api";
import type { StrategyRecommendation } from "@/lib/types";
import {
Loader2,
Brain,
AlertTriangle,
ArrowRight,
Shield,
Calendar,
RefreshCw,
} from "lucide-react";
interface CaseStrategyProps {
caseId: string;
}
const PRIORITY_STYLES = {
high: "bg-red-50 text-red-700 border-red-200",
medium: "bg-amber-50 text-amber-700 border-amber-200",
low: "bg-emerald-50 text-emerald-700 border-emerald-200",
} as const;
const IMPORTANCE_STYLES = {
critical: "border-l-red-500",
important: "border-l-amber-500",
routine: "border-l-neutral-300",
} as const;
export function CaseStrategy({ caseId }: CaseStrategyProps) {
const mutation = useMutation({
mutationFn: () =>
api.post<StrategyRecommendation>("/ai/case-strategy", {
case_id: caseId,
}),
});
if (!mutation.data && !mutation.isPending && !mutation.isError) {
return (
<div className="flex flex-col items-center gap-3 py-8 text-center">
<div className="rounded-xl bg-neutral-100 p-3">
<Brain className="h-6 w-6 text-neutral-400" />
</div>
<div>
<p className="text-sm font-medium text-neutral-900">
KI-Strategieanalyse
</p>
<p className="mt-1 text-sm text-neutral-500">
Claude analysiert die Akte und gibt strategische Empfehlungen.
</p>
</div>
<button
onClick={() => mutation.mutate()}
className="inline-flex items-center gap-2 rounded-md bg-neutral-900 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-neutral-800"
>
<Brain className="h-4 w-4" />
Strategie analysieren
</button>
</div>
);
}
if (mutation.isPending) {
return (
<div className="flex flex-col items-center gap-3 py-12 text-center">
<Loader2 className="h-6 w-6 animate-spin text-neutral-400" />
<p className="text-sm text-neutral-500">
Claude analysiert die Akte...
</p>
<p className="text-xs text-neutral-400">
Dies kann bis zu 30 Sekunden dauern.
</p>
</div>
);
}
if (mutation.isError) {
return (
<div className="flex flex-col items-center gap-3 py-8 text-center">
<div className="rounded-xl bg-red-50 p-3">
<AlertTriangle className="h-6 w-6 text-red-500" />
</div>
<p className="text-sm text-neutral-900">Analyse fehlgeschlagen</p>
<button
onClick={() => mutation.mutate()}
className="inline-flex items-center gap-1 text-sm text-neutral-500 transition-colors hover:text-neutral-700"
>
<RefreshCw className="h-3.5 w-3.5" />
Erneut versuchen
</button>
</div>
);
}
const data = mutation.data!;
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<h3 className="text-sm font-semibold text-neutral-900">
KI-Strategieanalyse
</h3>
<button
onClick={() => mutation.mutate()}
className="inline-flex items-center gap-1 rounded-md border border-neutral-200 px-2.5 py-1.5 text-xs font-medium text-neutral-600 transition-colors hover:bg-neutral-50"
>
<RefreshCw className="h-3.5 w-3.5" />
Aktualisieren
</button>
</div>
{/* Summary */}
<div className="rounded-md border border-blue-100 bg-blue-50 px-4 py-3 text-sm text-blue-800">
{data.summary}
</div>
{/* Next Steps */}
{data.next_steps?.length > 0 && (
<div>
<h4 className="mb-2 flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wide text-neutral-500">
<ArrowRight className="h-3.5 w-3.5" />
Naechste Schritte
</h4>
<div className="space-y-2">
{data.next_steps.map((step, i) => (
<div
key={i}
className="rounded-md border border-neutral-200 bg-white px-4 py-3"
>
<div className="flex items-start gap-3">
<span
className={`mt-0.5 inline-block shrink-0 rounded-full border px-2 py-0.5 text-xs font-medium ${PRIORITY_STYLES[step.priority]}`}
>
{step.priority === "high"
? "Hoch"
: step.priority === "medium"
? "Mittel"
: "Niedrig"}
</span>
<div className="min-w-0">
<p className="text-sm font-medium text-neutral-900">
{step.action}
</p>
<p className="mt-1 text-sm text-neutral-500">
{step.reasoning}
</p>
{step.deadline && (
<p className="mt-1 text-xs text-neutral-400">
Frist: {step.deadline}
</p>
)}
</div>
</div>
</div>
))}
</div>
</div>
)}
{/* Risk Assessment */}
{data.risk_assessment?.length > 0 && (
<div>
<h4 className="mb-2 flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wide text-neutral-500">
<Shield className="h-3.5 w-3.5" />
Risikobewertung
</h4>
<div className="space-y-2">
{data.risk_assessment.map((risk, i) => (
<div
key={i}
className="rounded-md border border-neutral-200 bg-white px-4 py-3"
>
<div className="flex items-start gap-3">
<span
className={`mt-0.5 inline-block shrink-0 rounded-full border px-2 py-0.5 text-xs font-medium ${PRIORITY_STYLES[risk.level]}`}
>
{risk.level === "high"
? "Hoch"
: risk.level === "medium"
? "Mittel"
: "Niedrig"}
</span>
<div className="min-w-0">
<p className="text-sm font-medium text-neutral-900">
{risk.risk}
</p>
<p className="mt-1 text-sm text-neutral-500">
Massnahme: {risk.mitigation}
</p>
</div>
</div>
</div>
))}
</div>
</div>
)}
{/* Timeline */}
{data.timeline?.length > 0 && (
<div>
<h4 className="mb-2 flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wide text-neutral-500">
<Calendar className="h-3.5 w-3.5" />
Zeitplan
</h4>
<div className="space-y-1">
{data.timeline.map((item, i) => (
<div
key={i}
className={`border-l-2 py-2 pl-4 ${IMPORTANCE_STYLES[item.importance]}`}
>
<div className="flex items-baseline gap-2">
<span className="shrink-0 text-xs font-medium text-neutral-400">
{item.date}
</span>
<span className="text-sm text-neutral-900">{item.event}</span>
</div>
</div>
))}
</div>
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,198 @@
"use client";
import { useState } from "react";
import { useMutation } from "@tanstack/react-query";
import { api } from "@/lib/api";
import type { DocumentDraft, DraftDocumentRequest } from "@/lib/types";
import { FileText, Loader2, Copy, Check, Download } from "lucide-react";
const TEMPLATES = {
klageschrift: "Klageschrift",
klageerwiderung: "Klageerwiderung",
abmahnung: "Abmahnung",
schriftsatz: "Schriftsatz",
berufung: "Berufungsschrift",
antrag: "Antrag",
stellungnahme: "Stellungnahme",
gutachten: "Gutachten",
vertrag: "Vertrag",
vollmacht: "Vollmacht",
upc_claim: "UPC Statement of Claim",
upc_defence: "UPC Statement of Defence",
upc_counterclaim: "UPC Counterclaim for Revocation",
upc_injunction: "UPC Provisional Measures",
} as const;
const LANGUAGES = [
{ value: "de", label: "Deutsch" },
{ value: "en", label: "English" },
{ value: "fr", label: "Francais" },
] as const;
const inputClass =
"w-full rounded-md border border-neutral-200 bg-white px-3 py-2 text-sm text-neutral-900 outline-none transition-colors focus:border-neutral-400 focus:ring-1 focus:ring-neutral-400";
interface DocumentDrafterProps {
caseId: string;
}
export function DocumentDrafter({ caseId }: DocumentDrafterProps) {
const [templateType, setTemplateType] = useState("");
const [instructions, setInstructions] = useState("");
const [language, setLanguage] = useState("de");
const [copied, setCopied] = useState(false);
const mutation = useMutation({
mutationFn: (req: DraftDocumentRequest) =>
api.post<DocumentDraft>("/ai/draft-document", req),
});
function handleSubmit(e: React.FormEvent) {
e.preventDefault();
if (!templateType) return;
mutation.mutate({
case_id: caseId,
template_type: templateType,
instructions,
language,
});
}
function handleCopy() {
if (mutation.data?.content) {
navigator.clipboard.writeText(mutation.data.content);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
}
}
function handleDownload() {
if (!mutation.data?.content) return;
const blob = new Blob([mutation.data.content], { type: "text/plain;charset=utf-8" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = `${templateType}_entwurf.txt`;
a.click();
URL.revokeObjectURL(url);
}
return (
<div className="space-y-4">
<form onSubmit={handleSubmit} className="space-y-3">
<div>
<label className="mb-1 block text-xs font-medium text-neutral-500">
Dokumenttyp
</label>
<select
value={templateType}
onChange={(e) => setTemplateType(e.target.value)}
className={inputClass}
disabled={mutation.isPending}
>
<option value="">Dokumenttyp waehlen...</option>
{Object.entries(TEMPLATES).map(([key, label]) => (
<option key={key} value={key}>
{label}
</option>
))}
</select>
</div>
<div>
<label className="mb-1 block text-xs font-medium text-neutral-500">
Sprache
</label>
<select
value={language}
onChange={(e) => setLanguage(e.target.value)}
className={inputClass}
disabled={mutation.isPending}
>
{LANGUAGES.map((lang) => (
<option key={lang.value} value={lang.value}>
{lang.label}
</option>
))}
</select>
</div>
<div>
<label className="mb-1 block text-xs font-medium text-neutral-500">
Anweisungen (optional)
</label>
<textarea
value={instructions}
onChange={(e) => setInstructions(e.target.value)}
placeholder="z.B. 'Fokus auf Patentanspruch 1, besonders die technischen Merkmale...'"
rows={3}
className={inputClass}
disabled={mutation.isPending}
/>
</div>
<button
type="submit"
disabled={!templateType || mutation.isPending}
className="inline-flex items-center gap-2 rounded-md bg-neutral-900 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-neutral-800 disabled:opacity-50"
>
{mutation.isPending ? (
<>
<Loader2 className="h-4 w-4 animate-spin" />
Dokument wird erstellt...
</>
) : (
<>
<FileText className="h-4 w-4" />
KI-Entwurf erstellen
</>
)}
</button>
</form>
{mutation.isError && (
<div className="rounded-md border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
Fehler beim Erstellen des Entwurfs. Bitte versuchen Sie es erneut.
</div>
)}
{mutation.data && (
<div className="space-y-3">
<div className="flex items-center justify-between">
<h4 className="text-sm font-medium text-neutral-900">
{mutation.data.title}
</h4>
<div className="flex items-center gap-2">
<button
onClick={handleCopy}
className="inline-flex items-center gap-1 rounded-md border border-neutral-200 px-2.5 py-1.5 text-xs font-medium text-neutral-600 transition-colors hover:bg-neutral-50"
>
{copied ? (
<>
<Check className="h-3.5 w-3.5 text-emerald-500" />
Kopiert
</>
) : (
<>
<Copy className="h-3.5 w-3.5" />
Kopieren
</>
)}
</button>
<button
onClick={handleDownload}
className="inline-flex items-center gap-1 rounded-md border border-neutral-200 px-2.5 py-1.5 text-xs font-medium text-neutral-600 transition-colors hover:bg-neutral-50"
>
<Download className="h-3.5 w-3.5" />
Download
</button>
</div>
</div>
<pre className="max-h-[600px] overflow-auto whitespace-pre-wrap rounded-md border border-neutral-200 bg-neutral-50 p-4 text-sm text-neutral-800">
{mutation.data.content}
</pre>
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,183 @@
"use client";
import { useState } from "react";
import { useMutation } from "@tanstack/react-query";
import { api } from "@/lib/api";
import type { SimilarCasesResponse } from "@/lib/types";
import {
Loader2,
Search,
ExternalLink,
AlertTriangle,
Scale,
RefreshCw,
} from "lucide-react";
interface SimilarCaseFinderProps {
caseId: string;
}
const inputClass =
"w-full rounded-md border border-neutral-200 bg-white px-3 py-2 text-sm text-neutral-900 outline-none transition-colors focus:border-neutral-400 focus:ring-1 focus:ring-neutral-400";
function RelevanceBadge({ score }: { score: number }) {
const pct = Math.round(score * 100);
let color = "bg-neutral-100 text-neutral-600";
if (pct >= 80) color = "bg-emerald-50 text-emerald-700";
else if (pct >= 60) color = "bg-blue-50 text-blue-700";
else if (pct >= 40) color = "bg-amber-50 text-amber-700";
return (
<span
className={`inline-block shrink-0 rounded-full px-2 py-0.5 text-xs font-medium ${color}`}
>
{pct}%
</span>
);
}
export function SimilarCaseFinder({ caseId }: SimilarCaseFinderProps) {
const [description, setDescription] = useState("");
const mutation = useMutation({
mutationFn: (req: { case_id: string; description: string }) =>
api.post<SimilarCasesResponse>("/ai/similar-cases", req),
});
function handleSearch(e?: React.FormEvent) {
e?.preventDefault();
mutation.mutate({ case_id: caseId, description });
}
return (
<div className="space-y-4">
<form onSubmit={handleSearch} className="space-y-3">
<div>
<label className="mb-1 block text-xs font-medium text-neutral-500">
Zusaetzliche Beschreibung (optional)
</label>
<textarea
value={description}
onChange={(e) => setDescription(e.target.value)}
placeholder="z.B. 'SEP-Lizenzierung im Mobilfunkbereich, FRAND-Verteidigung...'"
rows={2}
className={inputClass}
disabled={mutation.isPending}
/>
</div>
<button
type="submit"
disabled={mutation.isPending}
className="inline-flex items-center gap-2 rounded-md bg-neutral-900 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-neutral-800 disabled:opacity-50"
>
{mutation.isPending ? (
<>
<Loader2 className="h-4 w-4 animate-spin" />
Suche laeuft...
</>
) : (
<>
<Search className="h-4 w-4" />
Aehnliche Faelle suchen
</>
)}
</button>
</form>
{mutation.isError && (
<div className="flex flex-col items-center gap-3 py-6 text-center">
<div className="rounded-xl bg-red-50 p-3">
<AlertTriangle className="h-6 w-6 text-red-500" />
</div>
<p className="text-sm text-neutral-900">Suche fehlgeschlagen</p>
<p className="text-xs text-neutral-500">
Die youpc.org-Datenbank ist moeglicherweise nicht verfuegbar.
</p>
<button
onClick={() => handleSearch()}
className="inline-flex items-center gap-1 text-sm text-neutral-500 transition-colors hover:text-neutral-700"
>
<RefreshCw className="h-3.5 w-3.5" />
Erneut versuchen
</button>
</div>
)}
{mutation.data && (
<div className="space-y-3">
<div className="flex items-center justify-between">
<p className="text-xs text-neutral-500">
{mutation.data.count} aehnliche{" "}
{mutation.data.count === 1 ? "Fall" : "Faelle"} gefunden
</p>
<button
onClick={() => handleSearch()}
disabled={mutation.isPending}
className="inline-flex items-center gap-1 rounded-md border border-neutral-200 px-2.5 py-1.5 text-xs font-medium text-neutral-600 transition-colors hover:bg-neutral-50"
>
<RefreshCw className="h-3.5 w-3.5" />
Aktualisieren
</button>
</div>
{mutation.data.cases?.length === 0 && (
<div className="flex flex-col items-center gap-2 py-6 text-center">
<Scale className="h-6 w-6 text-neutral-300" />
<p className="text-sm text-neutral-500">
Keine aehnlichen UPC-Faelle gefunden.
</p>
</div>
)}
{mutation.data.cases?.map((c, i) => (
<div
key={i}
className="rounded-md border border-neutral-200 bg-white px-4 py-3"
>
<div className="flex items-start justify-between gap-3">
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<RelevanceBadge score={c.relevance} />
<span className="text-xs font-medium text-neutral-400">
{c.case_number}
</span>
{c.url && (
<a
href={c.url}
target="_blank"
rel="noopener noreferrer"
className="text-neutral-400 transition-colors hover:text-neutral-600"
>
<ExternalLink className="h-3.5 w-3.5" />
</a>
)}
</div>
<p className="mt-1 text-sm font-medium text-neutral-900">
{c.title}
</p>
<div className="mt-1 flex flex-wrap gap-x-3 text-xs text-neutral-400">
{c.court && <span>{c.court}</span>}
{c.date && <span>{c.date}</span>}
</div>
</div>
</div>
<p className="mt-2 text-sm text-neutral-600">{c.explanation}</p>
{c.key_holdings && (
<div className="mt-2 rounded border border-neutral-100 bg-neutral-50 px-3 py-2">
<p className="text-xs font-medium text-neutral-500">
Relevante Entscheidungsgruende
</p>
<p className="mt-0.5 text-xs text-neutral-600">
{c.key_holdings}
</p>
</div>
)}
</div>
))}
</div>
)}
</div>
);
}

View File

@@ -1,622 +0,0 @@
"use client";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { api } from "@/lib/api";
import type {
ProceedingType,
TimelineResponse,
DetermineResponse,
TimelineEvent,
Case,
} from "@/lib/types";
import { format, parseISO, isPast, isThisWeek, isBefore, addDays } from "date-fns";
import { de } from "date-fns/locale";
import {
Scale,
Calendar,
ChevronRight,
ChevronDown,
GitBranch,
Check,
Clock,
AlertTriangle,
FileText,
Users,
Gavel,
ArrowRight,
RotateCcw,
Loader2,
CheckCircle2,
FolderOpen,
} from "lucide-react";
import { useState, useCallback, useMemo } from "react";
import { toast } from "sonner";
// --- Helpers ---
function formatDuration(value: number, unit: string): string {
if (value === 0) return "";
const labels: Record<string, string> = {
days: value === 1 ? "Tag" : "Tage",
weeks: value === 1 ? "Woche" : "Wochen",
months: value === 1 ? "Monat" : "Monate",
};
return `${value} ${labels[unit] || unit}`;
}
function getPartyIcon(party?: string) {
switch (party) {
case "claimant":
return <Scale className="h-3.5 w-3.5" />;
case "defendant":
return <Users className="h-3.5 w-3.5" />;
case "court":
return <Gavel className="h-3.5 w-3.5" />;
default:
return <FileText className="h-3.5 w-3.5" />;
}
}
function getPartyLabel(party?: string): string {
switch (party) {
case "claimant":
return "Klaeger";
case "defendant":
return "Beklagter";
case "court":
return "Gericht";
case "both":
return "Beide Parteien";
default:
return "";
}
}
function getEventTypeLabel(type?: string): string {
switch (type) {
case "filing":
return "Einreichung";
case "hearing":
return "Verhandlung";
case "decision":
return "Entscheidung";
default:
return "";
}
}
type Urgency = "past" | "overdue" | "this_week" | "upcoming" | "future" | "none";
function getUrgency(dateStr?: string): Urgency {
if (!dateStr) return "none";
const date = parseISO(dateStr);
const today = new Date();
today.setHours(0, 0, 0, 0);
if (isPast(date) && isBefore(date, today)) return "overdue";
if (isThisWeek(date, { weekStartsOn: 1 })) return "this_week";
if (isBefore(date, addDays(today, 30))) return "upcoming";
return "future";
}
const urgencyStyles: Record<Urgency, { dot: string; text: string; bg: string }> = {
past: { dot: "bg-neutral-400", text: "text-neutral-500", bg: "bg-neutral-50" },
overdue: { dot: "bg-red-500", text: "text-red-700", bg: "bg-red-50" },
this_week: { dot: "bg-amber-500", text: "text-amber-700", bg: "bg-amber-50" },
upcoming: { dot: "bg-blue-500", text: "text-blue-700", bg: "bg-blue-50" },
future: { dot: "bg-green-500", text: "text-green-700", bg: "bg-green-50" },
none: { dot: "bg-neutral-300", text: "text-neutral-500", bg: "bg-neutral-50" },
};
// --- Spawn Extraction ---
function extractSpawns(events: TimelineEvent[]): TimelineEvent[] {
const spawns: TimelineEvent[] = [];
function walk(evts: TimelineEvent[]) {
for (const ev of evts) {
if (ev.is_spawn) spawns.push(ev);
if (ev.children) walk(ev.children);
}
}
walk(events);
return spawns;
}
// --- Flat timeline extraction ---
function flattenTimeline(events: TimelineEvent[], depth = 0): (TimelineEvent & { depth: number })[] {
const result: (TimelineEvent & { depth: number })[] = [];
for (const ev of events) {
result.push({ ...ev, depth });
if (ev.children && ev.children.length > 0) {
result.push(...flattenTimeline(ev.children, depth + 1));
}
}
return result;
}
// --- Main Component ---
export function DeadlineWizard() {
const [selectedType, setSelectedType] = useState<string>("");
const [triggerDate, setTriggerDate] = useState("");
const [conditions, setConditions] = useState<Record<string, boolean>>({});
const [selectedCaseId, setSelectedCaseId] = useState<string>("");
const [showBatchPanel, setShowBatchPanel] = useState(false);
const queryClient = useQueryClient();
// Fetch proceeding types
const { data: proceedingTypes, isLoading: typesLoading } = useQuery({
queryKey: ["proceeding-types"],
queryFn: () => api.get<ProceedingType[]>("/proceeding-types"),
});
// Fetch timeline structure when type is selected
const { data: timelineData } = useQuery({
queryKey: ["timeline", selectedType],
queryFn: () => api.get<TimelineResponse>(`/proceeding-types/${selectedType}/timeline`),
enabled: !!selectedType,
});
// Determine mutation
const determineMutation = useMutation({
mutationFn: (params: { proceeding_type: string; trigger_event_date: string; conditions: Record<string, boolean> }) =>
api.post<DetermineResponse>("/deadlines/determine", params),
});
// Cases for batch create
const { data: cases } = useQuery({
queryKey: ["cases"],
queryFn: () => api.get<Case[]>("/cases"),
enabled: showBatchPanel,
});
// Batch create mutation
const batchMutation = useMutation({
mutationFn: (params: { caseId: string; deadlines: { title: string; due_date: string; rule_code?: string }[] }) =>
api.post(`/cases/${params.caseId}/deadlines/batch`, { deadlines: params.deadlines }),
onSuccess: () => {
toast.success("Alle Fristen wurden auf die Akte uebernommen");
queryClient.invalidateQueries({ queryKey: ["deadlines"] });
setShowBatchPanel(false);
},
onError: () => {
toast.error("Fehler beim Erstellen der Fristen");
},
});
// Spawns from timeline structure (for condition toggles)
const spawns = useMemo(() => {
if (!timelineData?.timeline) return [];
return extractSpawns(timelineData.timeline);
}, [timelineData]);
// Calculate on type/date/condition change
const calculate = useCallback(() => {
if (!selectedType || !triggerDate) return;
determineMutation.mutate({
proceeding_type: selectedType,
trigger_event_date: triggerDate,
conditions,
});
}, [selectedType, triggerDate, conditions, determineMutation]);
// Auto-calculate when date or conditions change
const handleDateChange = (date: string) => {
setTriggerDate(date);
if (selectedType && date) {
determineMutation.mutate({
proceeding_type: selectedType,
trigger_event_date: date,
conditions,
});
}
};
const handleConditionToggle = (spawnId: string) => {
const next = { ...conditions, [spawnId]: !conditions[spawnId] };
setConditions(next);
if (selectedType && triggerDate) {
determineMutation.mutate({
proceeding_type: selectedType,
trigger_event_date: triggerDate,
conditions: next,
});
}
};
const handleTypeSelect = (code: string) => {
setSelectedType(code);
setConditions({});
if (triggerDate) {
// Will recalculate once timeline loads
determineMutation.reset();
}
};
const handleReset = () => {
setSelectedType("");
setTriggerDate("");
setConditions({});
setShowBatchPanel(false);
determineMutation.reset();
};
// Collect calculated deadlines for batch create
const collectDeadlines = (events: TimelineEvent[]): { title: string; due_date: string; rule_code?: string }[] => {
const result: { title: string; due_date: string; rule_code?: string }[] = [];
for (const ev of events) {
if (ev.date && ev.duration_value > 0) {
result.push({ title: ev.name, due_date: ev.date, rule_code: ev.rule_code || undefined });
}
if (ev.children) result.push(...collectDeadlines(ev.children));
}
return result;
};
const results = determineMutation.data;
const selectedPT = proceedingTypes?.find((pt) => pt.code === selectedType);
return (
<div className="space-y-5">
{/* Step 1: Proceeding Type Selection */}
<div className="rounded-lg border border-neutral-200 bg-white p-5">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2 text-sm font-medium text-neutral-900">
<Scale className="h-4 w-4" />
Verfahrensart waehlen
</div>
{selectedType && (
<button
onClick={handleReset}
className="flex items-center gap-1 text-xs text-neutral-500 hover:text-neutral-700"
>
<RotateCcw className="h-3 w-3" />
Zuruecksetzen
</button>
)}
</div>
<div className="mt-4 grid grid-cols-2 gap-2 sm:grid-cols-3 lg:grid-cols-6">
{typesLoading ? (
<div className="col-span-full flex justify-center py-4">
<Loader2 className="h-5 w-5 animate-spin text-neutral-400" />
</div>
) : (
proceedingTypes?.map((pt) => (
<button
key={pt.id}
onClick={() => handleTypeSelect(pt.code)}
className={`rounded-lg border px-3 py-2.5 text-left transition-all ${
selectedType === pt.code
? "border-neutral-900 bg-neutral-900 text-white shadow-sm"
: "border-neutral-200 bg-white text-neutral-700 hover:border-neutral-400 hover:bg-neutral-50"
}`}
>
<div className="flex items-center gap-1.5">
<div
className="h-2 w-2 rounded-full"
style={{ backgroundColor: pt.default_color }}
/>
<span className="text-xs font-semibold">{pt.code}</span>
</div>
<div className="mt-1 text-xs leading-tight opacity-80">{pt.name}</div>
</button>
))
)}
</div>
</div>
{/* Step 2: Date + Conditions */}
{selectedType && (
<div className="animate-fade-in rounded-lg border border-neutral-200 bg-white p-5">
<div className="flex items-center gap-2 text-sm font-medium text-neutral-900">
<Calendar className="h-4 w-4" />
Ausloesendes Ereignis
</div>
<div className="mt-4 flex flex-col gap-4 sm:flex-row sm:items-end">
<div className="flex-1">
<label className="mb-1 block text-xs font-medium text-neutral-500">
Datum des {selectedPT?.name || selectedType} (z.B. Klagezustellung)
</label>
<input
type="date"
value={triggerDate}
onChange={(e) => handleDateChange(e.target.value)}
className="w-full rounded-md border border-neutral-200 bg-white px-3 py-2 text-sm text-neutral-900 outline-none transition-colors focus:border-neutral-400 focus:ring-1 focus:ring-neutral-400"
/>
</div>
{/* Condition toggles */}
{spawns.length > 0 && (
<div className="flex flex-wrap gap-2">
{spawns.map((spawn) => (
<button
key={spawn.id}
onClick={() => handleConditionToggle(spawn.id)}
className={`flex items-center gap-1.5 rounded-full px-3 py-1.5 text-xs font-medium transition-all ${
conditions[spawn.id]
? "bg-neutral-900 text-white"
: "border border-neutral-300 bg-white text-neutral-600 hover:bg-neutral-50"
}`}
>
<GitBranch className="h-3 w-3" />
{spawn.spawn_label || spawn.name}
{conditions[spawn.id] && <Check className="h-3 w-3" />}
</button>
))}
</div>
)}
</div>
</div>
)}
{/* Error */}
{determineMutation.isError && (
<div className="flex items-center gap-2 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
<AlertTriangle className="h-4 w-4 shrink-0" />
Fehler bei der Berechnung. Bitte Eingaben pruefen.
</div>
)}
{/* Step 3: Calculated Timeline */}
{results && results.timeline && (
<div className="animate-fade-in space-y-3">
{/* Header */}
<div className="flex items-center justify-between">
<div>
<h3 className="text-sm font-medium text-neutral-900">
Verfahrens-Timeline: {results.proceeding_name}
</h3>
<p className="mt-0.5 text-xs text-neutral-500">
{results.total_deadlines} Ereignisse ab{" "}
{format(parseISO(results.trigger_event_date), "dd. MMMM yyyy", { locale: de })}
</p>
</div>
<button
onClick={() => setShowBatchPanel(!showBatchPanel)}
className="flex items-center gap-1.5 rounded-md bg-neutral-900 px-3 py-1.5 text-xs font-medium text-white transition-colors hover:bg-neutral-800"
>
<CheckCircle2 className="h-3.5 w-3.5" />
Alle uebernehmen
</button>
</div>
{/* Timeline visualization */}
<div className="rounded-lg border border-neutral-200 bg-white">
<TimelineTree events={results.timeline} conditions={conditions} depth={0} />
</div>
{/* Batch create panel */}
{showBatchPanel && (
<div className="animate-fade-in rounded-lg border border-neutral-200 bg-neutral-50 p-4">
<div className="flex items-center gap-2 text-sm font-medium text-neutral-900">
<FolderOpen className="h-4 w-4" />
Fristen auf Akte uebernehmen
</div>
<div className="mt-3 flex gap-3">
<select
value={selectedCaseId}
onChange={(e) => setSelectedCaseId(e.target.value)}
className="flex-1 rounded-md border border-neutral-200 bg-white px-3 py-2 text-sm text-neutral-900 outline-none focus:border-neutral-400"
>
<option value="">Akte waehlen...</option>
{cases
?.filter((c) => c.status !== "closed")
.map((c) => (
<option key={c.id} value={c.id}>
{c.case_number} {c.title}
</option>
))}
</select>
<button
disabled={!selectedCaseId || batchMutation.isPending}
onClick={() => {
const deadlines = collectDeadlines(results.timeline);
if (deadlines.length === 0) return;
batchMutation.mutate({ caseId: selectedCaseId, deadlines });
}}
className="flex items-center gap-1.5 rounded-md bg-neutral-900 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-neutral-800 disabled:cursor-not-allowed disabled:opacity-50"
>
{batchMutation.isPending ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<ArrowRight className="h-3.5 w-3.5" />
)}
{batchMutation.isPending ? "Erstelle..." : `${collectDeadlines(results.timeline).length} Fristen erstellen`}
</button>
</div>
</div>
)}
</div>
)}
{/* Empty state */}
{!results && !determineMutation.isPending && selectedType && triggerDate && (
<div className="flex items-center justify-center py-8">
<Loader2 className="h-5 w-5 animate-spin text-neutral-400" />
</div>
)}
{!selectedType && (
<div className="flex flex-col items-center rounded-lg border border-dashed border-neutral-300 bg-white px-6 py-12 text-center">
<div className="rounded-xl bg-neutral-100 p-3">
<Scale className="h-6 w-6 text-neutral-400" />
</div>
<p className="mt-3 text-sm font-medium text-neutral-700">
UPC-Fristenbestimmung
</p>
<p className="mt-1 max-w-sm text-xs text-neutral-500">
Waehlen Sie die Verfahrensart und geben Sie das Datum des ausloesenden Ereignisses ein.
Alle Fristen des Verfahrens werden automatisch berechnet.
</p>
</div>
)}
</div>
);
}
// --- Timeline Tree Component ---
function TimelineTree({
events,
conditions,
depth,
}: {
events: TimelineEvent[];
conditions: Record<string, boolean>;
depth: number;
}) {
return (
<>
{events.map((ev, i) => (
<TimelineNode
key={ev.id}
event={ev}
conditions={conditions}
depth={depth}
isLast={i === events.length - 1}
/>
))}
</>
);
}
function TimelineNode({
event: ev,
conditions,
depth,
isLast,
}: {
event: TimelineEvent;
conditions: Record<string, boolean>;
depth: number;
isLast: boolean;
}) {
const [expanded, setExpanded] = useState(true);
// Skip inactive spawns
if (ev.is_spawn && !conditions[ev.id]) return null;
const hasChildren = ev.children && ev.children.length > 0;
const visibleChildren = ev.children?.filter(
(c) => !c.is_spawn || conditions[c.id]
);
const hasVisibleChildren = visibleChildren && visibleChildren.length > 0;
const urgency = getUrgency(ev.date);
const styles = urgencyStyles[urgency];
const duration = formatDuration(ev.duration_value, ev.duration_unit);
const isConditional = ev.has_condition && ev.condition_rule_id;
return (
<>
<div
className={`group relative flex gap-3 px-4 py-3 transition-colors hover:bg-neutral-50 ${
!isLast && depth === 0 ? "border-b border-neutral-100" : ""
}`}
style={{ paddingLeft: `${16 + depth * 24}px` }}
>
{/* Timeline connector */}
<div className="flex flex-col items-center pt-1">
<div className={`h-3 w-3 shrink-0 rounded-full border-2 border-white shadow-sm ${styles.dot}`} />
{!isLast && <div className="mt-1 w-px flex-1 bg-neutral-200" />}
</div>
{/* Content */}
<div className="min-w-0 flex-1">
<div className="flex flex-col gap-1 sm:flex-row sm:items-start sm:justify-between sm:gap-2">
<div className="flex items-center gap-1.5">
{hasVisibleChildren && (
<button
onClick={() => setExpanded(!expanded)}
className="text-neutral-400 hover:text-neutral-600"
>
{expanded ? (
<ChevronDown className="h-3.5 w-3.5" />
) : (
<ChevronRight className="h-3.5 w-3.5" />
)}
</button>
)}
{ev.is_spawn && (
<GitBranch className="h-3.5 w-3.5 text-violet-500" />
)}
<span className="text-sm font-medium text-neutral-900">{ev.name}</span>
{!ev.is_mandatory && (
<span className="rounded bg-neutral-100 px-1 py-0.5 text-[10px] text-neutral-500">
optional
</span>
)}
</div>
{/* Date */}
{ev.date && (
<div className="flex items-center gap-1.5 shrink-0">
{ev.was_adjusted && (
<span className="text-[10px] text-amber-600" title={`Original: ${ev.original_date}`}>
angepasst
</span>
)}
<span className={`text-sm font-medium tabular-nums ${styles.text}`}>
{format(parseISO(ev.date), "dd.MM.yyyy")}
</span>
</div>
)}
</div>
{/* Meta row */}
<div className="mt-0.5 flex flex-wrap items-center gap-x-2 gap-y-0.5 text-xs text-neutral-500">
{ev.primary_party && (
<span className="flex items-center gap-0.5">
{getPartyIcon(ev.primary_party)}
{getPartyLabel(ev.primary_party)}
</span>
)}
{ev.event_type && (
<>
<span className="text-neutral-300">·</span>
<span>{getEventTypeLabel(ev.event_type)}</span>
</>
)}
{duration && (
<>
<span className="text-neutral-300">·</span>
<span className="flex items-center gap-0.5">
<Clock className="h-3 w-3" />
{duration}
</span>
</>
)}
{ev.rule_code && (
<>
<span className="text-neutral-300">·</span>
<span className="rounded bg-neutral-100 px-1 py-0.5 font-mono text-[10px]">
{ev.rule_code}
</span>
</>
)}
{isConditional && (
<>
<span className="text-neutral-300">·</span>
<span className="text-violet-600">
bedingt{ev.alt_rule_code ? ` (${ev.alt_rule_code})` : ""}
</span>
</>
)}
</div>
{/* Notes */}
{ev.deadline_notes && (
<p className="mt-1 text-xs text-neutral-400 italic">{ev.deadline_notes}</p>
)}
</div>
</div>
{/* Children */}
{expanded && hasVisibleChildren && (
<TimelineTree events={visibleChildren!} conditions={conditions} depth={depth + 1} />
)}
</>
);
}

View File

@@ -120,76 +120,12 @@ export interface DeadlineRule {
rule_code?: string;
deadline_notes?: string;
sequence_order: number;
condition_rule_id?: string;
alt_duration_value?: number;
alt_duration_unit?: string;
alt_rule_code?: string;
is_spawn?: boolean;
spawn_label?: string;
}
export interface RuleTreeNode extends DeadlineRule {
children?: RuleTreeNode[];
}
// Timeline determination types
export interface TimelineEvent {
id: string;
code?: string;
name: string;
description?: string;
primary_party?: string;
event_type?: string;
is_mandatory: boolean;
duration_value: number;
duration_unit: string;
rule_code?: string;
deadline_notes?: string;
is_spawn: boolean;
spawn_label?: string;
has_condition: boolean;
condition_rule_id?: string;
alt_rule_code?: string;
alt_duration_value?: number;
alt_duration_unit?: string;
date?: string;
original_date?: string;
was_adjusted: boolean;
children?: TimelineEvent[];
}
export interface TimelineResponse {
proceeding_type: ProceedingType;
timeline: TimelineEvent[];
}
export interface DetermineRequest {
proceeding_type: string;
trigger_event_date: string;
conditions: Record<string, boolean>;
}
export interface DetermineResponse {
proceeding_type: string;
proceeding_name: string;
proceeding_color: string;
trigger_event_date: string;
timeline: TimelineEvent[];
total_deadlines: number;
}
export interface BatchCreateRequest {
deadlines: {
title: string;
due_date: string;
original_due_date?: string;
rule_id?: string;
rule_code?: string;
notes?: string;
}[];
}
export interface ProceedingType {
id: number;
code: string;
@@ -393,3 +329,81 @@ export interface ExtractionResponse {
deadlines: ExtractedDeadline[];
count: number;
}
// AI Document Drafting
export interface DocumentDraft {
title: string;
content: string;
language: string;
}
export interface DraftDocumentRequest {
case_id: string;
template_type: string;
instructions: string;
language: string;
}
export const TEMPLATE_TYPES: Record<string, string> = {
klageschrift: "Klageschrift",
klageerwiderung: "Klageerwiderung",
abmahnung: "Abmahnung",
schriftsatz: "Schriftsatz",
berufung: "Berufungsschrift",
antrag: "Antrag",
stellungnahme: "Stellungnahme",
gutachten: "Gutachten",
vertrag: "Vertrag",
vollmacht: "Vollmacht",
upc_claim: "UPC Statement of Claim",
upc_defence: "UPC Statement of Defence",
upc_counterclaim: "UPC Counterclaim for Revocation",
upc_injunction: "UPC Provisional Measures",
};
// AI Case Strategy
export interface StrategyStep {
priority: "high" | "medium" | "low";
action: string;
reasoning: string;
deadline?: string;
}
export interface RiskItem {
level: "high" | "medium" | "low";
risk: string;
mitigation: string;
}
export interface TimelineItem {
date: string;
event: string;
importance: "critical" | "important" | "routine";
}
export interface StrategyRecommendation {
summary: string;
next_steps: StrategyStep[];
risk_assessment: RiskItem[];
timeline: TimelineItem[];
}
// AI Similar Case Finder
export interface SimilarCase {
case_number: string;
title: string;
court: string;
date: string;
relevance: number;
explanation: string;
key_holdings: string;
url?: string;
}
export interface SimilarCasesResponse {
cases: SimilarCase[];
count: number;
}