Compare commits
15 Commits
mai/linus/
...
19bea8d058
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
19bea8d058 | ||
|
|
661135d137 | ||
|
|
f8d97546e9 | ||
|
|
45605c803b | ||
|
|
e57b7c48ed | ||
|
|
c5c3f41e08 | ||
|
|
d0197a091c | ||
|
|
fe97fed56d | ||
|
|
b49992b9c0 | ||
|
|
8bb8d7fed8 | ||
|
|
b4f3b26cbe | ||
|
|
6e9345fcfe | ||
|
|
785df2ced4 | ||
|
|
749273fba7 | ||
|
|
0ab2e8b383 |
@@ -3,11 +3,16 @@
|
|||||||
|
|
||||||
# Backend
|
# Backend
|
||||||
PORT=8080
|
PORT=8080
|
||||||
|
DATABASE_URL=postgresql://user:pass@host:5432/dbname
|
||||||
|
|
||||||
# Supabase (required for database access)
|
# Supabase (required for database + auth)
|
||||||
SUPABASE_URL=
|
SUPABASE_URL=https://your-project.supabase.co
|
||||||
SUPABASE_ANON_KEY=
|
SUPABASE_ANON_KEY=
|
||||||
SUPABASE_SERVICE_KEY=
|
SUPABASE_SERVICE_KEY=
|
||||||
|
SUPABASE_JWT_SECRET=
|
||||||
|
|
||||||
# Claude API (required for AI features)
|
# Claude API (required for AI features)
|
||||||
ANTHROPIC_API_KEY=
|
ANTHROPIC_API_KEY=
|
||||||
|
|
||||||
|
# CalDAV (configured per-tenant in tenant settings, not env vars)
|
||||||
|
# See tenant.settings.caldav JSON field
|
||||||
|
|||||||
@@ -1,32 +1,46 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"log"
|
"log/slog"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"os"
|
||||||
|
|
||||||
"mgit.msbls.de/m/KanzlAI-mGMT/internal/auth"
|
"mgit.msbls.de/m/KanzlAI-mGMT/internal/auth"
|
||||||
"mgit.msbls.de/m/KanzlAI-mGMT/internal/config"
|
"mgit.msbls.de/m/KanzlAI-mGMT/internal/config"
|
||||||
"mgit.msbls.de/m/KanzlAI-mGMT/internal/db"
|
"mgit.msbls.de/m/KanzlAI-mGMT/internal/db"
|
||||||
|
"mgit.msbls.de/m/KanzlAI-mGMT/internal/logging"
|
||||||
"mgit.msbls.de/m/KanzlAI-mGMT/internal/router"
|
"mgit.msbls.de/m/KanzlAI-mGMT/internal/router"
|
||||||
|
"mgit.msbls.de/m/KanzlAI-mGMT/internal/services"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
|
logging.Setup()
|
||||||
|
|
||||||
cfg, err := config.Load()
|
cfg, err := config.Load()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("Failed to load config: %v", err)
|
slog.Error("failed to load config", "error", err)
|
||||||
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
database, err := db.Connect(cfg.DatabaseURL)
|
database, err := db.Connect(cfg.DatabaseURL)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("Failed to connect to database: %v", err)
|
slog.Error("failed to connect to database", "error", err)
|
||||||
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
defer database.Close()
|
defer database.Close()
|
||||||
|
|
||||||
authMW := auth.NewMiddleware(cfg.SupabaseJWTSecret, database)
|
authMW := auth.NewMiddleware(cfg.SupabaseJWTSecret, database)
|
||||||
handler := router.New(database, authMW, cfg)
|
|
||||||
|
|
||||||
log.Printf("Starting KanzlAI API server on :%s", cfg.Port)
|
// Start CalDAV sync service
|
||||||
|
calDAVSvc := services.NewCalDAVService(database)
|
||||||
|
calDAVSvc.Start()
|
||||||
|
defer calDAVSvc.Stop()
|
||||||
|
|
||||||
|
handler := router.New(database, authMW, cfg, calDAVSvc)
|
||||||
|
|
||||||
|
slog.Info("starting KanzlAI API server", "port", cfg.Port)
|
||||||
if err := http.ListenAndServe(":"+cfg.Port, handler); err != nil {
|
if err := http.ListenAndServe(":"+cfg.Port, handler); err != nil {
|
||||||
log.Fatal(err)
|
slog.Error("server failed", "error", err)
|
||||||
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,11 +3,17 @@ module mgit.msbls.de/m/KanzlAI-mGMT
|
|||||||
go 1.25.5
|
go 1.25.5
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/anthropics/anthropic-sdk-go v1.27.1 // indirect
|
github.com/anthropics/anthropic-sdk-go v1.27.1
|
||||||
github.com/golang-jwt/jwt/v5 v5.3.1 // indirect
|
github.com/emersion/go-ical v0.0.0-20250609112844-439c63cef608
|
||||||
github.com/google/uuid v1.6.0 // indirect
|
github.com/emersion/go-webdav v0.7.0
|
||||||
github.com/jmoiron/sqlx v1.4.0 // indirect
|
github.com/golang-jwt/jwt/v5 v5.3.1
|
||||||
github.com/lib/pq v1.12.0 // indirect
|
github.com/google/uuid v1.6.0
|
||||||
|
github.com/jmoiron/sqlx v1.4.0
|
||||||
|
github.com/lib/pq v1.12.0
|
||||||
|
)
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/teambition/rrule-go v1.8.2 // indirect
|
||||||
github.com/tidwall/gjson v1.18.0 // indirect
|
github.com/tidwall/gjson v1.18.0 // indirect
|
||||||
github.com/tidwall/match v1.1.1 // indirect
|
github.com/tidwall/match v1.1.1 // indirect
|
||||||
github.com/tidwall/pretty v1.2.1 // indirect
|
github.com/tidwall/pretty v1.2.1 // indirect
|
||||||
|
|||||||
@@ -1,6 +1,18 @@
|
|||||||
|
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
|
||||||
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
|
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
|
||||||
github.com/anthropics/anthropic-sdk-go v1.27.1 h1:7DgMZ2Ng3C2mPzJGHA30NXQTZolcF07mHd0tGaLwfzk=
|
github.com/anthropics/anthropic-sdk-go v1.27.1 h1:7DgMZ2Ng3C2mPzJGHA30NXQTZolcF07mHd0tGaLwfzk=
|
||||||
github.com/anthropics/anthropic-sdk-go v1.27.1/go.mod h1:qUKmaW+uuPB64iy1l+4kOSvaLqPXnHTTBKH6RVZ7q5Q=
|
github.com/anthropics/anthropic-sdk-go v1.27.1/go.mod h1:qUKmaW+uuPB64iy1l+4kOSvaLqPXnHTTBKH6RVZ7q5Q=
|
||||||
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/dnaeon/go-vcr v1.2.0 h1:zHCHvJYTMh1N7xnV7zf1m1GPBF9Ad0Jk/whtQ1663qI=
|
||||||
|
github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5OLb6RQ=
|
||||||
|
github.com/emersion/go-ical v0.0.0-20240127095438-fc1c9d8fb2b6/go.mod h1:BEksegNspIkjCQfmzWgsgbu6KdeJ/4LwUZs7DMBzjzw=
|
||||||
|
github.com/emersion/go-ical v0.0.0-20250609112844-439c63cef608 h1:5XWaET4YAcppq3l1/Yh2ay5VmQjUdq6qhJuucdGbmOY=
|
||||||
|
github.com/emersion/go-ical v0.0.0-20250609112844-439c63cef608/go.mod h1:BEksegNspIkjCQfmzWgsgbu6KdeJ/4LwUZs7DMBzjzw=
|
||||||
|
github.com/emersion/go-vcard v0.0.0-20230815062825-8fda7d206ec9/go.mod h1:HMJKR5wlh/ziNp+sHEDV2ltblO4JD2+IdDOWtGcQBTM=
|
||||||
|
github.com/emersion/go-webdav v0.7.0 h1:cp6aBWXBf8Sjzguka9VJarr4XTkGc2IHxXI1Gq3TKpA=
|
||||||
|
github.com/emersion/go-webdav v0.7.0/go.mod h1:mI8iBx3RAODwX7PJJ7qzsKAKs/vY429YfS2/9wKnDbQ=
|
||||||
|
github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y=
|
||||||
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
|
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
|
||||||
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
|
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
|
||||||
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
||||||
@@ -11,7 +23,14 @@ github.com/jmoiron/sqlx v1.4.0/go.mod h1:ZrZ7UsYB/weZdl2Bxg6jCRO9c3YHl8r3ahlKmRT
|
|||||||
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
|
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
|
||||||
github.com/lib/pq v1.12.0 h1:mC1zeiNamwKBecjHarAr26c/+d8V5w/u4J0I/yASbJo=
|
github.com/lib/pq v1.12.0 h1:mC1zeiNamwKBecjHarAr26c/+d8V5w/u4J0I/yASbJo=
|
||||||
github.com/lib/pq v1.12.0/go.mod h1:/p+8NSbOcwzAEI7wiMXFlgydTwcgTr3OSKMsD2BitpA=
|
github.com/lib/pq v1.12.0/go.mod h1:/p+8NSbOcwzAEI7wiMXFlgydTwcgTr3OSKMsD2BitpA=
|
||||||
|
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
|
||||||
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
|
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
|
||||||
|
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||||
|
github.com/teambition/rrule-go v1.8.2 h1:lIjpjvWTj9fFUZCmuoVDrKVOtdiyzbzc93qTmRVe/J8=
|
||||||
|
github.com/teambition/rrule-go v1.8.2/go.mod h1:Ieq5AbrKGciP1V//Wq8ktsTXwSwJHDD5mD/wLBGl3p4=
|
||||||
github.com/tidwall/gjson v1.14.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
|
github.com/tidwall/gjson v1.14.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
|
||||||
github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY=
|
github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY=
|
||||||
github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
|
github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
|
||||||
@@ -24,3 +43,7 @@ github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY=
|
|||||||
github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28=
|
github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28=
|
||||||
golang.org/x/sync v0.16.0 h1:ycBJEhp9p4vXvUZNszeOq0kGTPghopOL8q0fq3vstxw=
|
golang.org/x/sync v0.16.0 h1:ycBJEhp9p4vXvUZNszeOq0kGTPghopOL8q0fq3vstxw=
|
||||||
golang.org/x/sync v0.16.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
|
golang.org/x/sync v0.16.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
|
||||||
|
gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
|
||||||
|
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
|||||||
68
backend/internal/handlers/caldav.go
Normal file
68
backend/internal/handlers/caldav.go
Normal file
@@ -0,0 +1,68 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"mgit.msbls.de/m/KanzlAI-mGMT/internal/auth"
|
||||||
|
"mgit.msbls.de/m/KanzlAI-mGMT/internal/services"
|
||||||
|
)
|
||||||
|
|
||||||
|
// CalDAVHandler handles CalDAV sync HTTP endpoints.
|
||||||
|
type CalDAVHandler struct {
|
||||||
|
svc *services.CalDAVService
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewCalDAVHandler creates a new CalDAV handler.
|
||||||
|
func NewCalDAVHandler(svc *services.CalDAVService) *CalDAVHandler {
|
||||||
|
return &CalDAVHandler{svc: svc}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TriggerSync handles POST /api/caldav/sync — triggers a full sync for the current tenant.
|
||||||
|
func (h *CalDAVHandler) TriggerSync(w http.ResponseWriter, r *http.Request) {
|
||||||
|
tenantID, ok := auth.TenantFromContext(r.Context())
|
||||||
|
if !ok {
|
||||||
|
writeError(w, http.StatusUnauthorized, "no tenant context")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
cfg, err := h.svc.LoadTenantConfig(tenantID)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, http.StatusBadRequest, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
status, err := h.svc.SyncTenant(r.Context(), tenantID, *cfg)
|
||||||
|
if err != nil {
|
||||||
|
// Still return the status — it contains partial results + error info
|
||||||
|
writeJSON(w, http.StatusOK, map[string]any{
|
||||||
|
"status": "completed_with_errors",
|
||||||
|
"sync": status,
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
writeJSON(w, http.StatusOK, map[string]any{
|
||||||
|
"status": "ok",
|
||||||
|
"sync": status,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetStatus handles GET /api/caldav/status — returns last sync status.
|
||||||
|
func (h *CalDAVHandler) GetStatus(w http.ResponseWriter, r *http.Request) {
|
||||||
|
tenantID, ok := auth.TenantFromContext(r.Context())
|
||||||
|
if !ok {
|
||||||
|
writeError(w, http.StatusUnauthorized, "no tenant context")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
status := h.svc.GetStatus(tenantID)
|
||||||
|
if status == nil {
|
||||||
|
writeJSON(w, http.StatusOK, map[string]any{
|
||||||
|
"status": "no_sync_yet",
|
||||||
|
"last_sync_at": nil,
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
writeJSON(w, http.StatusOK, status)
|
||||||
|
}
|
||||||
@@ -196,6 +196,46 @@ func (h *TenantHandler) RemoveMember(w http.ResponseWriter, r *http.Request) {
|
|||||||
jsonResponse(w, map[string]string{"status": "removed"}, http.StatusOK)
|
jsonResponse(w, map[string]string{"status": "removed"}, http.StatusOK)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// UpdateSettings handles PUT /api/tenants/{id}/settings
|
||||||
|
func (h *TenantHandler) UpdateSettings(w http.ResponseWriter, r *http.Request) {
|
||||||
|
userID, ok := auth.UserFromContext(r.Context())
|
||||||
|
if !ok {
|
||||||
|
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
tenantID, err := uuid.Parse(r.PathValue("id"))
|
||||||
|
if err != nil {
|
||||||
|
jsonError(w, "invalid tenant ID", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only owners and admins can update settings
|
||||||
|
role, err := h.svc.GetUserRole(r.Context(), userID, tenantID)
|
||||||
|
if err != nil {
|
||||||
|
jsonError(w, err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if role != "owner" && role != "admin" {
|
||||||
|
jsonError(w, "only owners and admins can update settings", http.StatusForbidden)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var settings json.RawMessage
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&settings); err != nil {
|
||||||
|
jsonError(w, "invalid request body", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
tenant, err := h.svc.UpdateSettings(r.Context(), tenantID, settings)
|
||||||
|
if err != nil {
|
||||||
|
jsonError(w, err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
jsonResponse(w, tenant, http.StatusOK)
|
||||||
|
}
|
||||||
|
|
||||||
// ListMembers handles GET /api/tenants/{id}/members
|
// ListMembers handles GET /api/tenants/{id}/members
|
||||||
func (h *TenantHandler) ListMembers(w http.ResponseWriter, r *http.Request) {
|
func (h *TenantHandler) ListMembers(w http.ResponseWriter, r *http.Request) {
|
||||||
userID, ok := auth.UserFromContext(r.Context())
|
userID, ok := auth.UserFromContext(r.Context())
|
||||||
|
|||||||
273
backend/internal/integration_test.go
Normal file
273
backend/internal/integration_test.go
Normal file
@@ -0,0 +1,273 @@
|
|||||||
|
package internal_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"mgit.msbls.de/m/KanzlAI-mGMT/internal/auth"
|
||||||
|
"mgit.msbls.de/m/KanzlAI-mGMT/internal/config"
|
||||||
|
"mgit.msbls.de/m/KanzlAI-mGMT/internal/db"
|
||||||
|
"mgit.msbls.de/m/KanzlAI-mGMT/internal/router"
|
||||||
|
|
||||||
|
"github.com/golang-jwt/jwt/v5"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
// testServer sets up the full router with a real DB connection.
|
||||||
|
// Requires DATABASE_URL and SUPABASE_JWT_SECRET env vars.
|
||||||
|
func testServer(t *testing.T) (http.Handler, func()) {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
dbURL := os.Getenv("DATABASE_URL")
|
||||||
|
if dbURL == "" {
|
||||||
|
t.Skip("DATABASE_URL not set, skipping integration test")
|
||||||
|
}
|
||||||
|
jwtSecret := os.Getenv("SUPABASE_JWT_SECRET")
|
||||||
|
if jwtSecret == "" {
|
||||||
|
jwtSecret = "test-jwt-secret-for-integration-tests"
|
||||||
|
os.Setenv("SUPABASE_JWT_SECRET", jwtSecret)
|
||||||
|
}
|
||||||
|
|
||||||
|
database, err := db.Connect(dbURL)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("connecting to database: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
cfg := &config.Config{
|
||||||
|
Port: "0",
|
||||||
|
DatabaseURL: dbURL,
|
||||||
|
SupabaseJWTSecret: jwtSecret,
|
||||||
|
}
|
||||||
|
|
||||||
|
authMW := auth.NewMiddleware(jwtSecret, database)
|
||||||
|
handler := router.New(database, authMW, cfg, nil)
|
||||||
|
|
||||||
|
return handler, func() { database.Close() }
|
||||||
|
}
|
||||||
|
|
||||||
|
// createTestJWT creates a JWT for the given user ID, signed with the test secret.
|
||||||
|
func createTestJWT(t *testing.T, userID uuid.UUID) string {
|
||||||
|
t.Helper()
|
||||||
|
secret := os.Getenv("SUPABASE_JWT_SECRET")
|
||||||
|
if secret == "" {
|
||||||
|
secret = "test-jwt-secret-for-integration-tests"
|
||||||
|
}
|
||||||
|
|
||||||
|
claims := jwt.MapClaims{
|
||||||
|
"sub": userID.String(),
|
||||||
|
"aud": "authenticated",
|
||||||
|
"exp": time.Now().Add(1 * time.Hour).Unix(),
|
||||||
|
"iat": time.Now().Unix(),
|
||||||
|
}
|
||||||
|
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||||
|
signed, err := token.SignedString([]byte(secret))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("signing JWT: %v", err)
|
||||||
|
}
|
||||||
|
return signed
|
||||||
|
}
|
||||||
|
|
||||||
|
// setupTestTenant creates a temporary tenant and user_tenant for testing.
|
||||||
|
// Returns tenantID and userID. Cleans up on test completion.
|
||||||
|
func setupTestTenant(t *testing.T, handler http.Handler) (tenantID, userID uuid.UUID) {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
dbURL := os.Getenv("DATABASE_URL")
|
||||||
|
database, err := db.Connect(dbURL)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("connecting to database for setup: %v", err)
|
||||||
|
}
|
||||||
|
defer database.Close()
|
||||||
|
|
||||||
|
tenantID = uuid.New()
|
||||||
|
userID = uuid.New()
|
||||||
|
|
||||||
|
_, err = database.Exec(`INSERT INTO tenants (id, name, slug) VALUES ($1, $2, $3)`,
|
||||||
|
tenantID, "Integration Test Kanzlei "+tenantID.String()[:8], "test-"+tenantID.String()[:8])
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("creating test tenant: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create a user in auth.users so JWT auth works
|
||||||
|
_, err = database.Exec(`INSERT INTO auth.users (id, instance_id, role, aud, email, encrypted_password, email_confirmed_at, created_at, updated_at, confirmation_token, recovery_token)
|
||||||
|
VALUES ($1, '00000000-0000-0000-0000-000000000000', 'authenticated', 'authenticated', $2, '', NOW(), NOW(), NOW(), '', '')`,
|
||||||
|
userID, fmt.Sprintf("test-%s@kanzlai.test", userID.String()[:8]))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("creating test user: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = database.Exec(`INSERT INTO user_tenants (user_id, tenant_id, role) VALUES ($1, $2, 'owner')`,
|
||||||
|
userID, tenantID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("creating user_tenant: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Cleanup(func() {
|
||||||
|
cleanupDB, _ := db.Connect(dbURL)
|
||||||
|
if cleanupDB != nil {
|
||||||
|
cleanupDB.Exec(`DELETE FROM case_events WHERE tenant_id = $1`, tenantID)
|
||||||
|
cleanupDB.Exec(`DELETE FROM deadlines WHERE tenant_id = $1`, tenantID)
|
||||||
|
cleanupDB.Exec(`DELETE FROM appointments WHERE tenant_id = $1`, tenantID)
|
||||||
|
cleanupDB.Exec(`DELETE FROM parties WHERE tenant_id = $1`, tenantID)
|
||||||
|
cleanupDB.Exec(`DELETE FROM documents WHERE tenant_id = $1`, tenantID)
|
||||||
|
cleanupDB.Exec(`DELETE FROM cases WHERE tenant_id = $1`, tenantID)
|
||||||
|
cleanupDB.Exec(`DELETE FROM user_tenants WHERE tenant_id = $1`, tenantID)
|
||||||
|
cleanupDB.Exec(`DELETE FROM tenants WHERE id = $1`, tenantID)
|
||||||
|
cleanupDB.Exec(`DELETE FROM auth.users WHERE id = $1`, userID)
|
||||||
|
cleanupDB.Close()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
return tenantID, userID
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHealthEndpoint(t *testing.T) {
|
||||||
|
handler, cleanup := testServer(t)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
req := httptest.NewRequest("GET", "/health", nil)
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
handler.ServeHTTP(w, req)
|
||||||
|
|
||||||
|
if w.Code != http.StatusOK {
|
||||||
|
t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
var resp map[string]string
|
||||||
|
json.Unmarshal(w.Body.Bytes(), &resp)
|
||||||
|
if resp["status"] != "ok" {
|
||||||
|
t.Fatalf("expected status ok, got %v", resp)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCriticalPath_CreateCase_AddDeadline_Dashboard(t *testing.T) {
|
||||||
|
handler, cleanup := testServer(t)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
_, userID := setupTestTenant(t, handler)
|
||||||
|
token := createTestJWT(t, userID)
|
||||||
|
|
||||||
|
// Step 1: Create a case
|
||||||
|
caseBody := `{"case_number":"TEST/001","title":"Integration Test — Patentverletzung","case_type":"patent","court":"UPC München"}`
|
||||||
|
req := httptest.NewRequest("POST", "/api/cases", bytes.NewBufferString(caseBody))
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
req.Header.Set("Authorization", "Bearer "+token)
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
handler.ServeHTTP(w, req)
|
||||||
|
|
||||||
|
if w.Code != http.StatusCreated {
|
||||||
|
t.Fatalf("create case: expected 201, got %d: %s", w.Code, w.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
var createdCase map[string]interface{}
|
||||||
|
json.Unmarshal(w.Body.Bytes(), &createdCase)
|
||||||
|
caseID, ok := createdCase["id"].(string)
|
||||||
|
if !ok || caseID == "" {
|
||||||
|
t.Fatalf("create case: missing ID in response: %v", createdCase)
|
||||||
|
}
|
||||||
|
t.Logf("Created case: %s", caseID)
|
||||||
|
|
||||||
|
// Step 2: List cases — verify our case is there
|
||||||
|
req = httptest.NewRequest("GET", "/api/cases", nil)
|
||||||
|
req.Header.Set("Authorization", "Bearer "+token)
|
||||||
|
w = httptest.NewRecorder()
|
||||||
|
handler.ServeHTTP(w, req)
|
||||||
|
|
||||||
|
if w.Code != http.StatusOK {
|
||||||
|
t.Fatalf("list cases: expected 200, got %d: %s", w.Code, w.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
var caseList map[string]interface{}
|
||||||
|
json.Unmarshal(w.Body.Bytes(), &caseList)
|
||||||
|
total := caseList["total"].(float64)
|
||||||
|
if total < 1 {
|
||||||
|
t.Fatalf("list cases: expected at least 1 case, got %.0f", total)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 3: Add a deadline to the case
|
||||||
|
dueDate := time.Now().AddDate(0, 0, 14).Format("2006-01-02")
|
||||||
|
warnDate := time.Now().AddDate(0, 0, 10).Format("2006-01-02")
|
||||||
|
deadlineBody := fmt.Sprintf(`{"title":"Klageerwiderung einreichen","due_date":"%s","warning_date":"%s","source":"manual"}`, dueDate, warnDate)
|
||||||
|
req = httptest.NewRequest("POST", "/api/cases/"+caseID+"/deadlines", bytes.NewBufferString(deadlineBody))
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
req.Header.Set("Authorization", "Bearer "+token)
|
||||||
|
w = httptest.NewRecorder()
|
||||||
|
handler.ServeHTTP(w, req)
|
||||||
|
|
||||||
|
if w.Code != http.StatusCreated {
|
||||||
|
t.Fatalf("create deadline: expected 201, got %d: %s", w.Code, w.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
var createdDeadline map[string]interface{}
|
||||||
|
json.Unmarshal(w.Body.Bytes(), &createdDeadline)
|
||||||
|
deadlineID, ok := createdDeadline["id"].(string)
|
||||||
|
if !ok || deadlineID == "" {
|
||||||
|
t.Fatalf("create deadline: missing ID in response: %v", createdDeadline)
|
||||||
|
}
|
||||||
|
t.Logf("Created deadline: %s", deadlineID)
|
||||||
|
|
||||||
|
// Step 4: Verify deadline appears in case deadlines
|
||||||
|
req = httptest.NewRequest("GET", "/api/cases/"+caseID+"/deadlines", nil)
|
||||||
|
req.Header.Set("Authorization", "Bearer "+token)
|
||||||
|
w = httptest.NewRecorder()
|
||||||
|
handler.ServeHTTP(w, req)
|
||||||
|
|
||||||
|
if w.Code != http.StatusOK {
|
||||||
|
t.Fatalf("list deadlines: expected 200, got %d: %s", w.Code, w.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
var deadlines []interface{}
|
||||||
|
json.Unmarshal(w.Body.Bytes(), &deadlines)
|
||||||
|
if len(deadlines) < 1 {
|
||||||
|
t.Fatalf("list deadlines: expected at least 1, got %d", len(deadlines))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 5: Fetch dashboard — should include our case and deadline
|
||||||
|
req = httptest.NewRequest("GET", "/api/dashboard", nil)
|
||||||
|
req.Header.Set("Authorization", "Bearer "+token)
|
||||||
|
w = httptest.NewRecorder()
|
||||||
|
handler.ServeHTTP(w, req)
|
||||||
|
|
||||||
|
if w.Code != http.StatusOK {
|
||||||
|
t.Fatalf("dashboard: expected 200, got %d: %s", w.Code, w.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
var dashboard map[string]interface{}
|
||||||
|
json.Unmarshal(w.Body.Bytes(), &dashboard)
|
||||||
|
|
||||||
|
// Verify dashboard has expected sections
|
||||||
|
for _, key := range []string{"deadline_summary", "case_summary", "upcoming_deadlines"} {
|
||||||
|
if _, exists := dashboard[key]; !exists {
|
||||||
|
t.Errorf("dashboard: missing key %q in response", key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify case_summary shows at least 1 active case
|
||||||
|
if cs, ok := dashboard["case_summary"].(map[string]interface{}); ok {
|
||||||
|
if active, ok := cs["active"].(float64); ok && active < 1 {
|
||||||
|
t.Errorf("dashboard: expected at least 1 active case, got %.0f", active)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Logf("Full critical path passed: auth -> create case -> add deadline -> dashboard")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUnauthenticatedAccess(t *testing.T) {
|
||||||
|
handler, cleanup := testServer(t)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
// Accessing API without token should return 401
|
||||||
|
req := httptest.NewRequest("GET", "/api/cases", nil)
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
handler.ServeHTTP(w, req)
|
||||||
|
|
||||||
|
if w.Code != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("expected 401, got %d: %s", w.Code, w.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
14
backend/internal/logging/logging.go
Normal file
14
backend/internal/logging/logging.go
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
package logging
|
||||||
|
|
||||||
|
import (
|
||||||
|
"log/slog"
|
||||||
|
"os"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Setup initializes the global slog logger with JSON output for production.
|
||||||
|
func Setup() {
|
||||||
|
handler := slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
|
||||||
|
Level: slog.LevelInfo,
|
||||||
|
})
|
||||||
|
slog.SetDefault(slog.New(handler))
|
||||||
|
}
|
||||||
98
backend/internal/middleware/ratelimit.go
Normal file
98
backend/internal/middleware/ratelimit.go
Normal file
@@ -0,0 +1,98 @@
|
|||||||
|
package middleware
|
||||||
|
|
||||||
|
import (
|
||||||
|
"log/slog"
|
||||||
|
"net/http"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TokenBucket implements a simple per-IP token bucket rate limiter.
|
||||||
|
type TokenBucket struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
buckets map[string]*bucket
|
||||||
|
rate float64 // tokens per second
|
||||||
|
burst int // max tokens
|
||||||
|
}
|
||||||
|
|
||||||
|
type bucket struct {
|
||||||
|
tokens float64
|
||||||
|
lastTime time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewTokenBucket creates a rate limiter allowing rate requests per second with burst capacity.
|
||||||
|
func NewTokenBucket(rate float64, burst int) *TokenBucket {
|
||||||
|
tb := &TokenBucket{
|
||||||
|
buckets: make(map[string]*bucket),
|
||||||
|
rate: rate,
|
||||||
|
burst: burst,
|
||||||
|
}
|
||||||
|
// Periodically clean up stale buckets
|
||||||
|
go tb.cleanup()
|
||||||
|
return tb
|
||||||
|
}
|
||||||
|
|
||||||
|
func (tb *TokenBucket) allow(key string) bool {
|
||||||
|
tb.mu.Lock()
|
||||||
|
defer tb.mu.Unlock()
|
||||||
|
|
||||||
|
b, ok := tb.buckets[key]
|
||||||
|
if !ok {
|
||||||
|
b = &bucket{tokens: float64(tb.burst), lastTime: time.Now()}
|
||||||
|
tb.buckets[key] = b
|
||||||
|
}
|
||||||
|
|
||||||
|
now := time.Now()
|
||||||
|
elapsed := now.Sub(b.lastTime).Seconds()
|
||||||
|
b.tokens += elapsed * tb.rate
|
||||||
|
if b.tokens > float64(tb.burst) {
|
||||||
|
b.tokens = float64(tb.burst)
|
||||||
|
}
|
||||||
|
b.lastTime = now
|
||||||
|
|
||||||
|
if b.tokens < 1 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
b.tokens--
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (tb *TokenBucket) cleanup() {
|
||||||
|
ticker := time.NewTicker(5 * time.Minute)
|
||||||
|
defer ticker.Stop()
|
||||||
|
for range ticker.C {
|
||||||
|
tb.mu.Lock()
|
||||||
|
cutoff := time.Now().Add(-10 * time.Minute)
|
||||||
|
for key, b := range tb.buckets {
|
||||||
|
if b.lastTime.Before(cutoff) {
|
||||||
|
delete(tb.buckets, key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tb.mu.Unlock()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Limit wraps an http.Handler with rate limiting.
|
||||||
|
func (tb *TokenBucket) Limit(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
ip := r.Header.Get("X-Forwarded-For")
|
||||||
|
if ip == "" {
|
||||||
|
ip = r.RemoteAddr
|
||||||
|
}
|
||||||
|
if !tb.allow(ip) {
|
||||||
|
slog.Warn("rate limit exceeded", "ip", ip, "path", r.URL.Path)
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
w.Header().Set("Retry-After", "10")
|
||||||
|
w.WriteHeader(http.StatusTooManyRequests)
|
||||||
|
w.Write([]byte(`{"error":"rate limit exceeded, try again later"}`))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// LimitFunc wraps an http.HandlerFunc with rate limiting.
|
||||||
|
func (tb *TokenBucket) LimitFunc(next http.HandlerFunc) http.HandlerFunc {
|
||||||
|
limited := tb.Limit(http.HandlerFunc(next))
|
||||||
|
return limited.ServeHTTP
|
||||||
|
}
|
||||||
70
backend/internal/middleware/ratelimit_test.go
Normal file
70
backend/internal/middleware/ratelimit_test.go
Normal file
@@ -0,0 +1,70 @@
|
|||||||
|
package middleware
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestTokenBucket_AllowsBurst(t *testing.T) {
|
||||||
|
tb := NewTokenBucket(1.0, 5) // 1/sec, burst 5
|
||||||
|
|
||||||
|
handler := tb.LimitFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
})
|
||||||
|
|
||||||
|
// Should allow burst of 5 requests
|
||||||
|
for i := 0; i < 5; i++ {
|
||||||
|
req := httptest.NewRequest("GET", "/test", nil)
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
handler.ServeHTTP(w, req)
|
||||||
|
if w.Code != http.StatusOK {
|
||||||
|
t.Fatalf("request %d: expected 200, got %d", i+1, w.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 6th request should be rate limited
|
||||||
|
req := httptest.NewRequest("GET", "/test", nil)
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
handler.ServeHTTP(w, req)
|
||||||
|
if w.Code != http.StatusTooManyRequests {
|
||||||
|
t.Fatalf("request 6: expected 429, got %d", w.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTokenBucket_DifferentIPs(t *testing.T) {
|
||||||
|
tb := NewTokenBucket(1.0, 2) // 1/sec, burst 2
|
||||||
|
|
||||||
|
handler := tb.LimitFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
})
|
||||||
|
|
||||||
|
// Exhaust IP1's bucket
|
||||||
|
for i := 0; i < 2; i++ {
|
||||||
|
req := httptest.NewRequest("GET", "/test", nil)
|
||||||
|
req.Header.Set("X-Forwarded-For", "1.2.3.4")
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
handler.ServeHTTP(w, req)
|
||||||
|
if w.Code != http.StatusOK {
|
||||||
|
t.Fatalf("ip1 request %d: expected 200, got %d", i+1, w.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// IP1 should now be limited
|
||||||
|
req := httptest.NewRequest("GET", "/test", nil)
|
||||||
|
req.Header.Set("X-Forwarded-For", "1.2.3.4")
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
handler.ServeHTTP(w, req)
|
||||||
|
if w.Code != http.StatusTooManyRequests {
|
||||||
|
t.Fatalf("ip1 request 3: expected 429, got %d", w.Code)
|
||||||
|
}
|
||||||
|
|
||||||
|
// IP2 should still work
|
||||||
|
req = httptest.NewRequest("GET", "/test", nil)
|
||||||
|
req.Header.Set("X-Forwarded-For", "5.6.7.8")
|
||||||
|
w = httptest.NewRecorder()
|
||||||
|
handler.ServeHTTP(w, req)
|
||||||
|
if w.Code != http.StatusOK {
|
||||||
|
t.Fatalf("ip2 request 1: expected 200, got %d", w.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,17 +2,20 @@ package router
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"log/slog"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/jmoiron/sqlx"
|
"github.com/jmoiron/sqlx"
|
||||||
|
|
||||||
"mgit.msbls.de/m/KanzlAI-mGMT/internal/auth"
|
"mgit.msbls.de/m/KanzlAI-mGMT/internal/auth"
|
||||||
"mgit.msbls.de/m/KanzlAI-mGMT/internal/config"
|
"mgit.msbls.de/m/KanzlAI-mGMT/internal/config"
|
||||||
"mgit.msbls.de/m/KanzlAI-mGMT/internal/handlers"
|
"mgit.msbls.de/m/KanzlAI-mGMT/internal/handlers"
|
||||||
|
"mgit.msbls.de/m/KanzlAI-mGMT/internal/middleware"
|
||||||
"mgit.msbls.de/m/KanzlAI-mGMT/internal/services"
|
"mgit.msbls.de/m/KanzlAI-mGMT/internal/services"
|
||||||
)
|
)
|
||||||
|
|
||||||
func New(db *sqlx.DB, authMW *auth.Middleware, cfg *config.Config) http.Handler {
|
func New(db *sqlx.DB, authMW *auth.Middleware, cfg *config.Config, calDAVSvc *services.CalDAVService) http.Handler {
|
||||||
mux := http.NewServeMux()
|
mux := http.NewServeMux()
|
||||||
|
|
||||||
// Services
|
// Services
|
||||||
@@ -60,6 +63,7 @@ func New(db *sqlx.DB, authMW *auth.Middleware, cfg *config.Config) http.Handler
|
|||||||
api.HandleFunc("POST /api/tenants", tenantH.CreateTenant)
|
api.HandleFunc("POST /api/tenants", tenantH.CreateTenant)
|
||||||
api.HandleFunc("GET /api/tenants", tenantH.ListTenants)
|
api.HandleFunc("GET /api/tenants", tenantH.ListTenants)
|
||||||
api.HandleFunc("GET /api/tenants/{id}", tenantH.GetTenant)
|
api.HandleFunc("GET /api/tenants/{id}", tenantH.GetTenant)
|
||||||
|
api.HandleFunc("PUT /api/tenants/{id}/settings", tenantH.UpdateSettings)
|
||||||
api.HandleFunc("POST /api/tenants/{id}/invite", tenantH.InviteUser)
|
api.HandleFunc("POST /api/tenants/{id}/invite", tenantH.InviteUser)
|
||||||
api.HandleFunc("DELETE /api/tenants/{id}/members/{uid}", tenantH.RemoveMember)
|
api.HandleFunc("DELETE /api/tenants/{id}/members/{uid}", tenantH.RemoveMember)
|
||||||
api.HandleFunc("GET /api/tenants/{id}/members", tenantH.ListMembers)
|
api.HandleFunc("GET /api/tenants/{id}/members", tenantH.ListMembers)
|
||||||
@@ -112,10 +116,18 @@ func New(db *sqlx.DB, authMW *auth.Middleware, cfg *config.Config) http.Handler
|
|||||||
scoped.HandleFunc("GET /api/documents/{docId}/meta", docH.GetMeta)
|
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)
|
||||||
|
|
||||||
// AI endpoints
|
// AI endpoints (rate limited: 5 req/min burst 10 per IP)
|
||||||
if aiH != nil {
|
if aiH != nil {
|
||||||
scoped.HandleFunc("POST /api/ai/extract-deadlines", aiH.ExtractDeadlines)
|
aiLimiter := middleware.NewTokenBucket(5.0/60.0, 10)
|
||||||
scoped.HandleFunc("POST /api/ai/summarize-case", aiH.SummarizeCase)
|
scoped.HandleFunc("POST /api/ai/extract-deadlines", aiLimiter.LimitFunc(aiH.ExtractDeadlines))
|
||||||
|
scoped.HandleFunc("POST /api/ai/summarize-case", aiLimiter.LimitFunc(aiH.SummarizeCase))
|
||||||
|
}
|
||||||
|
|
||||||
|
// CalDAV sync endpoints
|
||||||
|
if calDAVSvc != nil {
|
||||||
|
calDAVH := handlers.NewCalDAVHandler(calDAVSvc)
|
||||||
|
scoped.HandleFunc("POST /api/caldav/sync", calDAVH.TriggerSync)
|
||||||
|
scoped.HandleFunc("GET /api/caldav/status", calDAVH.GetStatus)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Wire: auth -> tenant routes go directly, scoped routes get tenant resolver
|
// Wire: auth -> tenant routes go directly, scoped routes get tenant resolver
|
||||||
@@ -123,7 +135,7 @@ func New(db *sqlx.DB, authMW *auth.Middleware, cfg *config.Config) http.Handler
|
|||||||
|
|
||||||
mux.Handle("/api/", authMW.RequireAuth(api))
|
mux.Handle("/api/", authMW.RequireAuth(api))
|
||||||
|
|
||||||
return mux
|
return requestLogger(mux)
|
||||||
}
|
}
|
||||||
|
|
||||||
func handleHealth(db *sqlx.DB) http.HandlerFunc {
|
func handleHealth(db *sqlx.DB) http.HandlerFunc {
|
||||||
@@ -138,3 +150,34 @@ func handleHealth(db *sqlx.DB) http.HandlerFunc {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type statusWriter struct {
|
||||||
|
http.ResponseWriter
|
||||||
|
status int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *statusWriter) WriteHeader(code int) {
|
||||||
|
w.status = code
|
||||||
|
w.ResponseWriter.WriteHeader(code)
|
||||||
|
}
|
||||||
|
|
||||||
|
func requestLogger(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
// Skip health checks to reduce noise
|
||||||
|
if r.URL.Path == "/health" {
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
sw := &statusWriter{ResponseWriter: w, status: http.StatusOK}
|
||||||
|
start := time.Now()
|
||||||
|
next.ServeHTTP(sw, r)
|
||||||
|
|
||||||
|
slog.Info("request",
|
||||||
|
"method", r.Method,
|
||||||
|
"path", r.URL.Path,
|
||||||
|
"status", sw.status,
|
||||||
|
"duration_ms", time.Since(start).Milliseconds(),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
|||||||
687
backend/internal/services/caldav_service.go
Normal file
687
backend/internal/services/caldav_service.go
Normal file
@@ -0,0 +1,687 @@
|
|||||||
|
package services
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/emersion/go-ical"
|
||||||
|
"github.com/emersion/go-webdav"
|
||||||
|
"github.com/emersion/go-webdav/caldav"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/jmoiron/sqlx"
|
||||||
|
|
||||||
|
"mgit.msbls.de/m/KanzlAI-mGMT/internal/models"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
calDAVDomain = "kanzlai.msbls.de"
|
||||||
|
calDAVProdID = "-//KanzlAI//KanzlAI-mGMT//EN"
|
||||||
|
defaultSyncMin = 15
|
||||||
|
)
|
||||||
|
|
||||||
|
// CalDAVConfig holds per-tenant CalDAV configuration from tenants.settings.
|
||||||
|
type CalDAVConfig struct {
|
||||||
|
URL string `json:"url"`
|
||||||
|
Username string `json:"username"`
|
||||||
|
Password string `json:"password"`
|
||||||
|
CalendarPath string `json:"calendar_path"`
|
||||||
|
SyncEnabled bool `json:"sync_enabled"`
|
||||||
|
SyncIntervalMinutes int `json:"sync_interval_minutes"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// SyncStatus holds the last sync result for a tenant.
|
||||||
|
type SyncStatus struct {
|
||||||
|
TenantID uuid.UUID `json:"tenant_id"`
|
||||||
|
LastSyncAt time.Time `json:"last_sync_at"`
|
||||||
|
ItemsPushed int `json:"items_pushed"`
|
||||||
|
ItemsPulled int `json:"items_pulled"`
|
||||||
|
Errors []string `json:"errors,omitempty"`
|
||||||
|
SyncDuration string `json:"sync_duration"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// CalDAVService handles bidirectional CalDAV synchronization.
|
||||||
|
type CalDAVService struct {
|
||||||
|
db *sqlx.DB
|
||||||
|
|
||||||
|
mu sync.RWMutex
|
||||||
|
statuses map[uuid.UUID]*SyncStatus // per-tenant sync status
|
||||||
|
|
||||||
|
stopCh chan struct{}
|
||||||
|
wg sync.WaitGroup
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewCalDAVService creates a new CalDAV sync service.
|
||||||
|
func NewCalDAVService(db *sqlx.DB) *CalDAVService {
|
||||||
|
return &CalDAVService{
|
||||||
|
db: db,
|
||||||
|
statuses: make(map[uuid.UUID]*SyncStatus),
|
||||||
|
stopCh: make(chan struct{}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetStatus returns the last sync status for a tenant.
|
||||||
|
func (s *CalDAVService) GetStatus(tenantID uuid.UUID) *SyncStatus {
|
||||||
|
s.mu.RLock()
|
||||||
|
defer s.mu.RUnlock()
|
||||||
|
return s.statuses[tenantID]
|
||||||
|
}
|
||||||
|
|
||||||
|
// setStatus stores the sync status for a tenant.
|
||||||
|
func (s *CalDAVService) setStatus(status *SyncStatus) {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
s.statuses[status.TenantID] = status
|
||||||
|
}
|
||||||
|
|
||||||
|
// Start begins the background sync goroutine that polls per-tenant.
|
||||||
|
func (s *CalDAVService) Start() {
|
||||||
|
s.wg.Go(func() {
|
||||||
|
s.backgroundLoop()
|
||||||
|
})
|
||||||
|
slog.Info("CalDAV sync service started")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stop gracefully stops the background sync.
|
||||||
|
func (s *CalDAVService) Stop() {
|
||||||
|
close(s.stopCh)
|
||||||
|
s.wg.Wait()
|
||||||
|
slog.Info("CalDAV sync service stopped")
|
||||||
|
}
|
||||||
|
|
||||||
|
// backgroundLoop polls tenants at their configured interval.
|
||||||
|
func (s *CalDAVService) backgroundLoop() {
|
||||||
|
// Check every minute, but only sync tenants whose interval has elapsed.
|
||||||
|
ticker := time.NewTicker(1 * time.Minute)
|
||||||
|
defer ticker.Stop()
|
||||||
|
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-s.stopCh:
|
||||||
|
return
|
||||||
|
case <-ticker.C:
|
||||||
|
s.syncAllTenants()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// syncAllTenants checks all tenants and syncs those due for a sync.
|
||||||
|
func (s *CalDAVService) syncAllTenants() {
|
||||||
|
configs, err := s.loadAllTenantConfigs()
|
||||||
|
if err != nil {
|
||||||
|
slog.Error("CalDAV: failed to load tenant configs", "error", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
for tenantID, cfg := range configs {
|
||||||
|
if !cfg.SyncEnabled {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
interval := cfg.SyncIntervalMinutes
|
||||||
|
if interval <= 0 {
|
||||||
|
interval = defaultSyncMin
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if enough time has passed since last sync
|
||||||
|
status := s.GetStatus(tenantID)
|
||||||
|
if status != nil && time.Since(status.LastSyncAt) < time.Duration(interval)*time.Minute {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
go func(tid uuid.UUID, c CalDAVConfig) {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
||||||
|
defer cancel()
|
||||||
|
if _, err := s.SyncTenant(ctx, tid, c); err != nil {
|
||||||
|
slog.Error("CalDAV: sync failed", "tenant_id", tid, "error", err)
|
||||||
|
}
|
||||||
|
}(tenantID, cfg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// loadAllTenantConfigs reads CalDAV configs from all tenants.
|
||||||
|
func (s *CalDAVService) loadAllTenantConfigs() (map[uuid.UUID]CalDAVConfig, error) {
|
||||||
|
type row struct {
|
||||||
|
ID uuid.UUID `db:"id"`
|
||||||
|
Settings json.RawMessage `db:"settings"`
|
||||||
|
}
|
||||||
|
var rows []row
|
||||||
|
if err := s.db.Select(&rows, "SELECT id, settings FROM tenants"); err != nil {
|
||||||
|
return nil, fmt.Errorf("querying tenants: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
result := make(map[uuid.UUID]CalDAVConfig)
|
||||||
|
for _, r := range rows {
|
||||||
|
cfg, err := parseCalDAVConfig(r.Settings)
|
||||||
|
if err != nil || cfg.URL == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
result[r.ID] = cfg
|
||||||
|
}
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// LoadTenantConfig reads CalDAV config for a single tenant.
|
||||||
|
func (s *CalDAVService) LoadTenantConfig(tenantID uuid.UUID) (*CalDAVConfig, error) {
|
||||||
|
var settings json.RawMessage
|
||||||
|
if err := s.db.Get(&settings, "SELECT settings FROM tenants WHERE id = $1", tenantID); err != nil {
|
||||||
|
return nil, fmt.Errorf("loading tenant settings: %w", err)
|
||||||
|
}
|
||||||
|
cfg, err := parseCalDAVConfig(settings)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if cfg.URL == "" {
|
||||||
|
return nil, fmt.Errorf("no CalDAV configuration for tenant")
|
||||||
|
}
|
||||||
|
return &cfg, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseCalDAVConfig(settings json.RawMessage) (CalDAVConfig, error) {
|
||||||
|
if len(settings) == 0 {
|
||||||
|
return CalDAVConfig{}, nil
|
||||||
|
}
|
||||||
|
var wrapper struct {
|
||||||
|
CalDAV CalDAVConfig `json:"caldav"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(settings, &wrapper); err != nil {
|
||||||
|
return CalDAVConfig{}, fmt.Errorf("parsing CalDAV settings: %w", err)
|
||||||
|
}
|
||||||
|
return wrapper.CalDAV, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// newCalDAVClient creates a caldav.Client from config.
|
||||||
|
func newCalDAVClient(cfg CalDAVConfig) (*caldav.Client, error) {
|
||||||
|
httpClient := webdav.HTTPClientWithBasicAuth(nil, cfg.Username, cfg.Password)
|
||||||
|
return caldav.NewClient(httpClient, cfg.URL)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SyncTenant performs a full bidirectional sync for a tenant.
|
||||||
|
func (s *CalDAVService) SyncTenant(ctx context.Context, tenantID uuid.UUID, cfg CalDAVConfig) (*SyncStatus, error) {
|
||||||
|
start := time.Now()
|
||||||
|
status := &SyncStatus{
|
||||||
|
TenantID: tenantID,
|
||||||
|
}
|
||||||
|
|
||||||
|
client, err := newCalDAVClient(cfg)
|
||||||
|
if err != nil {
|
||||||
|
status.Errors = append(status.Errors, fmt.Sprintf("creating client: %v", err))
|
||||||
|
status.LastSyncAt = time.Now()
|
||||||
|
s.setStatus(status)
|
||||||
|
return status, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Push local changes to CalDAV
|
||||||
|
pushed, pushErrs := s.pushAll(ctx, client, tenantID, cfg)
|
||||||
|
status.ItemsPushed = pushed
|
||||||
|
status.Errors = append(status.Errors, pushErrs...)
|
||||||
|
|
||||||
|
// Pull remote changes from CalDAV
|
||||||
|
pulled, pullErrs := s.pullAll(ctx, client, tenantID, cfg)
|
||||||
|
status.ItemsPulled = pulled
|
||||||
|
status.Errors = append(status.Errors, pullErrs...)
|
||||||
|
|
||||||
|
status.LastSyncAt = time.Now()
|
||||||
|
status.SyncDuration = time.Since(start).String()
|
||||||
|
s.setStatus(status)
|
||||||
|
|
||||||
|
if len(status.Errors) > 0 {
|
||||||
|
return status, fmt.Errorf("sync completed with %d errors", len(status.Errors))
|
||||||
|
}
|
||||||
|
return status, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Push: Local -> CalDAV ---
|
||||||
|
|
||||||
|
// pushAll pushes all deadlines and appointments to CalDAV.
|
||||||
|
func (s *CalDAVService) pushAll(ctx context.Context, client *caldav.Client, tenantID uuid.UUID, cfg CalDAVConfig) (int, []string) {
|
||||||
|
var pushed int
|
||||||
|
var errs []string
|
||||||
|
|
||||||
|
// Push deadlines as VTODO
|
||||||
|
deadlines, err := s.loadDeadlines(tenantID)
|
||||||
|
if err != nil {
|
||||||
|
return 0, []string{fmt.Sprintf("loading deadlines: %v", err)}
|
||||||
|
}
|
||||||
|
for _, d := range deadlines {
|
||||||
|
if err := s.pushDeadline(ctx, client, cfg, &d); err != nil {
|
||||||
|
errs = append(errs, fmt.Sprintf("push deadline %s: %v", d.ID, err))
|
||||||
|
} else {
|
||||||
|
pushed++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Push appointments as VEVENT
|
||||||
|
appointments, err := s.loadAppointments(ctx, tenantID)
|
||||||
|
if err != nil {
|
||||||
|
errs = append(errs, fmt.Sprintf("loading appointments: %v", err))
|
||||||
|
return pushed, errs
|
||||||
|
}
|
||||||
|
for _, a := range appointments {
|
||||||
|
if err := s.pushAppointment(ctx, client, cfg, &a); err != nil {
|
||||||
|
errs = append(errs, fmt.Sprintf("push appointment %s: %v", a.ID, err))
|
||||||
|
} else {
|
||||||
|
pushed++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return pushed, errs
|
||||||
|
}
|
||||||
|
|
||||||
|
// PushDeadline pushes a single deadline to CalDAV (called on create/update).
|
||||||
|
func (s *CalDAVService) PushDeadline(ctx context.Context, tenantID uuid.UUID, deadline *models.Deadline) error {
|
||||||
|
cfg, err := s.LoadTenantConfig(tenantID)
|
||||||
|
if err != nil || !cfg.SyncEnabled {
|
||||||
|
return nil // CalDAV not configured or disabled — silently skip
|
||||||
|
}
|
||||||
|
client, err := newCalDAVClient(*cfg)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("creating CalDAV client: %w", err)
|
||||||
|
}
|
||||||
|
return s.pushDeadline(ctx, client, *cfg, deadline)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *CalDAVService) pushDeadline(ctx context.Context, client *caldav.Client, cfg CalDAVConfig, d *models.Deadline) error {
|
||||||
|
uid := deadlineUID(d.ID)
|
||||||
|
|
||||||
|
cal := ical.NewCalendar()
|
||||||
|
cal.Props.SetText(ical.PropProductID, calDAVProdID)
|
||||||
|
cal.Props.SetText(ical.PropVersion, "2.0")
|
||||||
|
|
||||||
|
todo := ical.NewComponent(ical.CompToDo)
|
||||||
|
todo.Props.SetText(ical.PropUID, uid)
|
||||||
|
todo.Props.SetText(ical.PropSummary, d.Title)
|
||||||
|
todo.Props.SetDateTime(ical.PropDateTimeStamp, time.Now().UTC())
|
||||||
|
|
||||||
|
if d.Description != nil {
|
||||||
|
todo.Props.SetText(ical.PropDescription, *d.Description)
|
||||||
|
}
|
||||||
|
if d.Notes != nil {
|
||||||
|
desc := ""
|
||||||
|
if d.Description != nil {
|
||||||
|
desc = *d.Description + "\n\n"
|
||||||
|
}
|
||||||
|
todo.Props.SetText(ical.PropDescription, desc+*d.Notes)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse due_date (stored as string "YYYY-MM-DD")
|
||||||
|
if due, err := time.Parse("2006-01-02", d.DueDate); err == nil {
|
||||||
|
todo.Props.SetDate(ical.PropDue, due)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Map status
|
||||||
|
switch d.Status {
|
||||||
|
case "completed":
|
||||||
|
todo.Props.SetText(ical.PropStatus, "COMPLETED")
|
||||||
|
if d.CompletedAt != nil {
|
||||||
|
todo.Props.SetDateTime(ical.PropCompleted, d.CompletedAt.UTC())
|
||||||
|
}
|
||||||
|
case "pending":
|
||||||
|
todo.Props.SetText(ical.PropStatus, "NEEDS-ACTION")
|
||||||
|
default:
|
||||||
|
todo.Props.SetText(ical.PropStatus, "IN-PROCESS")
|
||||||
|
}
|
||||||
|
|
||||||
|
cal.Children = append(cal.Children, todo)
|
||||||
|
|
||||||
|
path := calendarObjectPath(cfg.CalendarPath, uid)
|
||||||
|
obj, err := client.PutCalendarObject(ctx, path, cal)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("putting VTODO: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update caldav_uid and etag in DB
|
||||||
|
return s.updateDeadlineCalDAV(d.ID, uid, obj.ETag)
|
||||||
|
}
|
||||||
|
|
||||||
|
// PushAppointment pushes a single appointment to CalDAV (called on create/update).
|
||||||
|
func (s *CalDAVService) PushAppointment(ctx context.Context, tenantID uuid.UUID, appointment *models.Appointment) error {
|
||||||
|
cfg, err := s.LoadTenantConfig(tenantID)
|
||||||
|
if err != nil || !cfg.SyncEnabled {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
client, err := newCalDAVClient(*cfg)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("creating CalDAV client: %w", err)
|
||||||
|
}
|
||||||
|
return s.pushAppointment(ctx, client, *cfg, appointment)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *CalDAVService) pushAppointment(ctx context.Context, client *caldav.Client, cfg CalDAVConfig, a *models.Appointment) error {
|
||||||
|
uid := appointmentUID(a.ID)
|
||||||
|
|
||||||
|
cal := ical.NewCalendar()
|
||||||
|
cal.Props.SetText(ical.PropProductID, calDAVProdID)
|
||||||
|
cal.Props.SetText(ical.PropVersion, "2.0")
|
||||||
|
|
||||||
|
event := ical.NewEvent()
|
||||||
|
event.Props.SetText(ical.PropUID, uid)
|
||||||
|
event.Props.SetText(ical.PropSummary, a.Title)
|
||||||
|
event.Props.SetDateTime(ical.PropDateTimeStamp, time.Now().UTC())
|
||||||
|
event.Props.SetDateTime(ical.PropDateTimeStart, a.StartAt.UTC())
|
||||||
|
|
||||||
|
if a.EndAt != nil {
|
||||||
|
event.Props.SetDateTime(ical.PropDateTimeEnd, a.EndAt.UTC())
|
||||||
|
}
|
||||||
|
if a.Description != nil {
|
||||||
|
event.Props.SetText(ical.PropDescription, *a.Description)
|
||||||
|
}
|
||||||
|
if a.Location != nil {
|
||||||
|
event.Props.SetText(ical.PropLocation, *a.Location)
|
||||||
|
}
|
||||||
|
|
||||||
|
cal.Children = append(cal.Children, event.Component)
|
||||||
|
|
||||||
|
path := calendarObjectPath(cfg.CalendarPath, uid)
|
||||||
|
obj, err := client.PutCalendarObject(ctx, path, cal)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("putting VEVENT: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return s.updateAppointmentCalDAV(a.ID, uid, obj.ETag)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteDeadlineCalDAV removes a deadline's VTODO from CalDAV.
|
||||||
|
func (s *CalDAVService) DeleteDeadlineCalDAV(ctx context.Context, tenantID uuid.UUID, deadline *models.Deadline) error {
|
||||||
|
if deadline.CalDAVUID == nil || *deadline.CalDAVUID == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
cfg, err := s.LoadTenantConfig(tenantID)
|
||||||
|
if err != nil || !cfg.SyncEnabled {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
client, err := newCalDAVClient(*cfg)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("creating CalDAV client: %w", err)
|
||||||
|
}
|
||||||
|
path := calendarObjectPath(cfg.CalendarPath, *deadline.CalDAVUID)
|
||||||
|
return client.RemoveAll(ctx, path)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteAppointmentCalDAV removes an appointment's VEVENT from CalDAV.
|
||||||
|
func (s *CalDAVService) DeleteAppointmentCalDAV(ctx context.Context, tenantID uuid.UUID, appointment *models.Appointment) error {
|
||||||
|
if appointment.CalDAVUID == nil || *appointment.CalDAVUID == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
cfg, err := s.LoadTenantConfig(tenantID)
|
||||||
|
if err != nil || !cfg.SyncEnabled {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
client, err := newCalDAVClient(*cfg)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("creating CalDAV client: %w", err)
|
||||||
|
}
|
||||||
|
path := calendarObjectPath(cfg.CalendarPath, *appointment.CalDAVUID)
|
||||||
|
return client.RemoveAll(ctx, path)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Pull: CalDAV -> Local ---
|
||||||
|
|
||||||
|
// pullAll fetches all calendar objects from CalDAV and reconciles with local DB.
|
||||||
|
func (s *CalDAVService) pullAll(ctx context.Context, client *caldav.Client, tenantID uuid.UUID, cfg CalDAVConfig) (int, []string) {
|
||||||
|
var pulled int
|
||||||
|
var errs []string
|
||||||
|
|
||||||
|
query := &caldav.CalendarQuery{
|
||||||
|
CompFilter: caldav.CompFilter{
|
||||||
|
Name: ical.CompCalendar,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
objects, err := client.QueryCalendar(ctx, cfg.CalendarPath, query)
|
||||||
|
if err != nil {
|
||||||
|
return 0, []string{fmt.Sprintf("querying calendar: %v", err)}
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, obj := range objects {
|
||||||
|
if obj.Data == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, child := range obj.Data.Children {
|
||||||
|
switch child.Name {
|
||||||
|
case ical.CompToDo:
|
||||||
|
uid, _ := child.Props.Text(ical.PropUID)
|
||||||
|
if uid == "" || !isKanzlAIUID(uid, "deadline") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err := s.reconcileDeadline(ctx, tenantID, child, obj.ETag); err != nil {
|
||||||
|
errs = append(errs, fmt.Sprintf("reconcile deadline %s: %v", uid, err))
|
||||||
|
} else {
|
||||||
|
pulled++
|
||||||
|
}
|
||||||
|
case ical.CompEvent:
|
||||||
|
uid, _ := child.Props.Text(ical.PropUID)
|
||||||
|
if uid == "" || !isKanzlAIUID(uid, "appointment") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err := s.reconcileAppointment(ctx, tenantID, child, obj.ETag); err != nil {
|
||||||
|
errs = append(errs, fmt.Sprintf("reconcile appointment %s: %v", uid, err))
|
||||||
|
} else {
|
||||||
|
pulled++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return pulled, errs
|
||||||
|
}
|
||||||
|
|
||||||
|
// reconcileDeadline handles conflict resolution for a pulled VTODO.
|
||||||
|
// KanzlAI wins for dates/status, CalDAV wins for notes/description.
|
||||||
|
func (s *CalDAVService) reconcileDeadline(ctx context.Context, tenantID uuid.UUID, comp *ical.Component, remoteEtag string) error {
|
||||||
|
uid, _ := comp.Props.Text(ical.PropUID)
|
||||||
|
deadlineID := extractIDFromUID(uid, "deadline")
|
||||||
|
if deadlineID == uuid.Nil {
|
||||||
|
return fmt.Errorf("invalid UID: %s", uid)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Load existing deadline
|
||||||
|
var d models.Deadline
|
||||||
|
err := s.db.Get(&d, `SELECT id, tenant_id, case_id, title, description, due_date, original_due_date,
|
||||||
|
warning_date, source, rule_id, status, completed_at,
|
||||||
|
caldav_uid, caldav_etag, notes, created_at, updated_at
|
||||||
|
FROM deadlines WHERE id = $1 AND tenant_id = $2`, deadlineID, tenantID)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("loading deadline: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if remote changed (etag mismatch)
|
||||||
|
if d.CalDAVEtag != nil && *d.CalDAVEtag == remoteEtag {
|
||||||
|
return nil // No change
|
||||||
|
}
|
||||||
|
|
||||||
|
// CalDAV wins for description/notes
|
||||||
|
description, _ := comp.Props.Text(ical.PropDescription)
|
||||||
|
hasConflict := false
|
||||||
|
|
||||||
|
if description != "" {
|
||||||
|
existingDesc := ""
|
||||||
|
if d.Description != nil {
|
||||||
|
existingDesc = *d.Description
|
||||||
|
}
|
||||||
|
existingNotes := ""
|
||||||
|
if d.Notes != nil {
|
||||||
|
existingNotes = *d.Notes
|
||||||
|
}
|
||||||
|
// CalDAV wins for notes/description
|
||||||
|
if description != existingDesc && description != existingNotes {
|
||||||
|
hasConflict = true
|
||||||
|
_, err = s.db.Exec(`UPDATE deadlines SET notes = $1, caldav_etag = $2, updated_at = NOW()
|
||||||
|
WHERE id = $3 AND tenant_id = $4`, description, remoteEtag, deadlineID, tenantID)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("updating deadline notes: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !hasConflict {
|
||||||
|
// Just update etag
|
||||||
|
_, err = s.db.Exec(`UPDATE deadlines SET caldav_etag = $1, updated_at = NOW()
|
||||||
|
WHERE id = $2 AND tenant_id = $3`, remoteEtag, deadlineID, tenantID)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("updating deadline etag: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Log conflict in case_events if detected
|
||||||
|
if hasConflict {
|
||||||
|
s.logConflictEvent(ctx, tenantID, d.CaseID, "deadline", deadlineID, "CalDAV description updated from remote")
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// reconcileAppointment handles conflict resolution for a pulled VEVENT.
|
||||||
|
func (s *CalDAVService) reconcileAppointment(ctx context.Context, tenantID uuid.UUID, comp *ical.Component, remoteEtag string) error {
|
||||||
|
uid, _ := comp.Props.Text(ical.PropUID)
|
||||||
|
appointmentID := extractIDFromUID(uid, "appointment")
|
||||||
|
if appointmentID == uuid.Nil {
|
||||||
|
return fmt.Errorf("invalid UID: %s", uid)
|
||||||
|
}
|
||||||
|
|
||||||
|
var a models.Appointment
|
||||||
|
err := s.db.GetContext(ctx, &a, `SELECT * FROM appointments WHERE id = $1 AND tenant_id = $2`, appointmentID, tenantID)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("loading appointment: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if a.CalDAVEtag != nil && *a.CalDAVEtag == remoteEtag {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// CalDAV wins for description
|
||||||
|
description, _ := comp.Props.Text(ical.PropDescription)
|
||||||
|
location, _ := comp.Props.Text(ical.PropLocation)
|
||||||
|
hasConflict := false
|
||||||
|
|
||||||
|
updates := []string{"caldav_etag = $1", "updated_at = NOW()"}
|
||||||
|
args := []any{remoteEtag}
|
||||||
|
argN := 2
|
||||||
|
|
||||||
|
if description != "" {
|
||||||
|
existingDesc := ""
|
||||||
|
if a.Description != nil {
|
||||||
|
existingDesc = *a.Description
|
||||||
|
}
|
||||||
|
if description != existingDesc {
|
||||||
|
hasConflict = true
|
||||||
|
updates = append(updates, fmt.Sprintf("description = $%d", argN))
|
||||||
|
args = append(args, description)
|
||||||
|
argN++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if location != "" {
|
||||||
|
existingLoc := ""
|
||||||
|
if a.Location != nil {
|
||||||
|
existingLoc = *a.Location
|
||||||
|
}
|
||||||
|
if location != existingLoc {
|
||||||
|
hasConflict = true
|
||||||
|
updates = append(updates, fmt.Sprintf("location = $%d", argN))
|
||||||
|
args = append(args, location)
|
||||||
|
argN++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
args = append(args, appointmentID, tenantID)
|
||||||
|
query := fmt.Sprintf("UPDATE appointments SET %s WHERE id = $%d AND tenant_id = $%d",
|
||||||
|
strings.Join(updates, ", "), argN, argN+1)
|
||||||
|
|
||||||
|
if _, err := s.db.ExecContext(ctx, query, args...); err != nil {
|
||||||
|
return fmt.Errorf("updating appointment: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if hasConflict {
|
||||||
|
caseID := uuid.Nil
|
||||||
|
if a.CaseID != nil {
|
||||||
|
caseID = *a.CaseID
|
||||||
|
}
|
||||||
|
s.logConflictEvent(ctx, tenantID, caseID, "appointment", appointmentID, "CalDAV description/location updated from remote")
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- DB helpers ---
|
||||||
|
|
||||||
|
func (s *CalDAVService) loadDeadlines(tenantID uuid.UUID) ([]models.Deadline, error) {
|
||||||
|
var deadlines []models.Deadline
|
||||||
|
err := s.db.Select(&deadlines, `SELECT id, tenant_id, case_id, title, description, due_date,
|
||||||
|
original_due_date, warning_date, source, rule_id, status, completed_at,
|
||||||
|
caldav_uid, caldav_etag, notes, created_at, updated_at
|
||||||
|
FROM deadlines WHERE tenant_id = $1`, tenantID)
|
||||||
|
return deadlines, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *CalDAVService) loadAppointments(ctx context.Context, tenantID uuid.UUID) ([]models.Appointment, error) {
|
||||||
|
var appointments []models.Appointment
|
||||||
|
err := s.db.SelectContext(ctx, &appointments, "SELECT * FROM appointments WHERE tenant_id = $1", tenantID)
|
||||||
|
return appointments, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *CalDAVService) updateDeadlineCalDAV(id uuid.UUID, calDAVUID, etag string) error {
|
||||||
|
_, err := s.db.Exec(`UPDATE deadlines SET caldav_uid = $1, caldav_etag = $2, updated_at = NOW()
|
||||||
|
WHERE id = $3`, calDAVUID, etag, id)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *CalDAVService) updateAppointmentCalDAV(id uuid.UUID, calDAVUID, etag string) error {
|
||||||
|
_, err := s.db.Exec(`UPDATE appointments SET caldav_uid = $1, caldav_etag = $2, updated_at = NOW()
|
||||||
|
WHERE id = $3`, calDAVUID, etag, id)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *CalDAVService) logConflictEvent(ctx context.Context, tenantID, caseID uuid.UUID, objectType string, objectID uuid.UUID, msg string) {
|
||||||
|
if caseID == uuid.Nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
metadata, _ := json.Marshal(map[string]string{
|
||||||
|
"object_type": objectType,
|
||||||
|
"object_id": objectID.String(),
|
||||||
|
"source": "caldav_sync",
|
||||||
|
})
|
||||||
|
_, err := s.db.ExecContext(ctx, `INSERT INTO case_events (id, tenant_id, case_id, event_type, title, description, metadata, created_at, updated_at)
|
||||||
|
VALUES ($1, $2, $3, 'caldav_conflict', $4, $5, $6, NOW(), NOW())`,
|
||||||
|
uuid.New(), tenantID, caseID, "CalDAV sync conflict", msg, metadata)
|
||||||
|
if err != nil {
|
||||||
|
slog.Error("CalDAV: failed to log conflict event", "error", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- UID helpers ---
|
||||||
|
|
||||||
|
func deadlineUID(id uuid.UUID) string {
|
||||||
|
return fmt.Sprintf("kanzlai-deadline-%s@%s", id, calDAVDomain)
|
||||||
|
}
|
||||||
|
|
||||||
|
func appointmentUID(id uuid.UUID) string {
|
||||||
|
return fmt.Sprintf("kanzlai-appointment-%s@%s", id, calDAVDomain)
|
||||||
|
}
|
||||||
|
|
||||||
|
func isKanzlAIUID(uid, objectType string) bool {
|
||||||
|
return strings.HasPrefix(uid, "kanzlai-"+objectType+"-") && strings.HasSuffix(uid, "@"+calDAVDomain)
|
||||||
|
}
|
||||||
|
|
||||||
|
func extractIDFromUID(uid, objectType string) uuid.UUID {
|
||||||
|
prefix := "kanzlai-" + objectType + "-"
|
||||||
|
suffix := "@" + calDAVDomain
|
||||||
|
if !strings.HasPrefix(uid, prefix) || !strings.HasSuffix(uid, suffix) {
|
||||||
|
return uuid.Nil
|
||||||
|
}
|
||||||
|
idStr := uid[len(prefix) : len(uid)-len(suffix)]
|
||||||
|
id, err := uuid.Parse(idStr)
|
||||||
|
if err != nil {
|
||||||
|
return uuid.Nil
|
||||||
|
}
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
|
||||||
|
func calendarObjectPath(calendarPath, uid string) string {
|
||||||
|
path := strings.TrimSuffix(calendarPath, "/")
|
||||||
|
return path + "/" + uid + ".ics"
|
||||||
|
}
|
||||||
124
backend/internal/services/caldav_service_test.go
Normal file
124
backend/internal/services/caldav_service_test.go
Normal file
@@ -0,0 +1,124 @@
|
|||||||
|
package services
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestDeadlineUID(t *testing.T) {
|
||||||
|
id := uuid.MustParse("550e8400-e29b-41d4-a716-446655440000")
|
||||||
|
uid := deadlineUID(id)
|
||||||
|
want := "kanzlai-deadline-550e8400-e29b-41d4-a716-446655440000@kanzlai.msbls.de"
|
||||||
|
if uid != want {
|
||||||
|
t.Errorf("deadlineUID = %q, want %q", uid, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAppointmentUID(t *testing.T) {
|
||||||
|
id := uuid.MustParse("550e8400-e29b-41d4-a716-446655440000")
|
||||||
|
uid := appointmentUID(id)
|
||||||
|
want := "kanzlai-appointment-550e8400-e29b-41d4-a716-446655440000@kanzlai.msbls.de"
|
||||||
|
if uid != want {
|
||||||
|
t.Errorf("appointmentUID = %q, want %q", uid, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestIsKanzlAIUID(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
uid string
|
||||||
|
objectType string
|
||||||
|
want bool
|
||||||
|
}{
|
||||||
|
{"kanzlai-deadline-550e8400-e29b-41d4-a716-446655440000@kanzlai.msbls.de", "deadline", true},
|
||||||
|
{"kanzlai-appointment-550e8400-e29b-41d4-a716-446655440000@kanzlai.msbls.de", "appointment", true},
|
||||||
|
{"kanzlai-deadline-550e8400-e29b-41d4-a716-446655440000@kanzlai.msbls.de", "appointment", false},
|
||||||
|
{"random-uid@other.com", "deadline", false},
|
||||||
|
{"", "deadline", false},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
got := isKanzlAIUID(tt.uid, tt.objectType)
|
||||||
|
if got != tt.want {
|
||||||
|
t.Errorf("isKanzlAIUID(%q, %q) = %v, want %v", tt.uid, tt.objectType, got, tt.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExtractIDFromUID(t *testing.T) {
|
||||||
|
id := uuid.MustParse("550e8400-e29b-41d4-a716-446655440000")
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
uid string
|
||||||
|
objectType string
|
||||||
|
want uuid.UUID
|
||||||
|
}{
|
||||||
|
{"kanzlai-deadline-550e8400-e29b-41d4-a716-446655440000@kanzlai.msbls.de", "deadline", id},
|
||||||
|
{"kanzlai-appointment-550e8400-e29b-41d4-a716-446655440000@kanzlai.msbls.de", "appointment", id},
|
||||||
|
{"invalid-uid", "deadline", uuid.Nil},
|
||||||
|
{"kanzlai-deadline-not-a-uuid@kanzlai.msbls.de", "deadline", uuid.Nil},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
got := extractIDFromUID(tt.uid, tt.objectType)
|
||||||
|
if got != tt.want {
|
||||||
|
t.Errorf("extractIDFromUID(%q, %q) = %v, want %v", tt.uid, tt.objectType, got, tt.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCalendarObjectPath(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
calendarPath string
|
||||||
|
uid string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{"/dav/calendars/user/cal", "kanzlai-deadline-abc@kanzlai.msbls.de", "/dav/calendars/user/cal/kanzlai-deadline-abc@kanzlai.msbls.de.ics"},
|
||||||
|
{"/dav/calendars/user/cal/", "kanzlai-deadline-abc@kanzlai.msbls.de", "/dav/calendars/user/cal/kanzlai-deadline-abc@kanzlai.msbls.de.ics"},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
got := calendarObjectPath(tt.calendarPath, tt.uid)
|
||||||
|
if got != tt.want {
|
||||||
|
t.Errorf("calendarObjectPath(%q, %q) = %q, want %q", tt.calendarPath, tt.uid, got, tt.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseCalDAVConfig(t *testing.T) {
|
||||||
|
settings := []byte(`{"caldav": {"url": "https://dav.example.com", "username": "user", "password": "pass", "calendar_path": "/cal", "sync_enabled": true, "sync_interval_minutes": 30}}`)
|
||||||
|
cfg, err := parseCalDAVConfig(settings)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("parseCalDAVConfig: %v", err)
|
||||||
|
}
|
||||||
|
if cfg.URL != "https://dav.example.com" {
|
||||||
|
t.Errorf("URL = %q, want %q", cfg.URL, "https://dav.example.com")
|
||||||
|
}
|
||||||
|
if cfg.Username != "user" {
|
||||||
|
t.Errorf("Username = %q, want %q", cfg.Username, "user")
|
||||||
|
}
|
||||||
|
if cfg.SyncIntervalMinutes != 30 {
|
||||||
|
t.Errorf("SyncIntervalMinutes = %d, want 30", cfg.SyncIntervalMinutes)
|
||||||
|
}
|
||||||
|
if !cfg.SyncEnabled {
|
||||||
|
t.Error("SyncEnabled = false, want true")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseCalDAVConfig_Empty(t *testing.T) {
|
||||||
|
cfg, err := parseCalDAVConfig(nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("parseCalDAVConfig(nil): %v", err)
|
||||||
|
}
|
||||||
|
if cfg.URL != "" {
|
||||||
|
t.Errorf("expected empty config, got URL=%q", cfg.URL)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseCalDAVConfig_NoCalDAV(t *testing.T) {
|
||||||
|
settings := []byte(`{"other_setting": true}`)
|
||||||
|
cfg, err := parseCalDAVConfig(settings)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("parseCalDAVConfig: %v", err)
|
||||||
|
}
|
||||||
|
if cfg.URL != "" {
|
||||||
|
t.Errorf("expected empty caldav config, got URL=%q", cfg.URL)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ package services
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"database/sql"
|
"database/sql"
|
||||||
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
@@ -173,6 +174,21 @@ func (s *TenantService) InviteByEmail(ctx context.Context, tenantID uuid.UUID, e
|
|||||||
return &ut, nil
|
return &ut, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// UpdateSettings merges new settings into the tenant's existing settings JSONB.
|
||||||
|
func (s *TenantService) UpdateSettings(ctx context.Context, tenantID uuid.UUID, settings json.RawMessage) (*models.Tenant, error) {
|
||||||
|
var tenant models.Tenant
|
||||||
|
err := s.db.QueryRowxContext(ctx,
|
||||||
|
`UPDATE tenants SET settings = COALESCE(settings, '{}'::jsonb) || $1::jsonb, updated_at = NOW()
|
||||||
|
WHERE id = $2
|
||||||
|
RETURNING id, name, slug, settings, created_at, updated_at`,
|
||||||
|
settings, tenantID,
|
||||||
|
).StructScan(&tenant)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("update settings: %w", err)
|
||||||
|
}
|
||||||
|
return &tenant, nil
|
||||||
|
}
|
||||||
|
|
||||||
// RemoveMember removes a user from a tenant. Cannot remove the last owner.
|
// RemoveMember removes a user from a tenant. Cannot remove the last owner.
|
||||||
func (s *TenantService) RemoveMember(ctx context.Context, tenantID, userID uuid.UUID) error {
|
func (s *TenantService) RemoveMember(ctx context.Context, tenantID, userID uuid.UUID) error {
|
||||||
// Check if the user being removed is an owner
|
// Check if the user being removed is an owner
|
||||||
|
|||||||
167
backend/seed/demo_data.sql
Normal file
167
backend/seed/demo_data.sql
Normal file
@@ -0,0 +1,167 @@
|
|||||||
|
-- KanzlAI Demo Data
|
||||||
|
-- Creates 1 test tenant, 5 cases with deadlines and appointments
|
||||||
|
-- Run with: psql $DATABASE_URL -f demo_data.sql
|
||||||
|
|
||||||
|
SET search_path TO kanzlai, public;
|
||||||
|
|
||||||
|
-- Demo tenant
|
||||||
|
INSERT INTO tenants (id, name, slug, settings) VALUES
|
||||||
|
('a0000000-0000-0000-0000-000000000001', 'Kanzlei Siebels & Partner', 'siebels-partner', '{}')
|
||||||
|
ON CONFLICT (id) DO NOTHING;
|
||||||
|
|
||||||
|
-- Link both users to the demo tenant
|
||||||
|
INSERT INTO user_tenants (user_id, tenant_id, role) VALUES
|
||||||
|
('1da9374d-a8a6-49fc-a2ec-5ddfa91d522d', 'a0000000-0000-0000-0000-000000000001', 'owner'),
|
||||||
|
('ac6c9501-3757-4a6d-8b97-2cff4288382b', 'a0000000-0000-0000-0000-000000000001', 'member')
|
||||||
|
ON CONFLICT DO NOTHING;
|
||||||
|
|
||||||
|
-- ============================================================
|
||||||
|
-- Case 1: Patentverletzung (patent infringement) — active
|
||||||
|
-- ============================================================
|
||||||
|
INSERT INTO cases (id, tenant_id, case_number, title, case_type, court, court_ref, status) VALUES
|
||||||
|
('c0000000-0000-0000-0000-000000000001',
|
||||||
|
'a0000000-0000-0000-0000-000000000001',
|
||||||
|
'2026/001', 'TechCorp GmbH ./. InnovatAG — Patentverletzung EP 1234567',
|
||||||
|
'patent', 'UPC München (Lokalkammer)', 'UPC_CFI-123/2026',
|
||||||
|
'active');
|
||||||
|
|
||||||
|
INSERT INTO parties (id, tenant_id, case_id, name, role, representative) VALUES
|
||||||
|
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000001',
|
||||||
|
'TechCorp GmbH', 'claimant', 'RA Dr. Siebels'),
|
||||||
|
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000001',
|
||||||
|
'InnovatAG', 'defendant', 'RA Müller');
|
||||||
|
|
||||||
|
INSERT INTO deadlines (id, tenant_id, case_id, title, due_date, warning_date, status, source) VALUES
|
||||||
|
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000001',
|
||||||
|
'Klageerwiderung einreichen', CURRENT_DATE + INTERVAL '3 days', CURRENT_DATE + INTERVAL '1 day', 'pending', 'manual'),
|
||||||
|
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000001',
|
||||||
|
'Beweisangebote nachreichen', CURRENT_DATE + INTERVAL '14 days', CURRENT_DATE + INTERVAL '10 days', 'pending', 'manual'),
|
||||||
|
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000001',
|
||||||
|
'Schriftsatz Anspruch 3', CURRENT_DATE - INTERVAL '2 days', CURRENT_DATE - INTERVAL '5 days', 'pending', 'manual');
|
||||||
|
|
||||||
|
INSERT INTO appointments (id, tenant_id, case_id, title, start_at, end_at, location, appointment_type) VALUES
|
||||||
|
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000001',
|
||||||
|
'Mündliche Verhandlung', CURRENT_DATE + INTERVAL '21 days' + TIME '10:00', CURRENT_DATE + INTERVAL '21 days' + TIME '12:00',
|
||||||
|
'UPC München, Saal 4', 'hearing');
|
||||||
|
|
||||||
|
-- ============================================================
|
||||||
|
-- Case 2: Markenrecht (trademark) — active
|
||||||
|
-- ============================================================
|
||||||
|
INSERT INTO cases (id, tenant_id, case_number, title, case_type, court, court_ref, status) VALUES
|
||||||
|
('c0000000-0000-0000-0000-000000000002',
|
||||||
|
'a0000000-0000-0000-0000-000000000001',
|
||||||
|
'2026/002', 'BrandHouse ./. CopyShop UG — Markenverletzung DE 30201234',
|
||||||
|
'trademark', 'LG Hamburg', '315 O 78/26',
|
||||||
|
'active');
|
||||||
|
|
||||||
|
INSERT INTO parties (id, tenant_id, case_id, name, role, representative) VALUES
|
||||||
|
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000002',
|
||||||
|
'BrandHouse SE', 'claimant', 'RA Dr. Siebels'),
|
||||||
|
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000002',
|
||||||
|
'CopyShop UG', 'defendant', 'RA Weber');
|
||||||
|
|
||||||
|
INSERT INTO deadlines (id, tenant_id, case_id, title, due_date, warning_date, status, source) VALUES
|
||||||
|
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000002',
|
||||||
|
'Antrag einstweilige Verfügung', CURRENT_DATE + INTERVAL '5 days', CURRENT_DATE + INTERVAL '2 days', 'pending', 'manual'),
|
||||||
|
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000002',
|
||||||
|
'Abmahnung Fristablauf', CURRENT_DATE + INTERVAL '30 days', CURRENT_DATE + INTERVAL '25 days', 'pending', 'manual');
|
||||||
|
|
||||||
|
INSERT INTO appointments (id, tenant_id, case_id, title, start_at, end_at, location, appointment_type) VALUES
|
||||||
|
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000002',
|
||||||
|
'Mandantenbesprechung BrandHouse', CURRENT_DATE + INTERVAL '2 days' + TIME '14:00', CURRENT_DATE + INTERVAL '2 days' + TIME '15:30',
|
||||||
|
'Kanzlei, Besprechungsraum 1', 'consultation');
|
||||||
|
|
||||||
|
-- ============================================================
|
||||||
|
-- Case 3: Arbeitsgericht (labor law) — active
|
||||||
|
-- ============================================================
|
||||||
|
INSERT INTO cases (id, tenant_id, case_number, title, case_type, court, court_ref, status) VALUES
|
||||||
|
('c0000000-0000-0000-0000-000000000003',
|
||||||
|
'a0000000-0000-0000-0000-000000000001',
|
||||||
|
'2026/003', 'Schmidt ./. AutoWerk Bayern GmbH — Kündigungsschutz',
|
||||||
|
'labor', 'ArbG München', '12 Ca 456/26',
|
||||||
|
'active');
|
||||||
|
|
||||||
|
INSERT INTO parties (id, tenant_id, case_id, name, role, representative) VALUES
|
||||||
|
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000003',
|
||||||
|
'Klaus Schmidt', 'claimant', 'RA Dr. Siebels'),
|
||||||
|
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000003',
|
||||||
|
'AutoWerk Bayern GmbH', 'defendant', 'RA Fischer');
|
||||||
|
|
||||||
|
INSERT INTO deadlines (id, tenant_id, case_id, title, due_date, warning_date, status, source) VALUES
|
||||||
|
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000003',
|
||||||
|
'Kündigungsschutzklage einreichen (3-Wochen-Frist)', CURRENT_DATE + INTERVAL '7 days', CURRENT_DATE + INTERVAL '4 days', 'pending', 'manual'),
|
||||||
|
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000003',
|
||||||
|
'Stellungnahme Arbeitgeber', CURRENT_DATE + INTERVAL '28 days', CURRENT_DATE + INTERVAL '21 days', 'pending', 'manual');
|
||||||
|
|
||||||
|
INSERT INTO appointments (id, tenant_id, case_id, title, start_at, end_at, location, appointment_type) VALUES
|
||||||
|
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000003',
|
||||||
|
'Güteverhandlung', CURRENT_DATE + INTERVAL '35 days' + TIME '09:00', CURRENT_DATE + INTERVAL '35 days' + TIME '10:00',
|
||||||
|
'ArbG München, Saal 12', 'hearing');
|
||||||
|
|
||||||
|
-- ============================================================
|
||||||
|
-- Case 4: Mietrecht (tenancy) — active
|
||||||
|
-- ============================================================
|
||||||
|
INSERT INTO cases (id, tenant_id, case_number, title, case_type, court, court_ref, status) VALUES
|
||||||
|
('c0000000-0000-0000-0000-000000000004',
|
||||||
|
'a0000000-0000-0000-0000-000000000001',
|
||||||
|
'2026/004', 'Hausverwaltung Zentral ./. Meier — Mietrückstand',
|
||||||
|
'civil', 'AG München', '432 C 1234/26',
|
||||||
|
'active');
|
||||||
|
|
||||||
|
INSERT INTO parties (id, tenant_id, case_id, name, role, representative) VALUES
|
||||||
|
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000004',
|
||||||
|
'Hausverwaltung Zentral GmbH', 'claimant', 'RA Dr. Siebels'),
|
||||||
|
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000004',
|
||||||
|
'Thomas Meier', 'defendant', NULL);
|
||||||
|
|
||||||
|
INSERT INTO deadlines (id, tenant_id, case_id, title, due_date, warning_date, status, source) VALUES
|
||||||
|
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000004',
|
||||||
|
'Mahnbescheid beantragen', CURRENT_DATE + INTERVAL '10 days', CURRENT_DATE + INTERVAL '7 days', 'pending', 'manual'),
|
||||||
|
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000004',
|
||||||
|
'Räumungsfrist prüfen', CURRENT_DATE + INTERVAL '60 days', CURRENT_DATE + INTERVAL '50 days', 'pending', 'manual');
|
||||||
|
|
||||||
|
INSERT INTO appointments (id, tenant_id, case_id, title, start_at, end_at, location, appointment_type) VALUES
|
||||||
|
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000004',
|
||||||
|
'Besprechung Hausverwaltung', CURRENT_DATE + INTERVAL '4 days' + TIME '11:00', CURRENT_DATE + INTERVAL '4 days' + TIME '12:00',
|
||||||
|
'Kanzlei, Besprechungsraum 2', 'meeting');
|
||||||
|
|
||||||
|
-- ============================================================
|
||||||
|
-- Case 5: Erbrecht (inheritance) — closed
|
||||||
|
-- ============================================================
|
||||||
|
INSERT INTO cases (id, tenant_id, case_number, title, case_type, court, court_ref, status) VALUES
|
||||||
|
('c0000000-0000-0000-0000-000000000005',
|
||||||
|
'a0000000-0000-0000-0000-000000000001',
|
||||||
|
'2025/042', 'Nachlass Wagner — Erbauseinandersetzung',
|
||||||
|
'civil', 'AG Starnberg', '3 VI 891/25',
|
||||||
|
'closed');
|
||||||
|
|
||||||
|
INSERT INTO parties (id, tenant_id, case_id, name, role, representative) VALUES
|
||||||
|
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000005',
|
||||||
|
'Maria Wagner', 'claimant', 'RA Dr. Siebels'),
|
||||||
|
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000005',
|
||||||
|
'Peter Wagner', 'defendant', 'RA Braun');
|
||||||
|
|
||||||
|
INSERT INTO deadlines (id, tenant_id, case_id, title, due_date, warning_date, status, source, completed_at) VALUES
|
||||||
|
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000005',
|
||||||
|
'Erbscheinsantrag einreichen', CURRENT_DATE - INTERVAL '30 days', CURRENT_DATE - INTERVAL '37 days', 'completed', 'manual', CURRENT_DATE - INTERVAL '32 days');
|
||||||
|
|
||||||
|
-- ============================================================
|
||||||
|
-- Case events for realistic activity feed
|
||||||
|
-- ============================================================
|
||||||
|
INSERT INTO case_events (id, tenant_id, case_id, event_type, title, description, created_at, updated_at) VALUES
|
||||||
|
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000001',
|
||||||
|
'case_created', 'Akte angelegt', 'Patentverletzungsklage TechCorp ./. InnovatAG eröffnet', NOW() - INTERVAL '10 days', NOW() - INTERVAL '10 days'),
|
||||||
|
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000001',
|
||||||
|
'party_added', 'Partei hinzugefügt', 'TechCorp GmbH als Kläger eingetragen', NOW() - INTERVAL '10 days', NOW() - INTERVAL '10 days'),
|
||||||
|
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000002',
|
||||||
|
'case_created', 'Akte angelegt', 'Markenrechtsstreit BrandHouse ./. CopyShop eröffnet', NOW() - INTERVAL '7 days', NOW() - INTERVAL '7 days'),
|
||||||
|
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000003',
|
||||||
|
'case_created', 'Akte angelegt', 'Kündigungsschutzklage Schmidt eröffnet', NOW() - INTERVAL '5 days', NOW() - INTERVAL '5 days'),
|
||||||
|
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000004',
|
||||||
|
'case_created', 'Akte angelegt', 'Mietrückstand Hausverwaltung ./. Meier eröffnet', NOW() - INTERVAL '3 days', NOW() - INTERVAL '3 days'),
|
||||||
|
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000001',
|
||||||
|
'status_changed', 'Fristablauf überschritten', 'Schriftsatz Anspruch 3 ist überfällig', NOW() - INTERVAL '1 day', NOW() - INTERVAL '1 day'),
|
||||||
|
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000005',
|
||||||
|
'case_created', 'Akte angelegt', 'Erbauseinandersetzung Wagner eröffnet', NOW() - INTERVAL '60 days', NOW() - INTERVAL '60 days'),
|
||||||
|
(gen_random_uuid(), 'a0000000-0000-0000-0000-000000000001', 'c0000000-0000-0000-0000-000000000005',
|
||||||
|
'status_changed', 'Akte geschlossen', 'Erbscheinsverfahren abgeschlossen', NOW() - INTERVAL '20 days', NOW() - INTERVAL '20 days');
|
||||||
@@ -6,6 +6,12 @@ services:
|
|||||||
- "8080"
|
- "8080"
|
||||||
environment:
|
environment:
|
||||||
- PORT=8080
|
- PORT=8080
|
||||||
|
- DATABASE_URL=${DATABASE_URL}
|
||||||
|
- SUPABASE_URL=${SUPABASE_URL}
|
||||||
|
- SUPABASE_ANON_KEY=${SUPABASE_ANON_KEY}
|
||||||
|
- SUPABASE_SERVICE_KEY=${SUPABASE_SERVICE_KEY}
|
||||||
|
- SUPABASE_JWT_SECRET=${SUPABASE_JWT_SECRET}
|
||||||
|
- ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY}
|
||||||
healthcheck:
|
healthcheck:
|
||||||
test: ["CMD", "wget", "--spider", "-q", "http://localhost:8080/health"]
|
test: ["CMD", "wget", "--spider", "-q", "http://localhost:8080/health"]
|
||||||
interval: 30s
|
interval: 30s
|
||||||
@@ -16,6 +22,9 @@ services:
|
|||||||
frontend:
|
frontend:
|
||||||
build:
|
build:
|
||||||
context: ./frontend
|
context: ./frontend
|
||||||
|
args:
|
||||||
|
NEXT_PUBLIC_SUPABASE_URL: ${SUPABASE_URL}
|
||||||
|
NEXT_PUBLIC_SUPABASE_ANON_KEY: ${SUPABASE_ANON_KEY}
|
||||||
expose:
|
expose:
|
||||||
- "3000"
|
- "3000"
|
||||||
depends_on:
|
depends_on:
|
||||||
@@ -23,6 +32,8 @@ services:
|
|||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
environment:
|
environment:
|
||||||
- API_URL=http://backend:8080
|
- API_URL=http://backend:8080
|
||||||
|
- NEXT_PUBLIC_SUPABASE_URL=${SUPABASE_URL}
|
||||||
|
- NEXT_PUBLIC_SUPABASE_ANON_KEY=${SUPABASE_ANON_KEY}
|
||||||
healthcheck:
|
healthcheck:
|
||||||
test: ["CMD", "node", "-e", "fetch('http://localhost:3000').then(r=>{if(!r.ok)throw r.status;process.exit(0)}).catch(()=>process.exit(1))"]
|
test: ["CMD", "node", "-e", "fetch('http://localhost:3000').then(r=>{if(!r.ok)throw r.status;process.exit(0)}).catch(()=>process.exit(1))"]
|
||||||
interval: 30s
|
interval: 30s
|
||||||
|
|||||||
@@ -10,6 +10,10 @@ WORKDIR /app
|
|||||||
COPY --from=deps /app/node_modules ./node_modules
|
COPY --from=deps /app/node_modules ./node_modules
|
||||||
COPY . .
|
COPY . .
|
||||||
ENV API_URL=http://backend:8080
|
ENV API_URL=http://backend:8080
|
||||||
|
ARG NEXT_PUBLIC_SUPABASE_URL
|
||||||
|
ARG NEXT_PUBLIC_SUPABASE_ANON_KEY
|
||||||
|
ENV NEXT_PUBLIC_SUPABASE_URL=$NEXT_PUBLIC_SUPABASE_URL
|
||||||
|
ENV NEXT_PUBLIC_SUPABASE_ANON_KEY=$NEXT_PUBLIC_SUPABASE_ANON_KEY
|
||||||
RUN mkdir -p public
|
RUN mkdir -p public
|
||||||
RUN bun run build
|
RUN bun run build
|
||||||
|
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ const nextConfig: NextConfig = {
|
|||||||
rewrites: async () => [
|
rewrites: async () => [
|
||||||
{
|
{
|
||||||
source: "/api/:path*",
|
source: "/api/:path*",
|
||||||
destination: `${process.env.API_URL || "http://localhost:8080"}/:path*`,
|
destination: `${process.env.API_URL || "http://localhost:8080"}/api/:path*`,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ export default function AIExtractPage() {
|
|||||||
|
|
||||||
const { data: casesData } = useQuery({
|
const { data: casesData } = useQuery({
|
||||||
queryKey: ["cases"],
|
queryKey: ["cases"],
|
||||||
queryFn: () => api.get<PaginatedResponse<Case>>("/api/cases"),
|
queryFn: () => api.get<PaginatedResponse<Case>>("/cases"),
|
||||||
});
|
});
|
||||||
|
|
||||||
const cases = casesData?.data ?? [];
|
const cases = casesData?.data ?? [];
|
||||||
@@ -40,12 +40,12 @@ export default function AIExtractPage() {
|
|||||||
const formData = new FormData();
|
const formData = new FormData();
|
||||||
formData.append("file", file);
|
formData.append("file", file);
|
||||||
response = await api.postFormData<ExtractionResponse>(
|
response = await api.postFormData<ExtractionResponse>(
|
||||||
"/api/ai/extract-deadlines",
|
"/ai/extract-deadlines",
|
||||||
formData,
|
formData,
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
response = await api.post<ExtractionResponse>(
|
response = await api.post<ExtractionResponse>(
|
||||||
"/api/ai/extract-deadlines",
|
"/ai/extract-deadlines",
|
||||||
{ text },
|
{ text },
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -74,7 +74,7 @@ export default function AIExtractPage() {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
const promises = deadlines.map((d) =>
|
const promises = deadlines.map((d) =>
|
||||||
api.post(`/api/cases/${selectedCaseId}/deadlines`, {
|
api.post(`/cases/${selectedCaseId}/deadlines`, {
|
||||||
title: d.title,
|
title: d.title,
|
||||||
due_date: d.due_date ?? "",
|
due_date: d.due_date ?? "",
|
||||||
source: "ai_extraction",
|
source: "ai_extraction",
|
||||||
|
|||||||
116
frontend/src/app/(app)/einstellungen/page.tsx
Normal file
116
frontend/src/app/(app)/einstellungen/page.tsx
Normal file
@@ -0,0 +1,116 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
import { Settings, Calendar, Users } from "lucide-react";
|
||||||
|
import Link from "next/link";
|
||||||
|
import { api } from "@/lib/api";
|
||||||
|
import type { Tenant } from "@/lib/types";
|
||||||
|
import { CalDAVSettings } from "@/components/settings/CalDAVSettings";
|
||||||
|
import { SkeletonCard } from "@/components/ui/Skeleton";
|
||||||
|
import { EmptyState } from "@/components/ui/EmptyState";
|
||||||
|
|
||||||
|
export default function EinstellungenPage() {
|
||||||
|
const tenantId =
|
||||||
|
typeof window !== "undefined"
|
||||||
|
? localStorage.getItem("kanzlai_tenant_id")
|
||||||
|
: null;
|
||||||
|
|
||||||
|
const {
|
||||||
|
data: tenant,
|
||||||
|
isLoading,
|
||||||
|
error,
|
||||||
|
refetch,
|
||||||
|
} = useQuery({
|
||||||
|
queryKey: ["tenant-current", tenantId],
|
||||||
|
queryFn: () => api.get<Tenant>(`/api/tenants/${tenantId}`),
|
||||||
|
enabled: !!tenantId,
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mx-auto max-w-3xl space-y-6 p-4 sm:p-6">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<h1 className="text-lg font-semibold text-neutral-900">
|
||||||
|
Einstellungen
|
||||||
|
</h1>
|
||||||
|
<Link
|
||||||
|
href="/einstellungen/team"
|
||||||
|
className="inline-flex items-center gap-1.5 rounded-md border border-neutral-200 bg-white px-3 py-1.5 text-sm font-medium text-neutral-700 hover:bg-neutral-50"
|
||||||
|
>
|
||||||
|
<Users className="h-3.5 w-3.5" />
|
||||||
|
Team verwalten
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Tenant Info */}
|
||||||
|
{isLoading ? (
|
||||||
|
<>
|
||||||
|
<SkeletonCard />
|
||||||
|
<SkeletonCard />
|
||||||
|
</>
|
||||||
|
) : error ? (
|
||||||
|
<EmptyState
|
||||||
|
icon={Settings}
|
||||||
|
title="Fehler beim Laden"
|
||||||
|
description="Einstellungen konnten nicht geladen werden."
|
||||||
|
action={
|
||||||
|
<button
|
||||||
|
onClick={() => refetch()}
|
||||||
|
className="rounded-md bg-neutral-900 px-3 py-1.5 text-sm font-medium text-white hover:bg-neutral-800"
|
||||||
|
>
|
||||||
|
Erneut versuchen
|
||||||
|
</button>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
) : tenant ? (
|
||||||
|
<>
|
||||||
|
{/* Kanzlei Info */}
|
||||||
|
<section className="rounded-xl border border-neutral-200 bg-white p-5">
|
||||||
|
<div className="flex items-center gap-2.5 border-b border-neutral-100 pb-3">
|
||||||
|
<Settings className="h-4 w-4 text-neutral-500" />
|
||||||
|
<h2 className="text-sm font-semibold text-neutral-900">
|
||||||
|
Kanzlei
|
||||||
|
</h2>
|
||||||
|
</div>
|
||||||
|
<div className="mt-4 grid gap-3 sm:grid-cols-2">
|
||||||
|
<div>
|
||||||
|
<p className="text-xs text-neutral-500">Name</p>
|
||||||
|
<p className="text-sm font-medium text-neutral-900">
|
||||||
|
{tenant.name}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="text-xs text-neutral-500">Slug</p>
|
||||||
|
<p className="text-sm font-medium text-neutral-900">
|
||||||
|
{tenant.slug}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="text-xs text-neutral-500">Erstellt am</p>
|
||||||
|
<p className="text-sm text-neutral-700">
|
||||||
|
{new Date(tenant.created_at).toLocaleDateString("de-DE", {
|
||||||
|
day: "2-digit",
|
||||||
|
month: "2-digit",
|
||||||
|
year: "numeric",
|
||||||
|
})}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{/* CalDAV Settings */}
|
||||||
|
<section className="rounded-xl border border-neutral-200 bg-white p-5">
|
||||||
|
<div className="flex items-center gap-2.5 border-b border-neutral-100 pb-3">
|
||||||
|
<Calendar className="h-4 w-4 text-neutral-500" />
|
||||||
|
<h2 className="text-sm font-semibold text-neutral-900">
|
||||||
|
CalDAV-Synchronisierung
|
||||||
|
</h2>
|
||||||
|
</div>
|
||||||
|
<div className="mt-4">
|
||||||
|
<CalDAVSettings tenant={tenant} />
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
40
frontend/src/app/(app)/einstellungen/team/page.tsx
Normal file
40
frontend/src/app/(app)/einstellungen/team/page.tsx
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import Link from "next/link";
|
||||||
|
import { ArrowLeft, Users } from "lucide-react";
|
||||||
|
import { TeamSettings } from "@/components/settings/TeamSettings";
|
||||||
|
|
||||||
|
export default function TeamPage() {
|
||||||
|
return (
|
||||||
|
<div className="mx-auto max-w-3xl space-y-6 p-4 sm:p-6">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<Link
|
||||||
|
href="/einstellungen"
|
||||||
|
className="rounded-md p-1.5 text-neutral-400 hover:bg-neutral-100 hover:text-neutral-600"
|
||||||
|
>
|
||||||
|
<ArrowLeft className="h-4 w-4" />
|
||||||
|
</Link>
|
||||||
|
<div className="flex items-center gap-2.5">
|
||||||
|
<Users className="h-4 w-4 text-neutral-500" />
|
||||||
|
<h1 className="text-lg font-semibold text-neutral-900">
|
||||||
|
Team verwalten
|
||||||
|
</h1>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<section className="rounded-xl border border-neutral-200 bg-white p-5">
|
||||||
|
<div className="border-b border-neutral-100 pb-3">
|
||||||
|
<h2 className="text-sm font-semibold text-neutral-900">
|
||||||
|
Mitglieder
|
||||||
|
</h2>
|
||||||
|
<p className="mt-0.5 text-xs text-neutral-500">
|
||||||
|
Benutzer einladen und Rollen verwalten
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="mt-4">
|
||||||
|
<TeamSettings />
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -16,7 +16,7 @@ export default function FristenPage() {
|
|||||||
|
|
||||||
const { data: deadlines } = useQuery({
|
const { data: deadlines } = useQuery({
|
||||||
queryKey: ["deadlines"],
|
queryKey: ["deadlines"],
|
||||||
queryFn: () => api.get<Deadline[]>("/api/deadlines"),
|
queryFn: () => api.get<Deadline[]>("/deadlines"),
|
||||||
});
|
});
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
99
frontend/src/app/(app)/termine/page.tsx
Normal file
99
frontend/src/app/(app)/termine/page.tsx
Normal file
@@ -0,0 +1,99 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { AppointmentList } from "@/components/appointments/AppointmentList";
|
||||||
|
import { AppointmentCalendar } from "@/components/appointments/AppointmentCalendar";
|
||||||
|
import { AppointmentModal } from "@/components/appointments/AppointmentModal";
|
||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
import { api } from "@/lib/api";
|
||||||
|
import type { Appointment } from "@/lib/types";
|
||||||
|
import { Calendar, List, Plus } from "lucide-react";
|
||||||
|
import { useState } from "react";
|
||||||
|
|
||||||
|
type ViewMode = "list" | "calendar";
|
||||||
|
|
||||||
|
export default function TerminePage() {
|
||||||
|
const [view, setView] = useState<ViewMode>("list");
|
||||||
|
const [modalOpen, setModalOpen] = useState(false);
|
||||||
|
const [editingAppointment, setEditingAppointment] = useState<Appointment | null>(null);
|
||||||
|
|
||||||
|
const { data: appointments } = useQuery({
|
||||||
|
queryKey: ["appointments"],
|
||||||
|
queryFn: () => api.get<Appointment[]>("/appointments"),
|
||||||
|
});
|
||||||
|
|
||||||
|
function handleEdit(appointment: Appointment) {
|
||||||
|
setEditingAppointment(appointment);
|
||||||
|
setModalOpen(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleCreate() {
|
||||||
|
setEditingAppointment(null);
|
||||||
|
setModalOpen(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleClose() {
|
||||||
|
setModalOpen(false);
|
||||||
|
setEditingAppointment(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-lg font-semibold text-neutral-900">Termine</h1>
|
||||||
|
<p className="mt-0.5 text-sm text-neutral-500">
|
||||||
|
Alle Termine im Uberblick
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<button
|
||||||
|
onClick={handleCreate}
|
||||||
|
className="flex items-center gap-1.5 rounded-md bg-neutral-900 px-3 py-1.5 text-sm font-medium text-white hover:bg-neutral-800"
|
||||||
|
>
|
||||||
|
<Plus className="h-3.5 w-3.5" />
|
||||||
|
Neuer Termin
|
||||||
|
</button>
|
||||||
|
<div className="flex rounded-md border border-neutral-200 bg-white">
|
||||||
|
<button
|
||||||
|
onClick={() => setView("list")}
|
||||||
|
className={`flex items-center gap-1 rounded-l-md px-2.5 py-1.5 text-sm transition-colors ${
|
||||||
|
view === "list"
|
||||||
|
? "bg-neutral-100 font-medium text-neutral-900"
|
||||||
|
: "text-neutral-500 hover:text-neutral-700"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<List className="h-3.5 w-3.5" />
|
||||||
|
Liste
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => setView("calendar")}
|
||||||
|
className={`flex items-center gap-1 rounded-r-md px-2.5 py-1.5 text-sm transition-colors ${
|
||||||
|
view === "calendar"
|
||||||
|
? "bg-neutral-100 font-medium text-neutral-900"
|
||||||
|
: "text-neutral-500 hover:text-neutral-700"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<Calendar className="h-3.5 w-3.5" />
|
||||||
|
Kalender
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{view === "list" ? (
|
||||||
|
<AppointmentList onEdit={handleEdit} />
|
||||||
|
) : (
|
||||||
|
<AppointmentCalendar
|
||||||
|
appointments={appointments || []}
|
||||||
|
onAppointmentClick={handleEdit}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<AppointmentModal
|
||||||
|
open={modalOpen}
|
||||||
|
onClose={handleClose}
|
||||||
|
appointment={editingAppointment}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
160
frontend/src/components/appointments/AppointmentCalendar.tsx
Normal file
160
frontend/src/components/appointments/AppointmentCalendar.tsx
Normal file
@@ -0,0 +1,160 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import type { Appointment } from "@/lib/types";
|
||||||
|
import {
|
||||||
|
format,
|
||||||
|
startOfMonth,
|
||||||
|
endOfMonth,
|
||||||
|
startOfWeek,
|
||||||
|
endOfWeek,
|
||||||
|
eachDayOfInterval,
|
||||||
|
isSameMonth,
|
||||||
|
isToday,
|
||||||
|
parseISO,
|
||||||
|
addMonths,
|
||||||
|
subMonths,
|
||||||
|
} from "date-fns";
|
||||||
|
import { de } from "date-fns/locale";
|
||||||
|
import { ChevronLeft, ChevronRight } from "lucide-react";
|
||||||
|
import { useState, useMemo } from "react";
|
||||||
|
|
||||||
|
const TYPE_DOT_COLORS: Record<string, string> = {
|
||||||
|
hearing: "bg-blue-500",
|
||||||
|
meeting: "bg-violet-500",
|
||||||
|
consultation: "bg-emerald-500",
|
||||||
|
deadline_hearing: "bg-amber-500",
|
||||||
|
other: "bg-neutral-400",
|
||||||
|
};
|
||||||
|
|
||||||
|
interface AppointmentCalendarProps {
|
||||||
|
appointments: Appointment[];
|
||||||
|
onDayClick?: (date: string) => void;
|
||||||
|
onAppointmentClick?: (appointment: Appointment) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function AppointmentCalendar({
|
||||||
|
appointments,
|
||||||
|
onDayClick,
|
||||||
|
onAppointmentClick,
|
||||||
|
}: AppointmentCalendarProps) {
|
||||||
|
const [currentMonth, setCurrentMonth] = useState(new Date());
|
||||||
|
|
||||||
|
const monthStart = startOfMonth(currentMonth);
|
||||||
|
const monthEnd = endOfMonth(currentMonth);
|
||||||
|
const calStart = startOfWeek(monthStart, { weekStartsOn: 1 });
|
||||||
|
const calEnd = endOfWeek(monthEnd, { weekStartsOn: 1 });
|
||||||
|
const days = eachDayOfInterval({ start: calStart, end: calEnd });
|
||||||
|
|
||||||
|
const appointmentsByDay = useMemo(() => {
|
||||||
|
const map = new Map<string, Appointment[]>();
|
||||||
|
for (const a of appointments) {
|
||||||
|
const key = a.start_at.slice(0, 10);
|
||||||
|
const existing = map.get(key) || [];
|
||||||
|
existing.push(a);
|
||||||
|
map.set(key, existing);
|
||||||
|
}
|
||||||
|
return map;
|
||||||
|
}, [appointments]);
|
||||||
|
|
||||||
|
const weekDays = ["Mo", "Di", "Mi", "Do", "Fr", "Sa", "So"];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="rounded-lg border border-neutral-200 bg-white">
|
||||||
|
{/* Header */}
|
||||||
|
<div className="flex items-center justify-between border-b border-neutral-200 px-4 py-3">
|
||||||
|
<button
|
||||||
|
onClick={() => setCurrentMonth(subMonths(currentMonth, 1))}
|
||||||
|
className="rounded-md p-1 text-neutral-400 hover:bg-neutral-100 hover:text-neutral-600"
|
||||||
|
>
|
||||||
|
<ChevronLeft className="h-4 w-4" />
|
||||||
|
</button>
|
||||||
|
<span className="text-sm font-medium text-neutral-900">
|
||||||
|
{format(currentMonth, "MMMM yyyy", { locale: de })}
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
onClick={() => setCurrentMonth(addMonths(currentMonth, 1))}
|
||||||
|
className="rounded-md p-1 text-neutral-400 hover:bg-neutral-100 hover:text-neutral-600"
|
||||||
|
>
|
||||||
|
<ChevronRight className="h-4 w-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Weekday labels */}
|
||||||
|
<div className="grid grid-cols-7 border-b border-neutral-100">
|
||||||
|
{weekDays.map((d) => (
|
||||||
|
<div key={d} className="px-2 py-2 text-center text-xs font-medium text-neutral-400">
|
||||||
|
{d}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Days grid */}
|
||||||
|
<div className="grid grid-cols-7">
|
||||||
|
{days.map((day, i) => {
|
||||||
|
const key = format(day, "yyyy-MM-dd");
|
||||||
|
const dayAppointments = appointmentsByDay.get(key) || [];
|
||||||
|
const inMonth = isSameMonth(day, currentMonth);
|
||||||
|
const today = isToday(day);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={i}
|
||||||
|
onClick={() => onDayClick?.(key)}
|
||||||
|
className={`min-h-[5rem] cursor-pointer border-b border-r border-neutral-100 p-1.5 transition-colors hover:bg-neutral-50 ${
|
||||||
|
!inMonth ? "bg-neutral-50/50" : ""
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className={`mb-1 text-right text-xs ${
|
||||||
|
today
|
||||||
|
? "font-bold text-neutral-900"
|
||||||
|
: inMonth
|
||||||
|
? "text-neutral-600"
|
||||||
|
: "text-neutral-300"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{today ? (
|
||||||
|
<span className="inline-flex h-5 w-5 items-center justify-center rounded-full bg-neutral-900 text-white">
|
||||||
|
{format(day, "d")}
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
format(day, "d")
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="space-y-0.5">
|
||||||
|
{dayAppointments.slice(0, 3).map((appt) => {
|
||||||
|
const dotColor =
|
||||||
|
TYPE_DOT_COLORS[appt.appointment_type ?? "other"] ?? TYPE_DOT_COLORS.other;
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={appt.id}
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
onAppointmentClick?.(appt);
|
||||||
|
}}
|
||||||
|
className="flex items-center gap-1 truncate rounded px-0.5 hover:bg-neutral-100"
|
||||||
|
title={`${format(parseISO(appt.start_at), "HH:mm")} ${appt.title}`}
|
||||||
|
>
|
||||||
|
<div className={`h-1.5 w-1.5 shrink-0 rounded-full ${dotColor}`} />
|
||||||
|
<span className="truncate text-[10px] text-neutral-700">
|
||||||
|
<span className="font-medium">
|
||||||
|
{format(parseISO(appt.start_at), "HH:mm")}
|
||||||
|
</span>{" "}
|
||||||
|
{appt.title}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
{dayAppointments.length > 3 && (
|
||||||
|
<div className="text-[10px] text-neutral-400">
|
||||||
|
+{dayAppointments.length - 3} mehr
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
265
frontend/src/components/appointments/AppointmentList.tsx
Normal file
265
frontend/src/components/appointments/AppointmentList.tsx
Normal file
@@ -0,0 +1,265 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import { api } from "@/lib/api";
|
||||||
|
import type { Appointment, Case } from "@/lib/types";
|
||||||
|
import { format, parseISO, isToday, isTomorrow, isThisWeek, isPast } from "date-fns";
|
||||||
|
import { de } from "date-fns/locale";
|
||||||
|
import { Calendar, Filter, MapPin, Trash2 } from "lucide-react";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { useState, useMemo } from "react";
|
||||||
|
|
||||||
|
const TYPE_LABELS: Record<string, string> = {
|
||||||
|
hearing: "Verhandlung",
|
||||||
|
meeting: "Besprechung",
|
||||||
|
consultation: "Beratung",
|
||||||
|
deadline_hearing: "Fristanhorung",
|
||||||
|
other: "Sonstiges",
|
||||||
|
};
|
||||||
|
|
||||||
|
const TYPE_COLORS: Record<string, string> = {
|
||||||
|
hearing: "bg-blue-100 text-blue-700",
|
||||||
|
meeting: "bg-violet-100 text-violet-700",
|
||||||
|
consultation: "bg-emerald-100 text-emerald-700",
|
||||||
|
deadline_hearing: "bg-amber-100 text-amber-700",
|
||||||
|
other: "bg-neutral-100 text-neutral-600",
|
||||||
|
};
|
||||||
|
|
||||||
|
interface AppointmentListProps {
|
||||||
|
onEdit: (appointment: Appointment) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
function groupByDate(appointments: Appointment[]): Map<string, Appointment[]> {
|
||||||
|
const groups = new Map<string, Appointment[]>();
|
||||||
|
for (const a of appointments) {
|
||||||
|
const key = a.start_at.slice(0, 10);
|
||||||
|
const group = groups.get(key) || [];
|
||||||
|
group.push(a);
|
||||||
|
groups.set(key, group);
|
||||||
|
}
|
||||||
|
return groups;
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatDateLabel(dateStr: string): string {
|
||||||
|
const d = parseISO(dateStr);
|
||||||
|
if (isToday(d)) return "Heute";
|
||||||
|
if (isTomorrow(d)) return "Morgen";
|
||||||
|
return format(d, "EEEE, d. MMMM yyyy", { locale: de });
|
||||||
|
}
|
||||||
|
|
||||||
|
export function AppointmentList({ onEdit }: AppointmentListProps) {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const [caseFilter, setCaseFilter] = useState("all");
|
||||||
|
const [typeFilter, setTypeFilter] = useState("all");
|
||||||
|
|
||||||
|
const { data: appointments, isLoading } = useQuery({
|
||||||
|
queryKey: ["appointments"],
|
||||||
|
queryFn: () => api.get<Appointment[]>("/appointments"),
|
||||||
|
});
|
||||||
|
|
||||||
|
const { data: cases } = useQuery({
|
||||||
|
queryKey: ["cases"],
|
||||||
|
queryFn: () => api.get<{ cases: Case[]; total: number }>("/cases"),
|
||||||
|
});
|
||||||
|
|
||||||
|
const deleteMutation = useMutation({
|
||||||
|
mutationFn: (id: string) => api.delete(`/appointments/${id}`),
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["appointments"] });
|
||||||
|
toast.success("Termin geloscht");
|
||||||
|
},
|
||||||
|
onError: () => toast.error("Fehler beim Loschen"),
|
||||||
|
});
|
||||||
|
|
||||||
|
const caseMap = useMemo(() => {
|
||||||
|
const map = new Map<string, Case>();
|
||||||
|
cases?.cases?.forEach((c) => map.set(c.id, c));
|
||||||
|
return map;
|
||||||
|
}, [cases]);
|
||||||
|
|
||||||
|
const filtered = useMemo(() => {
|
||||||
|
if (!appointments) return [];
|
||||||
|
return appointments
|
||||||
|
.filter((a) => {
|
||||||
|
if (caseFilter !== "all" && a.case_id !== caseFilter) return false;
|
||||||
|
if (typeFilter !== "all" && a.appointment_type !== typeFilter) return false;
|
||||||
|
return true;
|
||||||
|
})
|
||||||
|
.sort((a, b) => a.start_at.localeCompare(b.start_at));
|
||||||
|
}, [appointments, caseFilter, typeFilter]);
|
||||||
|
|
||||||
|
const grouped = useMemo(() => groupByDate(filtered), [filtered]);
|
||||||
|
|
||||||
|
const counts = useMemo(() => {
|
||||||
|
if (!appointments) return { today: 0, thisWeek: 0, total: 0 };
|
||||||
|
let today = 0;
|
||||||
|
let thisWeek = 0;
|
||||||
|
for (const a of appointments) {
|
||||||
|
const d = parseISO(a.start_at);
|
||||||
|
if (isToday(d)) today++;
|
||||||
|
if (isThisWeek(d, { weekStartsOn: 1 })) thisWeek++;
|
||||||
|
}
|
||||||
|
return { today, thisWeek, total: appointments.length };
|
||||||
|
}, [appointments]);
|
||||||
|
|
||||||
|
if (isLoading) {
|
||||||
|
return (
|
||||||
|
<div className="space-y-3">
|
||||||
|
{[1, 2, 3, 4].map((i) => (
|
||||||
|
<div key={i} className="h-16 animate-pulse rounded-lg bg-neutral-100" />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
{/* Summary cards */}
|
||||||
|
<div className="grid grid-cols-3 gap-3">
|
||||||
|
<div className="rounded-lg border border-neutral-200 bg-white p-3">
|
||||||
|
<div className="text-2xl font-semibold text-neutral-900">{counts.today}</div>
|
||||||
|
<div className="text-xs text-neutral-500">Heute</div>
|
||||||
|
</div>
|
||||||
|
<div className="rounded-lg border border-neutral-200 bg-white p-3">
|
||||||
|
<div className="text-2xl font-semibold text-neutral-900">{counts.thisWeek}</div>
|
||||||
|
<div className="text-xs text-neutral-500">Diese Woche</div>
|
||||||
|
</div>
|
||||||
|
<div className="rounded-lg border border-neutral-200 bg-white p-3">
|
||||||
|
<div className="text-2xl font-semibold text-neutral-900">{counts.total}</div>
|
||||||
|
<div className="text-xs text-neutral-500">Gesamt</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Filters */}
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<div className="flex items-center gap-1.5 text-sm text-neutral-500">
|
||||||
|
<Filter className="h-3.5 w-3.5" />
|
||||||
|
<span>Filter:</span>
|
||||||
|
</div>
|
||||||
|
<select
|
||||||
|
value={typeFilter}
|
||||||
|
onChange={(e) => setTypeFilter(e.target.value)}
|
||||||
|
className="rounded-md border border-neutral-200 bg-white px-2.5 py-1 text-sm text-neutral-700"
|
||||||
|
>
|
||||||
|
<option value="all">Alle Typen</option>
|
||||||
|
{Object.entries(TYPE_LABELS).map(([value, label]) => (
|
||||||
|
<option key={value} value={value}>
|
||||||
|
{label}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
{cases?.cases && cases.cases.length > 0 && (
|
||||||
|
<select
|
||||||
|
value={caseFilter}
|
||||||
|
onChange={(e) => setCaseFilter(e.target.value)}
|
||||||
|
className="rounded-md border border-neutral-200 bg-white px-2.5 py-1 text-sm text-neutral-700"
|
||||||
|
>
|
||||||
|
<option value="all">Alle Akten</option>
|
||||||
|
{cases.cases.map((c) => (
|
||||||
|
<option key={c.id} value={c.id}>
|
||||||
|
{c.case_number} — {c.title}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Grouped list */}
|
||||||
|
{filtered.length === 0 ? (
|
||||||
|
<div className="rounded-lg border border-neutral-200 bg-white p-8 text-center">
|
||||||
|
<Calendar className="mx-auto h-8 w-8 text-neutral-300" />
|
||||||
|
<p className="mt-2 text-sm text-neutral-500">Keine Termine gefunden</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-4">
|
||||||
|
{Array.from(grouped.entries()).map(([dateKey, dayAppointments]) => {
|
||||||
|
const dateIsPast = isPast(parseISO(dateKey + "T23:59:59"));
|
||||||
|
return (
|
||||||
|
<div key={dateKey}>
|
||||||
|
<div className={`mb-2 text-xs font-medium uppercase tracking-wider ${dateIsPast ? "text-neutral-400" : "text-neutral-600"}`}>
|
||||||
|
{formatDateLabel(dateKey)}
|
||||||
|
</div>
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
{dayAppointments.map((appt) => {
|
||||||
|
const caseInfo = appt.case_id ? caseMap.get(appt.case_id) : null;
|
||||||
|
const typeBadge = appt.appointment_type
|
||||||
|
? TYPE_COLORS[appt.appointment_type] ?? TYPE_COLORS.other
|
||||||
|
: null;
|
||||||
|
const typeLabel = appt.appointment_type
|
||||||
|
? TYPE_LABELS[appt.appointment_type] ?? appt.appointment_type
|
||||||
|
: null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={appt.id}
|
||||||
|
onClick={() => onEdit(appt)}
|
||||||
|
className={`flex cursor-pointer items-start gap-3 rounded-lg border px-4 py-3 transition-colors hover:bg-neutral-50 ${
|
||||||
|
dateIsPast
|
||||||
|
? "border-neutral-150 bg-neutral-50/50"
|
||||||
|
: "border-neutral-200 bg-white"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<div className="shrink-0 pt-0.5 text-center">
|
||||||
|
<div className="text-xs font-medium text-neutral-900">
|
||||||
|
{format(parseISO(appt.start_at), "HH:mm")}
|
||||||
|
</div>
|
||||||
|
{appt.end_at && (
|
||||||
|
<div className="text-[10px] text-neutral-400">
|
||||||
|
{format(parseISO(appt.end_at), "HH:mm")}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className={`truncate text-sm font-medium ${dateIsPast ? "text-neutral-500" : "text-neutral-900"}`}>
|
||||||
|
{appt.title}
|
||||||
|
</span>
|
||||||
|
{typeBadge && typeLabel && (
|
||||||
|
<span className={`shrink-0 rounded px-1.5 py-0.5 text-xs font-medium ${typeBadge}`}>
|
||||||
|
{typeLabel}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="mt-0.5 flex items-center gap-2 text-xs text-neutral-500">
|
||||||
|
{appt.location && (
|
||||||
|
<span className="flex items-center gap-0.5">
|
||||||
|
<MapPin className="h-3 w-3" />
|
||||||
|
{appt.location}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{appt.location && caseInfo && <span>·</span>}
|
||||||
|
{caseInfo && (
|
||||||
|
<span className="truncate">
|
||||||
|
{caseInfo.case_number} — {caseInfo.title}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{appt.description && (
|
||||||
|
<p className="mt-1 truncate text-xs text-neutral-400">
|
||||||
|
{appt.description}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
deleteMutation.mutate(appt.id);
|
||||||
|
}}
|
||||||
|
disabled={deleteMutation.isPending}
|
||||||
|
title="Loschen"
|
||||||
|
className="shrink-0 rounded-md p-1.5 text-neutral-300 hover:bg-red-50 hover:text-red-500"
|
||||||
|
>
|
||||||
|
<Trash2 className="h-3.5 w-3.5" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
280
frontend/src/components/appointments/AppointmentModal.tsx
Normal file
280
frontend/src/components/appointments/AppointmentModal.tsx
Normal file
@@ -0,0 +1,280 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import { api } from "@/lib/api";
|
||||||
|
import type { Appointment, Case } from "@/lib/types";
|
||||||
|
import { format, parseISO } from "date-fns";
|
||||||
|
import { X } from "lucide-react";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
|
||||||
|
const APPOINTMENT_TYPES = [
|
||||||
|
{ value: "hearing", label: "Verhandlung" },
|
||||||
|
{ value: "meeting", label: "Besprechung" },
|
||||||
|
{ value: "consultation", label: "Beratung" },
|
||||||
|
{ value: "deadline_hearing", label: "Fristanhorung" },
|
||||||
|
{ value: "other", label: "Sonstiges" },
|
||||||
|
];
|
||||||
|
|
||||||
|
interface AppointmentModalProps {
|
||||||
|
open: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
appointment?: Appointment | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function toLocalDatetime(iso: string): string {
|
||||||
|
const d = parseISO(iso);
|
||||||
|
return format(d, "yyyy-MM-dd'T'HH:mm");
|
||||||
|
}
|
||||||
|
|
||||||
|
export function AppointmentModal({ open, onClose, appointment }: AppointmentModalProps) {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const isEdit = !!appointment;
|
||||||
|
|
||||||
|
const [title, setTitle] = useState("");
|
||||||
|
const [description, setDescription] = useState("");
|
||||||
|
const [startAt, setStartAt] = useState("");
|
||||||
|
const [endAt, setEndAt] = useState("");
|
||||||
|
const [location, setLocation] = useState("");
|
||||||
|
const [appointmentType, setAppointmentType] = useState("");
|
||||||
|
const [caseId, setCaseId] = useState("");
|
||||||
|
|
||||||
|
const { data: cases } = useQuery({
|
||||||
|
queryKey: ["cases"],
|
||||||
|
queryFn: () => api.get<{ cases: Case[]; total: number }>("/cases"),
|
||||||
|
});
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (appointment) {
|
||||||
|
setTitle(appointment.title);
|
||||||
|
setDescription(appointment.description ?? "");
|
||||||
|
setStartAt(toLocalDatetime(appointment.start_at));
|
||||||
|
setEndAt(appointment.end_at ? toLocalDatetime(appointment.end_at) : "");
|
||||||
|
setLocation(appointment.location ?? "");
|
||||||
|
setAppointmentType(appointment.appointment_type ?? "");
|
||||||
|
setCaseId(appointment.case_id ?? "");
|
||||||
|
} else {
|
||||||
|
setTitle("");
|
||||||
|
setDescription("");
|
||||||
|
setStartAt("");
|
||||||
|
setEndAt("");
|
||||||
|
setLocation("");
|
||||||
|
setAppointmentType("");
|
||||||
|
setCaseId("");
|
||||||
|
}
|
||||||
|
}, [appointment]);
|
||||||
|
|
||||||
|
const createMutation = useMutation({
|
||||||
|
mutationFn: (body: Record<string, unknown>) =>
|
||||||
|
api.post<Appointment>("/appointments", body),
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["appointments"] });
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["dashboard"] });
|
||||||
|
toast.success("Termin erstellt");
|
||||||
|
onClose();
|
||||||
|
},
|
||||||
|
onError: () => toast.error("Fehler beim Erstellen des Termins"),
|
||||||
|
});
|
||||||
|
|
||||||
|
const updateMutation = useMutation({
|
||||||
|
mutationFn: (body: Record<string, unknown>) =>
|
||||||
|
api.put<Appointment>(`/api/appointments/${appointment!.id}`, body),
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["appointments"] });
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["dashboard"] });
|
||||||
|
toast.success("Termin aktualisiert");
|
||||||
|
onClose();
|
||||||
|
},
|
||||||
|
onError: () => toast.error("Fehler beim Aktualisieren des Termins"),
|
||||||
|
});
|
||||||
|
|
||||||
|
const deleteMutation = useMutation({
|
||||||
|
mutationFn: () => api.delete(`/appointments/${appointment!.id}`),
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["appointments"] });
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["dashboard"] });
|
||||||
|
toast.success("Termin geloscht");
|
||||||
|
onClose();
|
||||||
|
},
|
||||||
|
onError: () => toast.error("Fehler beim Loschen des Termins"),
|
||||||
|
});
|
||||||
|
|
||||||
|
function handleSubmit(e: React.FormEvent) {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!title.trim() || !startAt) return;
|
||||||
|
|
||||||
|
const body: Record<string, unknown> = {
|
||||||
|
title: title.trim(),
|
||||||
|
start_at: new Date(startAt).toISOString(),
|
||||||
|
};
|
||||||
|
if (description.trim()) body.description = description.trim();
|
||||||
|
if (endAt) body.end_at = new Date(endAt).toISOString();
|
||||||
|
if (location.trim()) body.location = location.trim();
|
||||||
|
if (appointmentType) body.appointment_type = appointmentType;
|
||||||
|
if (caseId) body.case_id = caseId;
|
||||||
|
|
||||||
|
if (isEdit) {
|
||||||
|
updateMutation.mutate(body);
|
||||||
|
} else {
|
||||||
|
createMutation.mutate(body);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const isPending = createMutation.isPending || updateMutation.isPending;
|
||||||
|
|
||||||
|
if (!open) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/30">
|
||||||
|
<div className="w-full max-w-lg rounded-lg border border-neutral-200 bg-white shadow-lg">
|
||||||
|
<div className="flex items-center justify-between border-b border-neutral-200 px-5 py-3">
|
||||||
|
<h2 className="text-sm font-semibold text-neutral-900">
|
||||||
|
{isEdit ? "Termin bearbeiten" : "Neuer Termin"}
|
||||||
|
</h2>
|
||||||
|
<button
|
||||||
|
onClick={onClose}
|
||||||
|
className="rounded-md p-1 text-neutral-400 hover:bg-neutral-100 hover:text-neutral-600"
|
||||||
|
>
|
||||||
|
<X className="h-4 w-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<form onSubmit={handleSubmit} className="space-y-4 p-5">
|
||||||
|
<div>
|
||||||
|
<label className="mb-1 block text-xs font-medium text-neutral-600">
|
||||||
|
Titel *
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={title}
|
||||||
|
onChange={(e) => setTitle(e.target.value)}
|
||||||
|
required
|
||||||
|
className="w-full rounded-md border border-neutral-200 px-3 py-1.5 text-sm outline-none focus:border-neutral-400 focus:ring-1 focus:ring-neutral-400"
|
||||||
|
placeholder="z.B. Mundliche Verhandlung"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-2 gap-3">
|
||||||
|
<div>
|
||||||
|
<label className="mb-1 block text-xs font-medium text-neutral-600">
|
||||||
|
Beginn *
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="datetime-local"
|
||||||
|
value={startAt}
|
||||||
|
onChange={(e) => setStartAt(e.target.value)}
|
||||||
|
required
|
||||||
|
className="w-full rounded-md border border-neutral-200 px-3 py-1.5 text-sm outline-none focus:border-neutral-400 focus:ring-1 focus:ring-neutral-400"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="mb-1 block text-xs font-medium text-neutral-600">
|
||||||
|
Ende
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="datetime-local"
|
||||||
|
value={endAt}
|
||||||
|
onChange={(e) => setEndAt(e.target.value)}
|
||||||
|
className="w-full rounded-md border border-neutral-200 px-3 py-1.5 text-sm outline-none focus:border-neutral-400 focus:ring-1 focus:ring-neutral-400"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-2 gap-3">
|
||||||
|
<div>
|
||||||
|
<label className="mb-1 block text-xs font-medium text-neutral-600">
|
||||||
|
Typ
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
value={appointmentType}
|
||||||
|
onChange={(e) => setAppointmentType(e.target.value)}
|
||||||
|
className="w-full rounded-md border border-neutral-200 px-3 py-1.5 text-sm outline-none focus:border-neutral-400"
|
||||||
|
>
|
||||||
|
<option value="">Kein Typ</option>
|
||||||
|
{APPOINTMENT_TYPES.map((t) => (
|
||||||
|
<option key={t.value} value={t.value}>
|
||||||
|
{t.label}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="mb-1 block text-xs font-medium text-neutral-600">
|
||||||
|
Akte
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
value={caseId}
|
||||||
|
onChange={(e) => setCaseId(e.target.value)}
|
||||||
|
className="w-full rounded-md border border-neutral-200 px-3 py-1.5 text-sm outline-none focus:border-neutral-400"
|
||||||
|
>
|
||||||
|
<option value="">Keine Akte</option>
|
||||||
|
{cases?.cases?.map((c) => (
|
||||||
|
<option key={c.id} value={c.id}>
|
||||||
|
{c.case_number} — {c.title}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="mb-1 block text-xs font-medium text-neutral-600">
|
||||||
|
Ort
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={location}
|
||||||
|
onChange={(e) => setLocation(e.target.value)}
|
||||||
|
className="w-full rounded-md border border-neutral-200 px-3 py-1.5 text-sm outline-none focus:border-neutral-400 focus:ring-1 focus:ring-neutral-400"
|
||||||
|
placeholder="z.B. UPC Munchen, Saal 3"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="mb-1 block text-xs font-medium text-neutral-600">
|
||||||
|
Beschreibung
|
||||||
|
</label>
|
||||||
|
<textarea
|
||||||
|
value={description}
|
||||||
|
onChange={(e) => setDescription(e.target.value)}
|
||||||
|
rows={3}
|
||||||
|
className="w-full rounded-md border border-neutral-200 px-3 py-1.5 text-sm outline-none focus:border-neutral-400 focus:ring-1 focus:ring-neutral-400"
|
||||||
|
placeholder="Optionale Notizen zum Termin"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center justify-between pt-2">
|
||||||
|
<div>
|
||||||
|
{isEdit && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => deleteMutation.mutate()}
|
||||||
|
disabled={deleteMutation.isPending}
|
||||||
|
className="rounded-md px-3 py-1.5 text-sm text-red-600 hover:bg-red-50"
|
||||||
|
>
|
||||||
|
Loschen
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onClose}
|
||||||
|
className="rounded-md border border-neutral-200 bg-white px-3 py-1.5 text-sm text-neutral-700 hover:bg-neutral-50"
|
||||||
|
>
|
||||||
|
Abbrechen
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={isPending || !title.trim() || !startAt}
|
||||||
|
className="rounded-md bg-neutral-900 px-3 py-1.5 text-sm font-medium text-white hover:bg-neutral-800 disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{isPending ? "Speichern..." : isEdit ? "Aktualisieren" : "Erstellen"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -39,14 +39,14 @@ export function DeadlineCalculator() {
|
|||||||
|
|
||||||
const { data: proceedingTypes, isLoading: typesLoading } = useQuery({
|
const { data: proceedingTypes, isLoading: typesLoading } = useQuery({
|
||||||
queryKey: ["proceeding-types"],
|
queryKey: ["proceeding-types"],
|
||||||
queryFn: () => api.get<ProceedingType[]>("/api/proceeding-types"),
|
queryFn: () => api.get<ProceedingType[]>("/proceeding-types"),
|
||||||
});
|
});
|
||||||
|
|
||||||
const calculateMutation = useMutation({
|
const calculateMutation = useMutation({
|
||||||
mutationFn: (params: {
|
mutationFn: (params: {
|
||||||
proceeding_type: string;
|
proceeding_type: string;
|
||||||
trigger_event_date: string;
|
trigger_event_date: string;
|
||||||
}) => api.post<CalculateResponse>("/api/deadlines/calculate", params),
|
}) => api.post<CalculateResponse>("/deadlines/calculate", params),
|
||||||
});
|
});
|
||||||
|
|
||||||
function handleCalculate(e: React.FormEvent) {
|
function handleCalculate(e: React.FormEvent) {
|
||||||
|
|||||||
@@ -54,12 +54,12 @@ export function DeadlineList() {
|
|||||||
|
|
||||||
const { data: deadlines, isLoading } = useQuery({
|
const { data: deadlines, isLoading } = useQuery({
|
||||||
queryKey: ["deadlines"],
|
queryKey: ["deadlines"],
|
||||||
queryFn: () => api.get<Deadline[]>("/api/deadlines"),
|
queryFn: () => api.get<Deadline[]>("/deadlines"),
|
||||||
});
|
});
|
||||||
|
|
||||||
const { data: cases } = useQuery({
|
const { data: cases } = useQuery({
|
||||||
queryKey: ["cases"],
|
queryKey: ["cases"],
|
||||||
queryFn: () => api.get<Case[]>("/api/cases"),
|
queryFn: () => api.get<Case[]>("/cases"),
|
||||||
});
|
});
|
||||||
|
|
||||||
const completeMutation = useMutation({
|
const completeMutation = useMutation({
|
||||||
|
|||||||
144
frontend/src/components/documents/DocumentList.tsx
Normal file
144
frontend/src/components/documents/DocumentList.tsx
Normal file
@@ -0,0 +1,144 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import { FileText, Download, Trash2, Loader2 } from "lucide-react";
|
||||||
|
import { format } from "date-fns";
|
||||||
|
import { de } from "date-fns/locale";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { api } from "@/lib/api";
|
||||||
|
import type { Document } from "@/lib/types";
|
||||||
|
|
||||||
|
const DOC_TYPE_BADGE: Record<string, string> = {
|
||||||
|
schriftsatz: "bg-blue-50 text-blue-700",
|
||||||
|
beschluss: "bg-violet-50 text-violet-700",
|
||||||
|
urteil: "bg-emerald-50 text-emerald-700",
|
||||||
|
gutachten: "bg-amber-50 text-amber-700",
|
||||||
|
vertrag: "bg-cyan-50 text-cyan-700",
|
||||||
|
korrespondenz: "bg-neutral-100 text-neutral-600",
|
||||||
|
};
|
||||||
|
|
||||||
|
interface DocumentListProps {
|
||||||
|
documents: Document[];
|
||||||
|
caseId: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function DocumentList({ documents, caseId }: DocumentListProps) {
|
||||||
|
const [deleteId, setDeleteId] = useState<string | null>(null);
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
|
const deleteMutation = useMutation({
|
||||||
|
mutationFn: (docId: string) => api.delete(`/documents/${docId}`),
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["case-documents", caseId] });
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["case", caseId] });
|
||||||
|
toast.success("Dokument geloescht");
|
||||||
|
setDeleteId(null);
|
||||||
|
},
|
||||||
|
onError: (err) => {
|
||||||
|
const msg =
|
||||||
|
err && typeof err === "object" && "error" in err
|
||||||
|
? (err as { error: string }).error
|
||||||
|
: "Unbekannter Fehler";
|
||||||
|
toast.error(`Fehler beim Loeschen: ${msg}`);
|
||||||
|
setDeleteId(null);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (documents.length === 0) {
|
||||||
|
return (
|
||||||
|
<p className="py-8 text-center text-sm text-neutral-400">
|
||||||
|
Keine Dokumente vorhanden.
|
||||||
|
</p>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-2">
|
||||||
|
{documents.map((doc) => (
|
||||||
|
<div
|
||||||
|
key={doc.id}
|
||||||
|
className="flex items-center justify-between rounded-md border border-neutral-200 bg-white px-4 py-3"
|
||||||
|
>
|
||||||
|
<div className="flex items-center gap-3 min-w-0">
|
||||||
|
<FileText className="h-4 w-4 shrink-0 text-neutral-400" />
|
||||||
|
<div className="min-w-0">
|
||||||
|
<p className="truncate text-sm font-medium text-neutral-900">
|
||||||
|
{doc.title}
|
||||||
|
</p>
|
||||||
|
<div className="mt-0.5 flex flex-wrap items-center gap-2 text-xs text-neutral-400">
|
||||||
|
{doc.doc_type && (
|
||||||
|
<span
|
||||||
|
className={`rounded-full px-2 py-0.5 text-xs font-medium ${
|
||||||
|
DOC_TYPE_BADGE[doc.doc_type.toLowerCase()] ??
|
||||||
|
"bg-neutral-100 text-neutral-600"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{doc.doc_type}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{doc.file_size != null && (
|
||||||
|
<span>{formatFileSize(doc.file_size)}</span>
|
||||||
|
)}
|
||||||
|
<span>
|
||||||
|
{format(new Date(doc.created_at), "d. MMM yyyy", {
|
||||||
|
locale: de,
|
||||||
|
})}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-1 shrink-0 ml-3">
|
||||||
|
<a
|
||||||
|
href={`/api/documents/${doc.id}`}
|
||||||
|
className="rounded p-1.5 text-neutral-400 hover:bg-neutral-100 hover:text-neutral-600"
|
||||||
|
title="Herunterladen"
|
||||||
|
>
|
||||||
|
<Download className="h-4 w-4" />
|
||||||
|
</a>
|
||||||
|
|
||||||
|
{deleteId === doc.id ? (
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => deleteMutation.mutate(doc.id)}
|
||||||
|
disabled={deleteMutation.isPending}
|
||||||
|
className="rounded px-2 py-1 text-xs font-medium text-red-600 hover:bg-red-50"
|
||||||
|
>
|
||||||
|
{deleteMutation.isPending ? (
|
||||||
|
<Loader2 className="h-3.5 w-3.5 animate-spin" />
|
||||||
|
) : (
|
||||||
|
"Loeschen"
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setDeleteId(null)}
|
||||||
|
className="rounded px-2 py-1 text-xs text-neutral-500 hover:bg-neutral-100"
|
||||||
|
>
|
||||||
|
Abbrechen
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setDeleteId(doc.id)}
|
||||||
|
className="rounded p-1.5 text-neutral-400 hover:bg-neutral-100 hover:text-red-500"
|
||||||
|
title="Loeschen"
|
||||||
|
>
|
||||||
|
<Trash2 className="h-4 w-4" />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatFileSize(bytes: number): string {
|
||||||
|
if (bytes < 1024) return `${bytes} B`;
|
||||||
|
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`;
|
||||||
|
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
||||||
|
}
|
||||||
144
frontend/src/components/documents/DocumentUpload.tsx
Normal file
144
frontend/src/components/documents/DocumentUpload.tsx
Normal file
@@ -0,0 +1,144 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useCallback, useState } from "react";
|
||||||
|
import { useDropzone } from "react-dropzone";
|
||||||
|
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import { Upload, FileText, X, Loader2 } from "lucide-react";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { api } from "@/lib/api";
|
||||||
|
import type { Document } from "@/lib/types";
|
||||||
|
|
||||||
|
interface DocumentUploadProps {
|
||||||
|
caseId: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function DocumentUpload({ caseId }: DocumentUploadProps) {
|
||||||
|
const [files, setFiles] = useState<File[]>([]);
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
|
const uploadMutation = useMutation({
|
||||||
|
mutationFn: async (file: File) => {
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append("file", file);
|
||||||
|
formData.append("title", file.name);
|
||||||
|
return api.postFormData<Document>(`/cases/${caseId}/documents`, formData);
|
||||||
|
},
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["case-documents", caseId] });
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["case", caseId] });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const onDrop = useCallback((acceptedFiles: File[]) => {
|
||||||
|
setFiles((prev) => [...prev, ...acceptedFiles]);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const { getRootProps, getInputProps, isDragActive } = useDropzone({
|
||||||
|
onDrop,
|
||||||
|
disabled: uploadMutation.isPending,
|
||||||
|
});
|
||||||
|
|
||||||
|
function removeFile(index: number) {
|
||||||
|
setFiles((prev) => prev.filter((_, i) => i !== index));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleUpload() {
|
||||||
|
if (files.length === 0) return;
|
||||||
|
|
||||||
|
let successCount = 0;
|
||||||
|
for (const file of files) {
|
||||||
|
try {
|
||||||
|
await uploadMutation.mutateAsync(file);
|
||||||
|
successCount++;
|
||||||
|
} catch (err) {
|
||||||
|
const msg =
|
||||||
|
err && typeof err === "object" && "error" in err
|
||||||
|
? (err as { error: string }).error
|
||||||
|
: file.name;
|
||||||
|
toast.error(`Fehler beim Hochladen: ${msg}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (successCount > 0) {
|
||||||
|
toast.success(
|
||||||
|
successCount === 1
|
||||||
|
? "Dokument hochgeladen"
|
||||||
|
: `${successCount} Dokumente hochgeladen`,
|
||||||
|
);
|
||||||
|
setFiles([]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-3">
|
||||||
|
<div
|
||||||
|
{...getRootProps()}
|
||||||
|
className={`cursor-pointer rounded-md border-2 border-dashed px-6 py-6 text-center transition-colors ${
|
||||||
|
isDragActive
|
||||||
|
? "border-neutral-500 bg-neutral-50"
|
||||||
|
: "border-neutral-300 hover:border-neutral-400"
|
||||||
|
} ${uploadMutation.isPending ? "pointer-events-none opacity-50" : ""}`}
|
||||||
|
>
|
||||||
|
<input {...getInputProps()} />
|
||||||
|
<Upload className="mx-auto h-6 w-6 text-neutral-400" />
|
||||||
|
<p className="mt-2 text-sm text-neutral-600">
|
||||||
|
Dateien hierher ziehen oder{" "}
|
||||||
|
<span className="font-medium text-neutral-900">durchsuchen</span>
|
||||||
|
</p>
|
||||||
|
<p className="mt-1 text-xs text-neutral-400">Max. 50 MB pro Datei</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{files.length > 0 && (
|
||||||
|
<div className="space-y-2">
|
||||||
|
{files.map((file, i) => (
|
||||||
|
<div
|
||||||
|
key={`${file.name}-${i}`}
|
||||||
|
className="flex items-center gap-3 rounded-md border border-neutral-200 bg-neutral-50 px-3 py-2"
|
||||||
|
>
|
||||||
|
<FileText className="h-4 w-4 shrink-0 text-neutral-500" />
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<p className="truncate text-sm text-neutral-900">{file.name}</p>
|
||||||
|
<p className="text-xs text-neutral-400">
|
||||||
|
{formatFileSize(file.size)}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => removeFile(i)}
|
||||||
|
disabled={uploadMutation.isPending}
|
||||||
|
className="rounded p-1 text-neutral-400 hover:bg-neutral-200 hover:text-neutral-600"
|
||||||
|
>
|
||||||
|
<X className="h-3.5 w-3.5" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={handleUpload}
|
||||||
|
disabled={uploadMutation.isPending}
|
||||||
|
className="inline-flex items-center gap-2 rounded-md bg-neutral-900 px-3 py-1.5 text-sm font-medium text-white hover:bg-neutral-800 disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{uploadMutation.isPending ? (
|
||||||
|
<>
|
||||||
|
<Loader2 className="h-3.5 w-3.5 animate-spin" />
|
||||||
|
Hochladen...
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<Upload className="h-3.5 w-3.5" />
|
||||||
|
{files.length === 1 ? "Hochladen" : `${files.length} Dateien hochladen`}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatFileSize(bytes: number): string {
|
||||||
|
if (bytes < 1024) return `${bytes} B`;
|
||||||
|
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`;
|
||||||
|
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
||||||
|
}
|
||||||
329
frontend/src/components/settings/CalDAVSettings.tsx
Normal file
329
frontend/src/components/settings/CalDAVSettings.tsx
Normal file
@@ -0,0 +1,329 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState, useEffect } from "react";
|
||||||
|
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import {
|
||||||
|
RefreshCw,
|
||||||
|
CheckCircle2,
|
||||||
|
AlertCircle,
|
||||||
|
Clock,
|
||||||
|
ArrowUpDown,
|
||||||
|
} from "lucide-react";
|
||||||
|
import { api } from "@/lib/api";
|
||||||
|
import type {
|
||||||
|
Tenant,
|
||||||
|
CalDAVConfig,
|
||||||
|
CalDAVSyncResponse,
|
||||||
|
} from "@/lib/types";
|
||||||
|
|
||||||
|
const SYNC_INTERVALS = [
|
||||||
|
{ value: 5, label: "5 Minuten" },
|
||||||
|
{ value: 15, label: "15 Minuten" },
|
||||||
|
{ value: 30, label: "30 Minuten" },
|
||||||
|
{ value: 60, label: "1 Stunde" },
|
||||||
|
{ value: 120, label: "2 Stunden" },
|
||||||
|
{ value: 360, label: "6 Stunden" },
|
||||||
|
];
|
||||||
|
|
||||||
|
const emptyConfig: CalDAVConfig = {
|
||||||
|
url: "",
|
||||||
|
username: "",
|
||||||
|
password: "",
|
||||||
|
calendar_path: "",
|
||||||
|
sync_enabled: false,
|
||||||
|
sync_interval_minutes: 15,
|
||||||
|
};
|
||||||
|
|
||||||
|
export function CalDAVSettings({ tenant }: { tenant: Tenant }) {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const existing = (tenant.settings as Record<string, unknown>)?.caldav as
|
||||||
|
| Partial<CalDAVConfig>
|
||||||
|
| undefined;
|
||||||
|
const [config, setConfig] = useState<CalDAVConfig>({
|
||||||
|
...emptyConfig,
|
||||||
|
...existing,
|
||||||
|
});
|
||||||
|
const [showPassword, setShowPassword] = useState(false);
|
||||||
|
|
||||||
|
// Reset form when tenant changes
|
||||||
|
useEffect(() => {
|
||||||
|
const caldav = (tenant.settings as Record<string, unknown>)?.caldav as
|
||||||
|
| Partial<CalDAVConfig>
|
||||||
|
| undefined;
|
||||||
|
setConfig({ ...emptyConfig, ...caldav });
|
||||||
|
}, [tenant]);
|
||||||
|
|
||||||
|
// Fetch sync status
|
||||||
|
const { data: syncStatus } = useQuery({
|
||||||
|
queryKey: ["caldav-status"],
|
||||||
|
queryFn: () => api.get<CalDAVSyncResponse>("/caldav/status"),
|
||||||
|
refetchInterval: 30_000,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Save settings
|
||||||
|
const saveMutation = useMutation({
|
||||||
|
mutationFn: (cfg: CalDAVConfig) => {
|
||||||
|
const tenantId =
|
||||||
|
typeof window !== "undefined"
|
||||||
|
? localStorage.getItem("kanzlai_tenant_id")
|
||||||
|
: null;
|
||||||
|
return api.put<Tenant>(`/api/tenants/${tenantId}/settings`, {
|
||||||
|
caldav: cfg,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
onSuccess: (updated) => {
|
||||||
|
queryClient.setQueryData(["tenant-current"], updated);
|
||||||
|
toast.success("CalDAV-Einstellungen gespeichert");
|
||||||
|
},
|
||||||
|
onError: () => {
|
||||||
|
toast.error("Fehler beim Speichern der CalDAV-Einstellungen");
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// Trigger sync
|
||||||
|
const syncMutation = useMutation({
|
||||||
|
mutationFn: () => api.post<CalDAVSyncResponse>("/caldav/sync"),
|
||||||
|
onSuccess: (result) => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["caldav-status"] });
|
||||||
|
if (result.status === "ok") {
|
||||||
|
toast.success(
|
||||||
|
`Synchronisierung abgeschlossen: ${result.sync.items_pushed} gesendet, ${result.sync.items_pulled} empfangen`
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
toast.error("Synchronisierung mit Fehlern abgeschlossen");
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onError: () => {
|
||||||
|
toast.error("Fehler bei der Synchronisierung");
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const handleSave = (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
saveMutation.mutate(config);
|
||||||
|
};
|
||||||
|
|
||||||
|
const hasConfig = config.url && config.username && config.password;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
{/* CalDAV Configuration Form */}
|
||||||
|
<form onSubmit={handleSave} className="space-y-4">
|
||||||
|
<div className="grid gap-4 sm:grid-cols-2">
|
||||||
|
<div className="sm:col-span-2">
|
||||||
|
<label className="mb-1 block text-sm font-medium text-neutral-700">
|
||||||
|
CalDAV-Server URL
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="url"
|
||||||
|
value={config.url}
|
||||||
|
onChange={(e) =>
|
||||||
|
setConfig((c) => ({ ...c, url: e.target.value }))
|
||||||
|
}
|
||||||
|
placeholder="https://dav.example.com/dav"
|
||||||
|
className="w-full rounded-md border border-neutral-200 px-3 py-1.5 text-sm outline-none focus:border-neutral-400 focus:ring-1 focus:ring-neutral-400"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="mb-1 block text-sm font-medium text-neutral-700">
|
||||||
|
Benutzername
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={config.username}
|
||||||
|
onChange={(e) =>
|
||||||
|
setConfig((c) => ({ ...c, username: e.target.value }))
|
||||||
|
}
|
||||||
|
placeholder="user@example.com"
|
||||||
|
className="w-full rounded-md border border-neutral-200 px-3 py-1.5 text-sm outline-none focus:border-neutral-400 focus:ring-1 focus:ring-neutral-400"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="mb-1 block text-sm font-medium text-neutral-700">
|
||||||
|
Passwort
|
||||||
|
</label>
|
||||||
|
<div className="relative">
|
||||||
|
<input
|
||||||
|
type={showPassword ? "text" : "password"}
|
||||||
|
value={config.password}
|
||||||
|
onChange={(e) =>
|
||||||
|
setConfig((c) => ({ ...c, password: e.target.value }))
|
||||||
|
}
|
||||||
|
placeholder="••••••••"
|
||||||
|
className="w-full rounded-md border border-neutral-200 px-3 py-1.5 pr-16 text-sm outline-none focus:border-neutral-400 focus:ring-1 focus:ring-neutral-400"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setShowPassword(!showPassword)}
|
||||||
|
className="absolute right-2 top-1/2 -translate-y-1/2 text-xs text-neutral-500 hover:text-neutral-700"
|
||||||
|
>
|
||||||
|
{showPassword ? "Verbergen" : "Anzeigen"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="sm:col-span-2">
|
||||||
|
<label className="mb-1 block text-sm font-medium text-neutral-700">
|
||||||
|
Kalender-Pfad
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={config.calendar_path}
|
||||||
|
onChange={(e) =>
|
||||||
|
setConfig((c) => ({ ...c, calendar_path: e.target.value }))
|
||||||
|
}
|
||||||
|
placeholder="/dav/calendars/user/default/"
|
||||||
|
className="w-full rounded-md border border-neutral-200 px-3 py-1.5 text-sm outline-none focus:border-neutral-400 focus:ring-1 focus:ring-neutral-400"
|
||||||
|
/>
|
||||||
|
<p className="mt-1 text-xs text-neutral-400">
|
||||||
|
Pfad zum Kalender auf dem CalDAV-Server
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Sync Settings */}
|
||||||
|
<div className="flex flex-col gap-4 border-t border-neutral-200 pt-4 sm:flex-row sm:items-center sm:justify-between">
|
||||||
|
<label className="flex items-center gap-2.5">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={config.sync_enabled}
|
||||||
|
onChange={(e) =>
|
||||||
|
setConfig((c) => ({ ...c, sync_enabled: e.target.checked }))
|
||||||
|
}
|
||||||
|
className="h-4 w-4 rounded border-neutral-300 text-neutral-900 focus:ring-neutral-400"
|
||||||
|
/>
|
||||||
|
<span className="text-sm font-medium text-neutral-700">
|
||||||
|
Automatische Synchronisierung
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<label className="text-sm text-neutral-500">Intervall:</label>
|
||||||
|
<select
|
||||||
|
value={config.sync_interval_minutes}
|
||||||
|
onChange={(e) =>
|
||||||
|
setConfig((c) => ({
|
||||||
|
...c,
|
||||||
|
sync_interval_minutes: Number(e.target.value),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
disabled={!config.sync_enabled}
|
||||||
|
className="rounded-md border border-neutral-200 px-2 py-1 text-sm outline-none focus:border-neutral-400 focus:ring-1 focus:ring-neutral-400 disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{SYNC_INTERVALS.map((opt) => (
|
||||||
|
<option key={opt.value} value={opt.value}>
|
||||||
|
{opt.label}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-3 border-t border-neutral-200 pt-4">
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={saveMutation.isPending}
|
||||||
|
className="rounded-md bg-neutral-900 px-4 py-1.5 text-sm font-medium text-white hover:bg-neutral-800 disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{saveMutation.isPending ? "Speichern..." : "Speichern"}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{hasConfig && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => syncMutation.mutate()}
|
||||||
|
disabled={syncMutation.isPending}
|
||||||
|
className="inline-flex items-center gap-1.5 rounded-md border border-neutral-200 bg-white px-4 py-1.5 text-sm font-medium text-neutral-700 hover:bg-neutral-50 disabled:opacity-50"
|
||||||
|
>
|
||||||
|
<RefreshCw
|
||||||
|
className={`h-3.5 w-3.5 ${syncMutation.isPending ? "animate-spin" : ""}`}
|
||||||
|
/>
|
||||||
|
{syncMutation.isPending
|
||||||
|
? "Synchronisiere..."
|
||||||
|
: "Jetzt synchronisieren"}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
{/* Sync Status */}
|
||||||
|
{syncStatus && syncStatus.last_sync_at !== null && (
|
||||||
|
<SyncStatusDisplay data={syncStatus} />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function SyncStatusDisplay({ data }: { data: CalDAVSyncResponse }) {
|
||||||
|
const hasErrors = data.sync?.errors && data.sync.errors.length > 0;
|
||||||
|
const lastSync = data.sync?.last_sync_at
|
||||||
|
? new Date(data.sync.last_sync_at)
|
||||||
|
: null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={`rounded-lg border p-4 ${
|
||||||
|
hasErrors
|
||||||
|
? "border-red-200 bg-red-50"
|
||||||
|
: "border-emerald-200 bg-emerald-50"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<div className="flex items-start gap-3">
|
||||||
|
{hasErrors ? (
|
||||||
|
<AlertCircle className="mt-0.5 h-4 w-4 shrink-0 text-red-600" />
|
||||||
|
) : (
|
||||||
|
<CheckCircle2 className="mt-0.5 h-4 w-4 shrink-0 text-emerald-600" />
|
||||||
|
)}
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<p
|
||||||
|
className={`text-sm font-medium ${hasErrors ? "text-red-800" : "text-emerald-800"}`}
|
||||||
|
>
|
||||||
|
{hasErrors
|
||||||
|
? "Letzte Synchronisierung mit Fehlern"
|
||||||
|
: "Letzte Synchronisierung erfolgreich"}
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div className="mt-2 flex flex-wrap gap-x-4 gap-y-1 text-xs">
|
||||||
|
{lastSync && (
|
||||||
|
<span className="inline-flex items-center gap-1 text-neutral-600">
|
||||||
|
<Clock className="h-3 w-3" />
|
||||||
|
{lastSync.toLocaleDateString("de-DE", {
|
||||||
|
day: "2-digit",
|
||||||
|
month: "2-digit",
|
||||||
|
year: "numeric",
|
||||||
|
})}{" "}
|
||||||
|
{lastSync.toLocaleTimeString("de-DE", {
|
||||||
|
hour: "2-digit",
|
||||||
|
minute: "2-digit",
|
||||||
|
})}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
<span className="inline-flex items-center gap-1 text-neutral-600">
|
||||||
|
<ArrowUpDown className="h-3 w-3" />
|
||||||
|
{data.sync.items_pushed} gesendet, {data.sync.items_pulled}{" "}
|
||||||
|
empfangen
|
||||||
|
</span>
|
||||||
|
{data.sync.sync_duration && (
|
||||||
|
<span className="text-neutral-400">
|
||||||
|
Dauer: {data.sync.sync_duration}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{hasErrors && (
|
||||||
|
<div className="mt-2 space-y-1">
|
||||||
|
{data.sync.errors!.map((err, i) => (
|
||||||
|
<p key={i} className="text-xs text-red-700">
|
||||||
|
{err}
|
||||||
|
</p>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
167
frontend/src/components/settings/TeamSettings.tsx
Normal file
167
frontend/src/components/settings/TeamSettings.tsx
Normal file
@@ -0,0 +1,167 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { UserPlus, Trash2, Shield, Crown, User } from "lucide-react";
|
||||||
|
import { api } from "@/lib/api";
|
||||||
|
import type { UserTenant } from "@/lib/types";
|
||||||
|
import { Skeleton } from "@/components/ui/Skeleton";
|
||||||
|
import { EmptyState } from "@/components/ui/EmptyState";
|
||||||
|
|
||||||
|
const ROLE_LABELS: Record<string, { label: string; icon: typeof Crown }> = {
|
||||||
|
owner: { label: "Eigentümer", icon: Crown },
|
||||||
|
admin: { label: "Administrator", icon: Shield },
|
||||||
|
member: { label: "Mitglied", icon: User },
|
||||||
|
};
|
||||||
|
|
||||||
|
export function TeamSettings() {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const tenantId =
|
||||||
|
typeof window !== "undefined"
|
||||||
|
? localStorage.getItem("kanzlai_tenant_id")
|
||||||
|
: null;
|
||||||
|
|
||||||
|
const [email, setEmail] = useState("");
|
||||||
|
const [role, setRole] = useState("member");
|
||||||
|
|
||||||
|
const {
|
||||||
|
data: members,
|
||||||
|
isLoading,
|
||||||
|
error,
|
||||||
|
} = useQuery({
|
||||||
|
queryKey: ["tenant-members", tenantId],
|
||||||
|
queryFn: () =>
|
||||||
|
api.get<UserTenant[]>(`/api/tenants/${tenantId}/members`),
|
||||||
|
enabled: !!tenantId,
|
||||||
|
});
|
||||||
|
|
||||||
|
const inviteMutation = useMutation({
|
||||||
|
mutationFn: (data: { email: string; role: string }) =>
|
||||||
|
api.post(`/api/tenants/${tenantId}/invite`, data),
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["tenant-members"] });
|
||||||
|
setEmail("");
|
||||||
|
setRole("member");
|
||||||
|
toast.success("Benutzer eingeladen");
|
||||||
|
},
|
||||||
|
onError: (err: { error?: string }) => {
|
||||||
|
toast.error(err.error || "Fehler beim Einladen");
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const removeMutation = useMutation({
|
||||||
|
mutationFn: (userId: string) =>
|
||||||
|
api.delete(`/api/tenants/${tenantId}/members/${userId}`),
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["tenant-members"] });
|
||||||
|
toast.success("Mitglied entfernt");
|
||||||
|
},
|
||||||
|
onError: (err: { error?: string }) => {
|
||||||
|
toast.error(err.error || "Fehler beim Entfernen");
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const handleInvite = (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!email.trim()) return;
|
||||||
|
inviteMutation.mutate({ email: email.trim(), role });
|
||||||
|
};
|
||||||
|
|
||||||
|
if (isLoading) {
|
||||||
|
return (
|
||||||
|
<div className="space-y-3">
|
||||||
|
<Skeleton className="h-10 w-full" />
|
||||||
|
<Skeleton className="h-10 w-full" />
|
||||||
|
<Skeleton className="h-10 w-full" />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return (
|
||||||
|
<EmptyState
|
||||||
|
icon={User}
|
||||||
|
title="Fehler beim Laden"
|
||||||
|
description="Team-Mitglieder konnten nicht geladen werden."
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
{/* Invite Form */}
|
||||||
|
<form onSubmit={handleInvite} className="flex flex-col gap-3 sm:flex-row">
|
||||||
|
<input
|
||||||
|
type="email"
|
||||||
|
value={email}
|
||||||
|
onChange={(e) => setEmail(e.target.value)}
|
||||||
|
placeholder="name@example.com"
|
||||||
|
className="flex-1 rounded-md border border-neutral-200 px-3 py-1.5 text-sm outline-none focus:border-neutral-400 focus:ring-1 focus:ring-neutral-400"
|
||||||
|
/>
|
||||||
|
<select
|
||||||
|
value={role}
|
||||||
|
onChange={(e) => setRole(e.target.value)}
|
||||||
|
className="rounded-md border border-neutral-200 px-2 py-1.5 text-sm outline-none focus:border-neutral-400 focus:ring-1 focus:ring-neutral-400"
|
||||||
|
>
|
||||||
|
<option value="member">Mitglied</option>
|
||||||
|
<option value="admin">Administrator</option>
|
||||||
|
</select>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={inviteMutation.isPending || !email.trim()}
|
||||||
|
className="inline-flex items-center gap-1.5 rounded-md bg-neutral-900 px-4 py-1.5 text-sm font-medium text-white hover:bg-neutral-800 disabled:opacity-50"
|
||||||
|
>
|
||||||
|
<UserPlus className="h-3.5 w-3.5" />
|
||||||
|
{inviteMutation.isPending ? "Einladen..." : "Einladen"}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
{/* Members List */}
|
||||||
|
{members && members.length > 0 ? (
|
||||||
|
<div className="overflow-hidden rounded-md border border-neutral-200">
|
||||||
|
{members.map((member, i) => {
|
||||||
|
const roleInfo = ROLE_LABELS[member.role] || ROLE_LABELS.member;
|
||||||
|
const RoleIcon = roleInfo.icon;
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={member.user_id}
|
||||||
|
className={`flex items-center justify-between px-4 py-3 ${
|
||||||
|
i < members.length - 1 ? "border-b border-neutral-100" : ""
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<div className="flex h-8 w-8 items-center justify-center rounded-full bg-neutral-100">
|
||||||
|
<RoleIcon className="h-4 w-4 text-neutral-500" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<p className="text-sm font-medium text-neutral-900">
|
||||||
|
{member.user_id.slice(0, 8)}...
|
||||||
|
</p>
|
||||||
|
<p className="text-xs text-neutral-500">{roleInfo.label}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{member.role !== "owner" && (
|
||||||
|
<button
|
||||||
|
onClick={() => removeMutation.mutate(member.user_id)}
|
||||||
|
disabled={removeMutation.isPending}
|
||||||
|
className="rounded-md p-1.5 text-neutral-400 hover:bg-red-50 hover:text-red-600 disabled:opacity-50"
|
||||||
|
title="Mitglied entfernen"
|
||||||
|
>
|
||||||
|
<Trash2 className="h-4 w-4" />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<EmptyState
|
||||||
|
icon={User}
|
||||||
|
title="Noch keine Mitglieder"
|
||||||
|
description="Laden Sie Teammitglieder per E-Mail ein."
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -152,6 +152,30 @@ export interface CalculateResponse {
|
|||||||
deadlines: CalculatedDeadline[];
|
deadlines: CalculatedDeadline[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface CalDAVConfig {
|
||||||
|
url: string;
|
||||||
|
username: string;
|
||||||
|
password: string;
|
||||||
|
calendar_path: string;
|
||||||
|
sync_enabled: boolean;
|
||||||
|
sync_interval_minutes: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CalDAVSyncStatus {
|
||||||
|
tenant_id: string;
|
||||||
|
last_sync_at: string;
|
||||||
|
items_pushed: number;
|
||||||
|
items_pulled: number;
|
||||||
|
errors?: string[];
|
||||||
|
sync_duration: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CalDAVSyncResponse {
|
||||||
|
status: string;
|
||||||
|
sync: CalDAVSyncStatus;
|
||||||
|
last_sync_at?: null;
|
||||||
|
}
|
||||||
|
|
||||||
export interface ApiError {
|
export interface ApiError {
|
||||||
error: string;
|
error: string;
|
||||||
status: number;
|
status: number;
|
||||||
|
|||||||
@@ -55,6 +55,6 @@ export async function middleware(request: NextRequest) {
|
|||||||
|
|
||||||
export const config = {
|
export const config = {
|
||||||
matcher: [
|
matcher: [
|
||||||
"/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)",
|
"/((?!api/|_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)",
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user