Files
paliad/internal/handlers/handlers.go
mAi 7decc5095f feat(t-paliad-191): admin rule-editor HTTP API
Phase 3 Slice 11a admin endpoints under /admin/api/rules, all
gated through auth.RequireAdminFunc:

  GET    /admin/api/rules                  — paginated list with filters
  GET    /admin/api/rules/{id}             — full row
  POST   /admin/api/rules                  — create draft
  PATCH  /admin/api/rules/{id}             — update draft only
  POST   /admin/api/rules/{id}/clone-as-draft
  POST   /admin/api/rules/{id}/publish
  POST   /admin/api/rules/{id}/archive
  POST   /admin/api/rules/{id}/restore
  GET    /admin/api/rules/{id}/audit       — paginated audit log
  GET    /admin/api/rules/{id}/preview     — preview-on-trigger-date
  GET    /admin/api/rules/export-migrations — SQL blob for the
                                              migration-export flow

Every write endpoint takes a `reason` body field; missing reason →
HTTP 400 (ErrAuditReasonRequired surfaced by the service). The
service writes the reason into paliad.audit_reason in the same tx
as the UPDATE so mig 079's trigger captures it.

writeRuleEditorError maps service-level typed errors to HTTP
statuses (404 for ErrRuleNotFound, 409 for ErrInvalidLifecycleState
+ ErrCyclicSpawn, 400 for ErrAuditReasonRequired + ErrInvalidInput).

dbServices gains a ruleEditor field; Services.RuleEditor in the
public bundle gets wired from main.go via NewRuleEditorService.

Route ordering: export-migrations is registered BEFORE the
{id}-shaped routes so the static path doesn't get captured by the
{id} placeholder. (Go 1.22+'s ServeMux requires the explicit
registration order for shadowing-resolution.)

Frontend (Slice 11b) will hire a new coder to surface the API in
an admin UI. Slice 11a ships the backend in isolation so the editor
can drive the lifecycle via curl / mai instructions today.
2026-05-15 01:50:15 +02:00

587 lines
34 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
EventTrigger *services.EventTriggerService
RuleEditor *services.RuleEditorService
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
Derivation *services.DerivationService
UserView *services.UserViewService
Broadcast *services.BroadcastService
Pin *services.PinService
CardLayout *services.CardLayoutService
Projection *services.ProjectionService
// Paliadin is wired when DATABASE_URL is set. The concrete backend
// is picked in cmd/server/main.go based on PALIADIN_REMOTE_HOST
// (remote → mRiver via SSH) or local tmux availability. Stays nil
// without DATABASE_URL; in that case the per-request handler gate
// 404s anyway.
Paliadin services.Paliadin
}
func Register(mux *http.ServeMux, client *auth.Client, giteaAPIToken string, svc *Services) {
authClient = client
giteaToken = giteaAPIToken
if svc != nil && svc.Paliadin != nil {
paliadinSvc = svc.Paliadin
}
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,
eventTrigger: svc.EventTrigger,
ruleEditor: svc.RuleEditor,
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,
approval: svc.Approval,
derivation: svc.Derivation,
userView: svc.UserView,
broadcast: svc.Broadcast,
pin: svc.Pin,
cardLayout: svc.CardLayout,
projection: svc.Projection,
}
}
// 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("GET /tools/verfahrensablauf", handleVerfahrensablaufPage)
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("POST /api/tools/event-trigger", handleEventTriggerCalculate)
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)
// t-paliad-171 / t-paliad-173 — SmartTimeline (Verlauf-tab redesign).
// /timeline returns the merged timeline (actuals + Slice 2 projections).
// /timeline/milestone is the "Eigener Meilenstein" write path.
// /timeline/anchor is the click-to-anchor write (Slice 2).
// /timeline/skip is the "ist nicht eingetreten" decision (§6.4).
protected.HandleFunc("GET /api/projects/{id}/timeline", handleGetProjectTimeline)
// t-paliad-177 Slice 2 — iCal feed (deadlines + appointments only).
protected.HandleFunc("GET /api/projects/{id}/timeline.ics", handleGetProjectTimelineICS)
protected.HandleFunc("POST /api/projects/{id}/timeline/milestone", handleCreateProjectTimelineMilestone)
protected.HandleFunc("POST /api/projects/{id}/timeline/anchor", handleProjectTimelineAnchor)
protected.HandleFunc("POST /api/projects/{id}/timeline/skip", handleProjectTimelineSkip)
// /counterclaim creates a CCR sub-project linked via the new
// paliad.projects.counterclaim_of FK (t-paliad-174 Slice 3).
protected.HandleFunc("POST /api/projects/{id}/counterclaim", handleCreateProjectCounterclaim)
protected.HandleFunc("GET /api/projects/{id}/children", handleListProjectChildren)
protected.HandleFunc("GET /api/projects/{id}/tree", handleGetProjectTree)
protected.HandleFunc("POST /api/projects/{id}/pin", handlePinProject)
protected.HandleFunc("DELETE /api/projects/{id}/pin", handleUnpinProject)
protected.HandleFunc("GET /api/user-pinned-projects", handleListPinnedProjects)
protected.HandleFunc("GET /api/projects/cards-preview", handleProjectsCardsPreview)
protected.HandleFunc("GET /api/user-card-layouts", handleListCardLayouts)
protected.HandleFunc("POST /api/user-card-layouts", handleCreateCardLayout)
protected.HandleFunc("PATCH /api/user-card-layouts/{id}", handleUpdateCardLayout)
protected.HandleFunc("DELETE /api/user-card-layouts/{id}", handleDeleteCardLayout)
protected.HandleFunc("POST /api/user-card-layouts/{id}/set-default", handleSetDefaultCardLayout)
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)
// t-paliad-139 — sub-team aggregation surfaces for the Team tab.
protected.HandleFunc("GET /api/projects/{id}/team/derived", handleListDerivedTeam)
protected.HandleFunc("GET /api/projects/{id}/team/from-descendants", handleListDescendantStaffedTeam)
// t-paliad-139 — project ↔ partner-unit attachment management.
protected.HandleFunc("GET /api/projects/{id}/partner-units", handleListAttachedUnits)
protected.HandleFunc("POST /api/projects/{id}/partner-units", handleAttachPartnerUnit)
protected.HandleFunc("DELETE /api/projects/{id}/partner-units/{unit_id}", handleDetachPartnerUnit)
// 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)
// t-paliad-139 — set unit_role on a member.
protected.HandleFunc("PATCH /api/partner-units/{id}/members/{user_id}/role", handleSetUnitMemberRole)
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))
// t-paliad-177 — standalone Project Timeline / Chart page (Slice 1).
// Horizontal SVG renderer mounted client-side; reuses the existing
// /api/projects/{id}/timeline JSON endpoint for data.
protected.HandleFunc("GET /projects/{id}/chart", gateOnboarded(handleProjectsChartPage))
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))
// t-paliad-147 — bulk team-email broadcast.
// /api/team/broadcast: project lead OR global_admin → BroadcastService gates.
// /admin/broadcasts page + list/detail API: visibility-gated in service
// (global_admin sees all; sender sees own).
protected.HandleFunc("GET /api/team/memberships", gateOnboarded(handleListMembershipsIndex))
protected.HandleFunc("POST /api/team/broadcast", gateOnboarded(handleTeamBroadcast))
protected.HandleFunc("GET /admin/broadcasts", gateOnboarded(handleAdminBroadcastsPage))
protected.HandleFunc("GET /api/admin/broadcasts", gateOnboarded(handleListBroadcasts))
protected.HandleFunc("GET /api/admin/broadcasts/{id}", gateOnboarded(handleGetBroadcast))
// 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.
// t-paliad-191 Slice 11a — admin rule-editor API.
protected.HandleFunc("GET /admin/api/rules", adminGate(users, handleAdminListRules))
protected.HandleFunc("GET /admin/api/rules/export-migrations", adminGate(users, handleAdminExportRuleMigrations))
protected.HandleFunc("GET /admin/api/rules/{id}", adminGate(users, handleAdminGetRule))
protected.HandleFunc("POST /admin/api/rules", adminGate(users, handleAdminCreateRule))
protected.HandleFunc("PATCH /admin/api/rules/{id}", adminGate(users, handleAdminPatchRule))
protected.HandleFunc("POST /admin/api/rules/{id}/clone-as-draft", adminGate(users, handleAdminCloneAsDraft))
protected.HandleFunc("POST /admin/api/rules/{id}/publish", adminGate(users, handleAdminPublishRule))
protected.HandleFunc("POST /admin/api/rules/{id}/archive", adminGate(users, handleAdminArchiveRule))
protected.HandleFunc("POST /admin/api/rules/{id}/restore", adminGate(users, handleAdminRestoreRule))
protected.HandleFunc("GET /admin/api/rules/{id}/audit", adminGate(users, handleAdminGetRuleAudit))
protected.HandleFunc("GET /admin/api/rules/{id}/preview", adminGate(users, handleAdminPreviewRule))
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))
// t-paliad-138 — approval-policy CRUD (admin only). The inbox
// + decision endpoints are NOT admin-only — they're below.
protected.HandleFunc("GET /api/projects/{id}/approval-policies",
adminGate(users, handleListApprovalPolicies))
protected.HandleFunc("PUT /api/projects/{id}/approval-policies/{entity_type}/{lifecycle}",
adminGate(users, handlePutApprovalPolicy))
protected.HandleFunc("DELETE /api/projects/{id}/approval-policies/{entity_type}/{lifecycle}",
adminGate(users, handleDeleteApprovalPolicy))
// t-paliad-154 — approval-policy authoring page + admin APIs for
// per-partner-unit defaults, matrix view, bulk-apply, and the
// existence-check used by /inbox.
protected.HandleFunc("GET /admin/approval-policies",
adminGate(users, gateOnboarded(handleAdminApprovalPoliciesPage)))
protected.HandleFunc("GET /api/admin/partner-units/{unit_id}/approval-policies",
adminGate(users, handleListUnitApprovalPolicies))
protected.HandleFunc("PUT /api/admin/partner-units/{unit_id}/approval-policies/{entity_type}/{lifecycle}",
adminGate(users, handlePutUnitApprovalPolicy))
protected.HandleFunc("DELETE /api/admin/partner-units/{unit_id}/approval-policies/{entity_type}/{lifecycle}",
adminGate(users, handleDeleteUnitApprovalPolicy))
protected.HandleFunc("GET /api/admin/approval-policies/seeded",
adminGate(users, handleApprovalPoliciesSeeded))
protected.HandleFunc("GET /api/admin/approval-policies/matrix",
adminGate(users, handleApprovalPoliciesMatrix))
protected.HandleFunc("POST /api/admin/approval-policies/apply-to-descendants",
adminGate(users, handleApplyMatrixToDescendants))
}
// t-paliad-138 — approval inbox + decision endpoints (any authenticated
// user; the service layer gates approve/reject by required-role match).
if svc != nil && svc.Approval != nil {
protected.HandleFunc("GET /inbox", gateOnboarded(handleInboxPage))
protected.HandleFunc("GET /api/inbox/pending-mine", handleListInboxPendingMine)
protected.HandleFunc("GET /api/inbox/mine", handleListInboxMine)
protected.HandleFunc("GET /api/inbox/count", handleInboxCount)
protected.HandleFunc("GET /api/approval-requests/{id}", handleGetApprovalRequest)
protected.HandleFunc("POST /api/approval-requests/{id}/approve", handleApproveApprovalRequest)
protected.HandleFunc("POST /api/approval-requests/{id}/reject", handleRejectApprovalRequest)
protected.HandleFunc("POST /api/approval-requests/{id}/revoke", handleRevokeApprovalRequest)
// t-paliad-154 — form-time effective policy lookup. Reachable by
// every authenticated user (NOT admin-gated) so deadline +
// appointment forms can render the 4-eye hint.
protected.HandleFunc("GET /api/projects/{id}/approval-policies/effective",
gateOnboarded(handleProjectEffectivePolicy))
}
// t-paliad-144 Phase A1+A2 — Custom Views (substrate + user_views CRUD
// + page shells). API endpoints register when the substrate services are
// wired; page shells register unconditionally so /views itself stays
// reachable for the empty-state onboarding.
if svc != nil && svc.UserView != nil && svc.Event != nil {
// API
protected.HandleFunc("GET /api/user-views", handleListUserViews)
protected.HandleFunc("POST /api/user-views", handleCreateUserView)
protected.HandleFunc("GET /api/user-views/{id}", handleGetUserView)
protected.HandleFunc("PATCH /api/user-views/{id}", handleUpdateUserView)
protected.HandleFunc("DELETE /api/user-views/{id}", handleDeleteUserView)
protected.HandleFunc("POST /api/user-views/{id}/touch", handleTouchUserView)
protected.HandleFunc("POST /api/views/run", handleRunAdhocView)
protected.HandleFunc("POST /api/views/{slug}/run", handleRunSavedView)
protected.HandleFunc("GET /api/views/system", handleListSystemViews)
// Page shells (A2)
protected.HandleFunc("GET /views", gateOnboarded(handleViewsLandingPage))
protected.HandleFunc("GET /views/new", gateOnboarded(handleViewsNewPage))
protected.HandleFunc("GET /views/{slug}/edit", gateOnboarded(handleViewsEditPage))
protected.HandleFunc("GET /views/{slug}", gateOnboarded(handleViewsShellPage))
}
// t-paliad-146 — Paliadin (PoC). Routes register unconditionally;
// the per-request handler gate (requirePaliadinOwner) returns 404
// for any authenticated user other than services.PaliadinOwnerEmail.
// No deploy-time toggle — the gate is in the code, not in the env.
protected.HandleFunc("GET /paliadin", gateOnboarded(handlePaliadinPage))
protected.HandleFunc("POST /api/paliadin/turn", handlePaliadinTurn)
protected.HandleFunc("GET /api/paliadin/stream/{id}", handlePaliadinStream)
protected.HandleFunc("GET /api/paliadin/turns/{id}", handlePaliadinTurnGet)
// Crash-resistant history hydrate (t-paliad-161 follow-up): both
// Paliadin surfaces use this to seed their UI from the DB before
// consulting localStorage.
protected.HandleFunc("GET /api/paliadin/history", handlePaliadinHistory)
protected.HandleFunc("POST /api/paliadin/reset", handlePaliadinReset)
// Agent-suggested write path (t-paliad-161 Slice D). Owner-gated;
// drafts a deadline / appointment that lands in the approval pipeline.
protected.HandleFunc("POST /api/paliadin/suggest/deadline", handlePaliadinSuggestDeadline)
protected.HandleFunc("POST /api/paliadin/suggest/appointment", handlePaliadinSuggestAppointment)
protected.HandleFunc("GET /admin/paliadin", gateOnboarded(handleAdminPaliadinPage))
protected.HandleFunc("GET /api/admin/paliadin/stats", handleAdminPaliadinStats)
protected.HandleFunc("GET /api/admin/paliadin/turns", handleAdminPaliadinTurns)
// 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)
}
// parseDirectOnly reads a `direct_only=true|false` query value. Returns true
// only for the explicit "true" / "1" forms; everything else (including empty)
// is the subtree-aggregating default per t-paliad-139.
func parseDirectOnly(raw string) bool {
switch raw {
case "true", "1":
return true
default:
return false
}
}