Files
paliad/internal/handlers/handlers.go
m 4ebbf2c1af feat(t-paliad-138): ApprovalService core + tests
Commit 2 of 8 — the workflow engine for the 4-Augen-Prüfung. Wires the
service into the handlers.Services bundle so commit 3 can call into
SubmitCreate/Update/Complete/Delete from DeadlineService and
AppointmentService.

Public surface:

- Submit{Create,Update,Complete,Delete} — invoked by Deadline /
  AppointmentService inside their existing tx. Looks up policy,
  runs the deadlock check, inserts paliad.approval_requests, marks
  the entity pending, emits the *_approval_requested project_events
  audit row.
- Approve / Reject / Revoke — top-level operations (own tx). Approve
  finalises the lifecycle (clears pending markers + sets approved_by
  for non-delete; hard-deletes for delete). Reject / Revoke revert
  the entity from pre_image (delete a pending-create, restore date
  fields, NULL completed_at).
- ListPendingForApprover / ListSubmittedByUser / GetRequest /
  PendingCountForUser — read paths the inbox + bell will hit in
  commit 5.
- ListPolicies / UpsertPolicy / DeletePolicy — CRUD for the
  authoring page in commit 4.

Self-approval is blocked at three layers:
  1. canApprove() returns ErrSelfApproval when caller == requester.
  2. The DB CHECK constraint approval_requests_no_self_approval.
  3. The deadlock check excludes the requester from the pool.

Strict-ladder helper levelOf(role) mirrors the SQL function added in
migration 054. Path-walk authorization: ancestors with eligible roles
qualify for descendant requests (matches the visibility predicate).

Tests:
- Pure-Go: levelOf strict-ladder semantics, IsValidRequiredRole,
  approvalEventType. All pass under `go test`.
- Live-DB (TEST_DATABASE_URL): no-policy noop; submit→approve cycle;
  reject-create deletes; reject-update restores pre_image;
  no-qualified-approver fail; revoke flow; policy CRUD roundtrip.
  Skipped when TEST_DATABASE_URL is unset, mirroring the existing
  audit_service_test pattern.

No call sites in DeadlineService / AppointmentService yet — that's
commit 3. Paliad continues to behave identically until that lands.
2026-05-06 15:21:47 +02:00

395 lines
23 KiB
Go

package handlers
import (
"encoding/json"
"net/http"
"mgit.msbls.de/m/paliad/internal/auth"
"mgit.msbls.de/m/paliad/internal/services"
)
var authClient *auth.Client
// noCacheAssets wraps a static-file handler so /assets/* and /icons/* always
// trigger a conditional GET. http.FileServer already emits Last-Modified, so
// browsers send If-Modified-Since on the next visit and the server replies
// 304 when the file is unchanged — fast for repeat loads, fresh on deploy.
func noCacheAssets(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-cache, must-revalidate")
h.ServeHTTP(w, r)
})
}
// noCachePages wraps a handler so its response always revalidates. Combined
// with the build-time `?v=<buildVersion>` stamp on /assets/*.js and /css URLs
// in dist/*.html, this is what makes a deploy actually reach users: the HTML
// is re-fetched (or 304'd) on every navigation, and any change to the asset
// version triggers a fresh script load.
func noCachePages(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-cache, must-revalidate")
h.ServeHTTP(w, r)
})
}
// Services bundles the Phase B + C database-backed services. Pass nil if
// DATABASE_URL was unset; the matter-management endpoints will return 503.
type Services struct {
Project *services.ProjectService
Team *services.TeamService
PartnerUnit *services.PartnerUnitService
Party *services.PartyService
Deadline *services.DeadlineService
Appointment *services.AppointmentService
CalDAV *services.CalDAVService
Rules *services.DeadlineRuleService
Calculator *services.DeadlineCalculator
Users *services.UserService
Fristenrechner *services.FristenrechnerService
EventDeadline *services.EventDeadlineService
DeadlineSearch *services.DeadlineSearchService
EventCategory *services.EventCategoryService
EventType *services.EventTypeService
Dashboard *services.DashboardService
Note *services.NoteService
ChecklistInst *services.ChecklistInstanceService
Mail *services.MailService
Invite *services.InviteService
Agenda *services.AgendaService
Audit *services.AuditService
EmailTemplate *services.EmailTemplateService
Link *services.LinkService
Event *services.EventService
Courts *services.CourtService
Approval *services.ApprovalService
}
func Register(mux *http.ServeMux, client *auth.Client, giteaAPIToken string, svc *Services) {
authClient = client
giteaToken = giteaAPIToken
if svc != nil {
dbSvc = &dbServices{
projects: svc.Project,
team: svc.Team,
partnerUnit: svc.PartnerUnit,
parties: svc.Party,
deadline: svc.Deadline,
appointment: svc.Appointment,
caldav: svc.CalDAV,
rules: svc.Rules,
calc: svc.Calculator,
users: svc.Users,
fristenrechner: svc.Fristenrechner,
eventDeadline: svc.EventDeadline,
deadlineSearch: svc.DeadlineSearch,
eventCategory: svc.EventCategory,
eventType: svc.EventType,
dashboard: svc.Dashboard,
note: svc.Note,
checklistInst: svc.ChecklistInst,
mail: svc.Mail,
invite: svc.Invite,
agenda: svc.Agenda,
audit: svc.Audit,
emailTemplate: svc.EmailTemplate,
link: svc.Link,
event: svc.Event,
courts: svc.Courts,
}
}
// API endpoints (JSON, public)
mux.HandleFunc("POST /api/login", handleAPILogin)
mux.HandleFunc("POST /api/register", handleAPIRegister)
// Public pages — wrapped in noCachePages so the HTML always revalidates
// and picks up new build-versioned /assets URLs after a deploy.
mux.Handle("GET /login", noCachePages(http.HandlerFunc(handleLoginPage)))
mux.Handle("GET /logout", noCachePages(http.HandlerFunc(handleLogout)))
// Landing page: public to unauthenticated visitors, redirects logged-in
// users to /dashboard. Handled on the outer mux so the auth Middleware
// doesn't bounce unauthenticated visitors to /login.
mux.Handle("GET /{$}", noCachePages(http.HandlerFunc(handleRootPage)))
// Static assets (public). Cache-Control: no-cache forces browsers to
// revalidate every load. Combined with the Last-Modified header that
// http.FileServer emits, repeat visits get a fast 304 when assets are
// unchanged but pick up a fresh bundle the moment we deploy. Without
// this, browsers were heuristically caching /assets/*.js for the whole
// freshness window and continuing to execute the previous deploy's
// (broken) bundle even after the SW had been kill-switched (t-paliad-043).
mux.Handle("GET /assets/", noCacheAssets(http.StripPrefix("/assets/", http.FileServer(http.Dir("dist/assets")))))
// PWA static surface (public): manifest, icons, service worker. The SW
// must be served from the application origin; its scope is /, so the file
// has to live at /sw.js (a SW served from /assets/sw.js could only claim
// /assets/* by default).
mux.HandleFunc("GET /manifest.json", servePWAManifest)
mux.Handle("GET /icons/", noCacheAssets(http.StripPrefix("/icons/", http.FileServer(http.Dir("dist/icons")))))
mux.HandleFunc("GET /sw.js", servePWAServiceWorker)
// Protected routes
protected := http.NewServeMux()
protected.HandleFunc("GET /tools/kostenrechner", handleKostenrechnerPage)
protected.HandleFunc("POST /api/tools/kostenrechner", handleKostenrechnerAPI)
protected.HandleFunc("GET /tools/fristenrechner", handleFristenrechnerPage)
protected.HandleFunc("POST /api/tools/fristenrechner", handleFristenrechnerAPI)
protected.HandleFunc("POST /api/tools/fristenrechner/calculate-rule", handleFristenrechnerCalculateRule)
protected.HandleFunc("GET /api/tools/proceeding-types", handleProceedingTypes)
protected.HandleFunc("GET /api/tools/trigger-events", handleTriggerEventsList)
protected.HandleFunc("POST /api/tools/event-deadlines", handleEventDeadlinesCalculate)
protected.HandleFunc("GET /api/tools/courts", handleCourtsList)
protected.HandleFunc("GET /api/tools/fristenrechner/search", handleFristenrechnerSearch)
protected.HandleFunc("GET /api/tools/fristenrechner/event-categories", handleFristenrechnerEventCategories)
protected.HandleFunc("GET /downloads", handleDownloadsPage)
protected.HandleFunc("GET /glossary", handleGlossaryPage)
protected.HandleFunc("GET /api/glossary", handleGlossaryAPI)
protected.HandleFunc("POST /api/glossary/suggest", handleGlossarySuggest)
protected.HandleFunc("GET /files/{filename}", handleFileDownload)
protected.HandleFunc("POST /api/files/refresh", handleFileRefresh)
protected.HandleFunc("GET /links", handleLinksPage)
protected.HandleFunc("GET /api/links", handleLinksAPI)
protected.HandleFunc("POST /api/links/suggest", handleLinkSuggest)
protected.HandleFunc("POST /api/links/feedback", handleLinkFeedback)
protected.HandleFunc("GET /api/links/suggestions/count", handleSuggestionCount)
protected.HandleFunc("GET /tools/gebuehrentabellen", handleGebuehrentabellenPage)
protected.HandleFunc("GET /api/tools/gebuehrentabellen", handleGebuehrentabellenAPI)
protected.HandleFunc("GET /api/tools/gebuehrentabellen/lookup", handleGebuehrentabellenLookup)
protected.HandleFunc("POST /api/tools/gebuehrentabellen/feedback", handleGebuehrentabellenFeedback)
protected.HandleFunc("GET /checklists", handleChecklistsPage)
protected.HandleFunc("GET /checklists/instances/{id}", handleChecklistInstancePage)
protected.HandleFunc("GET /checklists/{slug}", handleChecklistDetailPage)
protected.HandleFunc("GET /api/checklists", handleChecklistsAPI)
protected.HandleFunc("GET /api/checklists/{slug}", handleChecklistAPI)
protected.HandleFunc("POST /api/checklists/feedback", handleChecklistsFeedback)
protected.HandleFunc("GET /api/checklists/{slug}/instances", handleListChecklistInstancesForTemplate)
protected.HandleFunc("POST /api/checklists/{slug}/instances", handleCreateChecklistInstance)
protected.HandleFunc("GET /api/checklist-instances", handleListAllChecklistInstances)
protected.HandleFunc("GET /api/checklist-instances/{id}", handleGetChecklistInstance)
protected.HandleFunc("PATCH /api/checklist-instances/{id}", handleUpdateChecklistInstance)
protected.HandleFunc("POST /api/checklist-instances/{id}/reset", handleResetChecklistInstance)
protected.HandleFunc("DELETE /api/checklist-instances/{id}", handleDeleteChecklistInstance)
protected.HandleFunc("GET /api/projects/{id}/checklists", handleListChecklistInstancesForProject)
protected.HandleFunc("GET /courts", handleCourtsPage)
protected.HandleFunc("GET /api/courts", handleCourtsAPI)
protected.HandleFunc("POST /api/courts/feedback", handleCourtsFeedback)
protected.HandleFunc("GET /changelog", handleChangelogPage)
protected.HandleFunc("GET /api/changelog", handleChangelogAPI)
protected.HandleFunc("GET /api/changelog/unseen-count", handleChangelogUnseenCount)
// Phase B (DB-backed) — return 503 if DATABASE_URL unset.
protected.HandleFunc("GET /api/deadline-rules", handleListDeadlineRules)
protected.HandleFunc("GET /api/proceeding-types-db", handleListProceedingTypesDB)
protected.HandleFunc("POST /api/deadlines/calculate", handleCalculateDeadlines)
// Projects v2 (hierarchical tree — t-paliad-024).
protected.HandleFunc("GET /api/projects", handleListProjects)
protected.HandleFunc("POST /api/projects", handleCreateProject)
protected.HandleFunc("GET /api/projects/tree", handleGetProjectsTree)
protected.HandleFunc("GET /api/projects/{id}", handleGetProject)
protected.HandleFunc("PATCH /api/projects/{id}", handleUpdateProject)
protected.HandleFunc("DELETE /api/projects/{id}", handleDeleteProject)
protected.HandleFunc("GET /api/projects/{id}/events", handleListProjectEvents)
protected.HandleFunc("GET /api/projects/{id}/children", handleListProjectChildren)
protected.HandleFunc("GET /api/projects/{id}/tree", handleGetProjectTree)
protected.HandleFunc("GET /api/projects/{id}/ancestors", handleListProjectAncestors)
protected.HandleFunc("GET /api/projects/{id}/parties", handleListParties)
protected.HandleFunc("POST /api/projects/{id}/parties", handleCreateParty)
// Team membership endpoints for Project detail "Team" tab.
protected.HandleFunc("GET /api/projects/{id}/team", handleListProjectTeam)
protected.HandleFunc("POST /api/projects/{id}/team", handleAddProjectTeamMember)
protected.HandleFunc("DELETE /api/projects/{id}/team/{user_id}", handleRemoveProjectTeamMember)
// Partner units (structural partner-led units; legacy "Dezernate").
protected.HandleFunc("GET /api/partner-units", handleListPartnerUnits)
protected.HandleFunc("POST /api/partner-units", handleCreatePartnerUnit)
protected.HandleFunc("GET /api/partner-units/{id}", handleGetPartnerUnit)
protected.HandleFunc("PATCH /api/partner-units/{id}", handleUpdatePartnerUnit)
protected.HandleFunc("DELETE /api/partner-units/{id}", handleDeletePartnerUnit)
protected.HandleFunc("GET /api/partner-units/{id}/members", handleListPartnerUnitMembers)
protected.HandleFunc("POST /api/partner-units/{id}/members", handleAddPartnerUnitMember)
protected.HandleFunc("DELETE /api/partner-units/{id}/members/{user_id}", handleRemovePartnerUnitMember)
protected.HandleFunc("DELETE /api/parties/{id}", handleDeleteParty)
// Phase F — Appointments (appointments)
protected.HandleFunc("GET /api/appointments", handleListAppointments)
protected.HandleFunc("GET /api/appointments/summary", handleAppointmentsSummary)
protected.HandleFunc("POST /api/appointments", handleCreateAppointment)
protected.HandleFunc("GET /api/appointments/{id}", handleGetAppointment)
protected.HandleFunc("PATCH /api/appointments/{id}", handleUpdateAppointment)
protected.HandleFunc("DELETE /api/appointments/{id}", handleDeleteAppointment)
protected.HandleFunc("GET /api/projects/{id}/appointments", handleListAppointmentsForProject)
// Phase F — CalDAV configuration (per-user, encrypted at rest)
protected.HandleFunc("GET /api/caldav-config", handleGetCalDAVConfig)
protected.HandleFunc("PUT /api/caldav-config", handlePutCalDAVConfig)
protected.HandleFunc("DELETE /api/caldav-config", handleDeleteCalDAVConfig)
protected.HandleFunc("POST /api/caldav-config/test", handleTestCalDAVConfig)
protected.HandleFunc("GET /api/caldav-config/log", handleCalDAVSyncLog)
// t-paliad-088 — Event Types (categorization for Deadlines).
protected.HandleFunc("GET /api/event-types", handleListEventTypes)
protected.HandleFunc("GET /api/event-types/suggest", handleSuggestEventTypes)
protected.HandleFunc("POST /api/event-types", handleCreateEventType)
protected.HandleFunc("PATCH /api/event-types/{id}", handleUpdateEventType)
// t-paliad-110 — unified events endpoint backing the shared EventsPage
// rendered on /deadlines and /appointments. Coexists with the
// type-specific /api/deadlines + /api/appointments endpoints (calendars,
// project-detail panes, mobile/PWA still call those directly).
protected.HandleFunc("GET /api/events", handleListEvents)
protected.HandleFunc("GET /api/events/summary", handleEventsSummary)
// Phase E — Deadlines (persistent deadlines)
protected.HandleFunc("GET /api/deadlines", handleListDeadlines)
protected.HandleFunc("GET /api/deadlines/summary", handleDeadlinesSummary)
protected.HandleFunc("GET /api/deadlines/{id}", handleGetDeadline)
protected.HandleFunc("PATCH /api/deadlines/{id}", handleUpdateDeadline)
protected.HandleFunc("PATCH /api/deadlines/{id}/complete", handleCompleteDeadline)
protected.HandleFunc("PATCH /api/deadlines/{id}/reopen", handleReopenDeadline)
protected.HandleFunc("DELETE /api/deadlines/{id}", handleDeleteDeadline)
protected.HandleFunc("GET /api/projects/{id}/deadlines", handleListDeadlinesForProject)
protected.HandleFunc("POST /api/projects/{id}/deadlines", handleCreateDeadline)
protected.HandleFunc("POST /api/projects/{id}/deadlines/bulk", handleBulkCreateDeadlines)
// Phase I — Notes (polymorphic notes)
protected.HandleFunc("GET /api/projects/{id}/notes", handleListNotesForProject)
protected.HandleFunc("POST /api/projects/{id}/notes", handleCreateNoteForProject)
protected.HandleFunc("GET /api/deadlines/{id}/notes", handleListNotesForDeadline)
protected.HandleFunc("POST /api/deadlines/{id}/notes", handleCreateNoteForDeadline)
protected.HandleFunc("GET /api/appointments/{id}/notes", handleListNotesForAppointment)
protected.HandleFunc("POST /api/appointments/{id}/notes", handleCreateNoteForAppointment)
protected.HandleFunc("PATCH /api/notes/{id}", handleUpdateNote)
protected.HandleFunc("DELETE /api/notes/{id}", handleDeleteNote)
// Global search — mixes static curated content with visibility-gated DB
// lookups across every major surface. See internal/handlers/search.go.
protected.HandleFunc("GET /api/search", handleSearch)
protected.HandleFunc("GET /api/me", handleGetMe)
protected.HandleFunc("PATCH /api/me", handleUpdateMe)
protected.HandleFunc("GET /api/users", handleListUsers)
protected.HandleFunc("GET /api/offices", handleListOffices)
protected.HandleFunc("GET /api/dashboard", handleDashboardAPI)
protected.HandleFunc("GET /api/agenda", handleAgendaAPI)
// Invitations — send a colleague a Paliad invite email.
protected.HandleFunc("POST /api/invite", handleInvite)
protected.HandleFunc("GET /api/invite", handleInviteStatus)
// First-login profile capture — authenticated but NOT behind the
// onboarding gate (it's the one page a user without paliad.users may reach).
protected.HandleFunc("GET /onboarding", handleOnboardingPage)
protected.HandleFunc("POST /api/onboarding", handleCreateOnboarding)
// Phase G — Dashboard (logged-in landing). Server-renders the data
// payload inline; client boots from window.__PALIAD_DASHBOARD__ with no
// waterfall fetch (design audit §2.3).
protected.HandleFunc("GET /dashboard", gateOnboarded(handleDashboardPage))
protected.HandleFunc("GET /agenda", gateOnboarded(handleAgendaPage))
// Phase D — server-rendered Projects pages.
protected.HandleFunc("GET /projects", gateOnboarded(handleProjectsListPage))
protected.HandleFunc("GET /projects/new", gateOnboarded(handleProjectsNewPage))
protected.HandleFunc("GET /projects/{id}", gateOnboarded(handleProjectsDetailPage))
protected.HandleFunc("GET /projects/{id}/history", gateOnboarded(handleProjectsDetailPage))
protected.HandleFunc("GET /projects/{id}/events", gateOnboarded(handleProjectsDetailPage))
protected.HandleFunc("GET /projects/{id}/children", gateOnboarded(handleProjectsDetailPage))
protected.HandleFunc("GET /projects/{id}/parties", gateOnboarded(handleProjectsDetailPage))
protected.HandleFunc("GET /projects/{id}/deadlines", gateOnboarded(handleProjectsDetailPage))
protected.HandleFunc("GET /projects/{id}/appointments", gateOnboarded(handleProjectsDetailPage))
protected.HandleFunc("GET /projects/{id}/documents", gateOnboarded(handleProjectsDetailPage))
protected.HandleFunc("GET /projects/{id}/notes", gateOnboarded(handleProjectsDetailPage))
protected.HandleFunc("GET /projects/{id}/checklists", gateOnboarded(handleProjectsDetailPage))
protected.HandleFunc("GET /projects/{id}/team", gateOnboarded(handleProjectsDetailPage))
protected.HandleFunc("GET /projects/{id}/deadlines/new", gateOnboarded(handleDeadlinesNewPage))
protected.HandleFunc("GET /projects/{id}/appointments/new", gateOnboarded(handleAppointmentsNewPage))
// t-paliad-115 — canonical /events URL for the unified Fristen + Termine
// surface. The page reads ?type=… for prefilled type filter and ?view=…
// for prefilled view (cards / list / calendar). The legacy /deadlines and
// /appointments list URLs 301-redirect to the typed /events variants.
protected.HandleFunc("GET /events", gateOnboarded(handleEventsListPage))
protected.HandleFunc("GET /deadlines", gateOnboarded(handleDeadlinesListRedirect))
protected.HandleFunc("GET /deadlines/new", gateOnboarded(handleDeadlinesNewPage))
protected.HandleFunc("GET /deadlines/calendar", gateOnboarded(handleDeadlinesCalendarPage))
protected.HandleFunc("GET /deadlines/{id}", gateOnboarded(handleDeadlinesDetailPage))
// Phase F — Appointments pages
protected.HandleFunc("GET /appointments", gateOnboarded(handleAppointmentsListRedirect))
protected.HandleFunc("GET /appointments/new", gateOnboarded(handleAppointmentsNewPage))
protected.HandleFunc("GET /appointments/calendar", gateOnboarded(handleAppointmentsCalendarPage))
protected.HandleFunc("GET /appointments/{id}", gateOnboarded(handleAppointmentsDetailPage))
// Team directory — browsable list of all onboarded users (t-paliad-029).
protected.HandleFunc("GET /team", gateOnboarded(handleTeamPage))
// Settings
protected.HandleFunc("GET /settings", gateOnboarded(handleSettingsPage))
protected.HandleFunc("GET /settings/{tab}", handleSettingsTabRedirect)
// Admin team management — page + API endpoints. RequireAdmin gates every
// route at the middleware layer so the handlers themselves don't repeat
// the role check. Only available when the DB is configured (the lookup
// hits paliad.users).
if svc != nil && svc.Users != nil {
adminGate := auth.RequireAdminFunc
users := svc.Users
protected.HandleFunc("GET /admin", adminGate(users, gateOnboarded(handleAdminIndexPage)))
protected.HandleFunc("GET /admin/team", adminGate(users, gateOnboarded(handleAdminTeamPage)))
protected.HandleFunc("GET /admin/audit-log", adminGate(users, gateOnboarded(handleAdminAuditLogPage)))
protected.HandleFunc("GET /admin/partner-units", adminGate(users, gateOnboarded(handleAdminPartnerUnitsPage)))
protected.HandleFunc("GET /admin/email-templates", adminGate(users, gateOnboarded(handleAdminEmailTemplatesPage)))
protected.HandleFunc("GET /admin/email-templates/{key}", adminGate(users, gateOnboarded(handleAdminEmailTemplatesEditPage)))
protected.HandleFunc("GET /admin/event-types", adminGate(users, gateOnboarded(handleAdminEventTypesPage)))
protected.HandleFunc("GET /api/admin/users", adminGate(users, handleAdminListUsers))
protected.HandleFunc("POST /api/admin/users", adminGate(users, handleAdminCreateUser))
protected.HandleFunc("GET /api/admin/users/unonboarded", adminGate(users, handleAdminListUnonboarded))
protected.HandleFunc("PATCH /api/admin/users/{id}", adminGate(users, handleAdminUpdateUser))
protected.HandleFunc("DELETE /api/admin/users/{id}", adminGate(users, handleAdminDeleteUser))
protected.HandleFunc("GET /api/audit-log", adminGate(users, handleListAuditLog))
protected.HandleFunc("GET /api/admin/email-templates", adminGate(users, handleAdminListEmailTemplates))
protected.HandleFunc("GET /api/admin/email-templates/{key}/variables", adminGate(users, handleAdminEmailTemplateVariables))
protected.HandleFunc("GET /api/admin/email-templates/{key}/{lang}", adminGate(users, handleAdminGetEmailTemplate))
protected.HandleFunc("PUT /api/admin/email-templates/{key}/{lang}", adminGate(users, handleAdminSaveEmailTemplate))
protected.HandleFunc("POST /api/admin/email-templates/{key}/{lang}/preview", adminGate(users, handleAdminPreviewEmailTemplate))
protected.HandleFunc("POST /api/admin/email-templates/{key}/{lang}/reset", adminGate(users, handleAdminResetEmailTemplate))
protected.HandleFunc("GET /api/admin/email-templates/{key}/{lang}/versions", adminGate(users, handleAdminListEmailTemplateVersions))
protected.HandleFunc("POST /api/admin/email-templates/{key}/{lang}/restore/{version_id}", adminGate(users, handleAdminRestoreEmailTemplateVersion))
// t-paliad-089 — admin Event-Type moderation panel.
protected.HandleFunc("GET /api/admin/event-types", adminGate(users, handleAdminListEventTypes))
protected.HandleFunc("GET /api/admin/event-types/private", adminGate(users, handleAdminListPrivateEventTypes))
protected.HandleFunc("POST /api/admin/event-types/archive", adminGate(users, handleAdminBulkArchiveEventTypes))
protected.HandleFunc("POST /api/admin/event-types/merge", adminGate(users, handleAdminMergeEventTypes))
protected.HandleFunc("POST /api/admin/event-types/{id}/promote", adminGate(users, handleAdminPromoteEventType))
protected.HandleFunc("POST /api/admin/event-types/{id}/restore", adminGate(users, handleAdminRestoreEventType))
}
// Catch-all 404 — runs for any authenticated path that no more-specific
// pattern claimed. Renders the chromed shell with HTTP 404 (Bug 9 from
// tests/smoke-auth-2026-04-25.md). Must be registered last on this mux.
protected.HandleFunc("/", handleNotFoundPage)
// Legacy German URLs redirect 301 on the OUTER mux so old bookmarks
// land on the new path before hitting the auth middleware (avoids a
// login→redirect round-trip from unauthenticated visitors).
registerLegacyRedirects(mux)
// Session middleware refreshes tokens; user-id middleware extracts the
// JWT sub claim into the request context for handlers that need it.
// noCachePages wraps the lot so every page response revalidates — combined
// with build-time ?v= stamping on /assets URLs, that's how a new deploy
// reaches users on their next navigation.
mux.Handle("/", noCachePages(client.Middleware(client.WithUserID(protected))))
}
func writeJSON(w http.ResponseWriter, status int, data any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(data)
}