feat: UPC deadline determination — event-driven proceeding timeline wizard
This commit is contained in:
@@ -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,15 +34,6 @@ 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)
|
||||
@@ -62,3 +53,12 @@ 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
|
||||
}
|
||||
|
||||
@@ -43,8 +43,7 @@ func (m *Middleware) RequireAuth(next http.Handler) http.Handler {
|
||||
}
|
||||
ctx = ContextWithRequestInfo(ctx, ip, r.UserAgent())
|
||||
|
||||
// Tenant/role resolution is handled by TenantResolver middleware for scoped routes.
|
||||
// Tenant management routes handle their own access control.
|
||||
// Tenant and role resolution handled by TenantResolver middleware for scoped routes.
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -34,6 +34,7 @@ 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)
|
||||
@@ -41,6 +42,7 @@ func (tr *TenantResolver) Resolve(next http.Handler) http.Handler {
|
||||
http.Error(w, `{"error":"invalid X-Tenant-ID"}`, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// Verify user has access and get their role
|
||||
role, err := tr.lookup.GetUserRole(r.Context(), userID, parsed)
|
||||
if err != nil {
|
||||
@@ -54,7 +56,7 @@ func (tr *TenantResolver) Resolve(next http.Handler) http.Handler {
|
||||
}
|
||||
|
||||
tenantID = parsed
|
||||
r = r.WithContext(ContextWithUserRole(r.Context(), role))
|
||||
ctx = ContextWithUserRole(ctx, role)
|
||||
} else {
|
||||
// Default to user's first tenant
|
||||
first, err := tr.lookup.FirstTenantForUser(r.Context(), userID)
|
||||
@@ -69,17 +71,17 @@ func (tr *TenantResolver) Resolve(next http.Handler) http.Handler {
|
||||
}
|
||||
tenantID = *first
|
||||
|
||||
// Resolve role for default tenant
|
||||
// Look up role for default tenant
|
||||
role, err := tr.lookup.GetUserRole(r.Context(), userID, tenantID)
|
||||
if err != nil {
|
||||
slog.Error("failed to resolve role for default tenant", "error", err)
|
||||
slog.Error("failed to get user role", "error", err, "user_id", userID, "tenant_id", tenantID)
|
||||
http.Error(w, `{"error":"internal error"}`, http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
r = r.WithContext(ContextWithUserRole(r.Context(), role))
|
||||
ctx = ContextWithUserRole(ctx, role)
|
||||
}
|
||||
|
||||
ctx := ContextWithTenantID(r.Context(), tenantID)
|
||||
ctx = ContextWithTenantID(ctx, tenantID)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -12,7 +12,6 @@ import (
|
||||
type mockTenantLookup struct {
|
||||
tenantID *uuid.UUID
|
||||
role string
|
||||
roleSet bool // true means role was explicitly set (even if empty)
|
||||
err error
|
||||
}
|
||||
|
||||
@@ -21,10 +20,7 @@ func (m *mockTenantLookup) FirstTenantForUser(ctx context.Context, userID uuid.U
|
||||
}
|
||||
|
||||
func (m *mockTenantLookup) GetUserRole(ctx context.Context, userID, tenantID uuid.UUID) (string, error) {
|
||||
if m.roleSet {
|
||||
return m.role, m.err
|
||||
}
|
||||
return "associate", m.err
|
||||
return m.role, m.err
|
||||
}
|
||||
|
||||
func TestTenantResolver_FromHeader(t *testing.T) {
|
||||
@@ -32,12 +28,14 @@ func TestTenantResolver_FromHeader(t *testing.T) {
|
||||
tr := NewTenantResolver(&mockTenantLookup{role: "partner"})
|
||||
|
||||
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)
|
||||
})
|
||||
|
||||
@@ -54,11 +52,14 @@ 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: "", roleSet: true})
|
||||
tr := NewTenantResolver(&mockTenantLookup{role: ""})
|
||||
|
||||
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
t.Fatal("next should not be called")
|
||||
@@ -78,7 +79,7 @@ func TestTenantResolver_FromHeader_NoAccess(t *testing.T) {
|
||||
|
||||
func TestTenantResolver_DefaultsToFirst(t *testing.T) {
|
||||
tenantID := uuid.New()
|
||||
tr := NewTenantResolver(&mockTenantLookup{tenantID: &tenantID, role: "owner"})
|
||||
tr := NewTenantResolver(&mockTenantLookup{tenantID: &tenantID, role: "associate"})
|
||||
|
||||
var gotTenantID uuid.UUID
|
||||
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
127
backend/internal/handlers/determine.go
Normal file
127
backend/internal/handlers/determine.go
Normal file
@@ -0,0 +1,127 @@
|
||||
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,
|
||||
})
|
||||
}
|
||||
@@ -26,6 +26,8 @@ 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"`
|
||||
|
||||
@@ -28,6 +28,7 @@ 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)
|
||||
@@ -64,6 +65,7 @@ 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)
|
||||
@@ -111,7 +113,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) // case-level access checked in handler
|
||||
scoped.HandleFunc("PUT /api/cases/{id}", caseH.Update)
|
||||
scoped.HandleFunc("DELETE /api/cases/{id}", perm(auth.PermCreateCase, caseH.Delete))
|
||||
|
||||
// Parties — same access as case editing
|
||||
@@ -137,6 +139,11 @@ 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)
|
||||
@@ -169,7 +176,7 @@ 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) // permission check inside handler
|
||||
scoped.HandleFunc("DELETE /api/documents/{docId}", docH.Delete)
|
||||
|
||||
// AI endpoints (rate limited: 5 req/min burst 10 per IP)
|
||||
if aiH != nil {
|
||||
|
||||
@@ -8,6 +8,12 @@ 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
|
||||
@@ -25,21 +31,13 @@ func (s *DeadlineRuleService) List(proceedingTypeID *int) ([]models.DeadlineRule
|
||||
|
||||
if proceedingTypeID != nil {
|
||||
err = s.db.Select(&rules,
|
||||
`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
|
||||
`SELECT `+ruleColumns+`
|
||||
FROM deadline_rules
|
||||
WHERE proceeding_type_id = $1 AND is_active = true
|
||||
ORDER BY sequence_order`, *proceedingTypeID)
|
||||
} else {
|
||||
err = s.db.Select(&rules,
|
||||
`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
|
||||
`SELECT `+ruleColumns+`
|
||||
FROM deadline_rules
|
||||
WHERE is_active = true
|
||||
ORDER BY proceeding_type_id, sequence_order`)
|
||||
@@ -72,11 +70,7 @@ func (s *DeadlineRuleService) GetRuleTree(proceedingTypeCode string) ([]RuleTree
|
||||
// Get all rules for this proceeding type
|
||||
var rules []models.DeadlineRule
|
||||
err = s.db.Select(&rules,
|
||||
`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
|
||||
`SELECT `+ruleColumns+`
|
||||
FROM deadline_rules
|
||||
WHERE proceeding_type_id = $1 AND is_active = true
|
||||
ORDER BY sequence_order`, pt.ID)
|
||||
@@ -87,6 +81,36 @@ 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 {
|
||||
@@ -94,11 +118,7 @@ func (s *DeadlineRuleService) GetByIDs(ids []string) ([]models.DeadlineRule, err
|
||||
}
|
||||
|
||||
query, args, err := sqlx.In(
|
||||
`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
|
||||
`SELECT `+ruleColumns+`
|
||||
FROM deadline_rules
|
||||
WHERE id IN (?) AND is_active = true
|
||||
ORDER BY sequence_order`, ids)
|
||||
@@ -119,11 +139,7 @@ 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 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
|
||||
`SELECT `+ruleColumns+`
|
||||
FROM deadline_rules
|
||||
WHERE proceeding_type_id = $1 AND is_active = true
|
||||
ORDER BY sequence_order`, proceedingTypeID)
|
||||
|
||||
236
backend/internal/services/determine_service.go
Normal file
236
backend/internal/services/determine_service.go
Normal file
@@ -0,0 +1,236 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user