Files
guestguard/internal/api/events.go
T
Kwaku Danso e5b187c575 feat(tier2): event branding + UX polish — Block D
Backend
- Migration 0010 adds event_branding (one row per event; all fields
  nullable so a brand-new event renders with defaults)
- BrandingRepo with COALESCE/NULLIF upsert semantics: nil pointer
  preserves the existing value, "" clears the field to NULL
- internal/uploads package: ImageStore interface + LocalFSStore (dev),
  pure-stdlib decode + re-encode that strips EXIF and rejects anything
  that isn't valid JPEG/PNG. Size cap 2 MB, random 16-byte filenames
- GET /events/{id}/branding (viewer+) returns the row plus the
  AllowedFonts list so the frontend picker stays in sync
- PUT /events/{id}/branding (editor+) validates hex colours, font
  allowlist, and refuses image URLs whose path doesn't start with
  /uploads/ (blocks arbitrary-origin <img> smuggling on guest pages)
- POST /uploads/image (authed) → fresh CDN URL; GET /uploads/{file}
  serves with year-long cache (immutable random names)
- GET /access/{token} now embeds the host's branding so the RSVP page
  can render in their colours/font with their logo + cover
- docker-compose mounts a named volume for uploads
- Custom-domain sub-block deferred to Tier 3 per the plan

Frontend
- BrandingCard.vue: colour pickers, font dropdown, logo + cover upload
  with progressive disclosure, live preview pane that re-renders on
  every keystroke
- RSVP page applies branding via CSS vars at the section root, so
  primary colour theme + font cascade through every child card. Cover
  image renders as a banner above the form; logo lands in the header
- Submit button background switches to var(--brand-primary) when set
- Mounted on the event detail page below the guests block

Plus the small UX fixes from the e2e walkthrough:
- Nav: dropped the top-level "Events" link; the logo doubles as the
  home affordance (→ /dashboard when signed in, → / otherwise). Account
  + Billing + Sign out live under a profile dropdown (avatar with
  initials, opens on click, closes on outside-click / Esc / route nav)
- Renamed "Back to dashboard" → "Back to events" across event detail,
  billing, account, and new-event pages

Tests
- TestBrandingGetReturnsDefaults / TestBrandingPutPersists /
  TestBrandingPutRejectsBadInputs / TestUploadAndServeImage /
  TestUploadRejectsNonImage — all pass
- Domain tests for IsValidHexColor + IsAllowedFont
- Full integration suite green (176s)

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-18 12:04:09 +01:00

283 lines
7.3 KiB
Go

package api
import (
"encoding/json"
"errors"
"net/http"
"regexp"
"strconv"
"time"
"github.com/google/uuid"
"github.com/alchemistkay/guestguard/internal/domain"
"github.com/alchemistkay/guestguard/internal/storage"
)
type eventHandler struct {
repo *storage.EventRepo
collabs *storage.CollaboratorRepo
enforcer *tierEnforcer
}
type createEventRequest struct {
Name string `json:"name"`
Slug string `json:"slug"`
EventDate time.Time `json:"event_date"`
Venue string `json:"venue"`
MaxCapacity int `json:"max_capacity"`
Settings map[string]any `json:"settings"`
Status string `json:"status"`
}
var slugRe = regexp.MustCompile(`^[a-z0-9]+(-[a-z0-9]+)*$`)
func (h *eventHandler) create(w http.ResponseWriter, r *http.Request) {
hostID, ok := hostFromContext(w, r)
if !ok {
return
}
if !h.enforcer.allowEventCreate(w, r, hostID) {
return
}
var req createEventRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "invalid json")
return
}
if req.Name == "" {
writeError(w, http.StatusBadRequest, "name is required")
return
}
if !slugRe.MatchString(req.Slug) {
writeError(w, http.StatusBadRequest, "slug must be lowercase alphanumeric with hyphens")
return
}
if req.EventDate.IsZero() {
writeError(w, http.StatusBadRequest, "event_date is required")
return
}
status := domain.EventStatus(req.Status)
if status == "" {
status = domain.EventStatusDraft
}
if !status.Valid() {
writeError(w, http.StatusBadRequest, "invalid status")
return
}
ev, err := h.repo.Create(r.Context(), storage.CreateEventParams{
HostID: hostID,
Name: req.Name,
Slug: req.Slug,
EventDate: req.EventDate,
Venue: req.Venue,
MaxCapacity: req.MaxCapacity,
Settings: req.Settings,
Status: status,
})
if err != nil {
if errors.Is(err, domain.ErrSlugTaken) {
writeError(w, http.StatusConflict, "slug already in use")
return
}
writeError(w, http.StatusInternalServerError, "failed to create event")
return
}
writeJSON(w, http.StatusCreated, ev)
}
// eventView wraps an Event with the caller's role so the dashboard UI can
// branch (e.g. hide the "Delete event" button for editors/viewers).
type eventView struct {
*domain.Event
YourRole domain.Role `json:"your_role"`
}
func (h *eventHandler) get(w http.ResponseWriter, r *http.Request) {
hostID, ok := hostFromContext(w, r)
if !ok {
return
}
id, ok := parseIDParam(w, r, "id")
if !ok {
return
}
ev, role, ok := requireRole(w, r, h.repo, h.collabs, id, hostID, domain.RoleViewer)
if !ok {
return
}
writeJSON(w, http.StatusOK, eventView{Event: ev, YourRole: role})
}
func (h *eventHandler) list(w http.ResponseWriter, r *http.Request) {
hostID, ok := hostFromContext(w, r)
if !ok {
return
}
q := r.URL.Query()
limit := atoiOr(q.Get("limit"), 50)
offset := atoiOr(q.Get("offset"), 0)
// Block C: the dashboard shows every event the user has any role on,
// not just events they own. Pull the role map up front so we can
// annotate each card with `your_role` — the frontend uses that to
// split "your events" from "shared with you" without a follow-up call.
roles, err := h.collabs.RolesForUser(r.Context(), hostID)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to resolve memberships")
return
}
collabIDs := make([]uuid.UUID, 0, len(roles))
for id := range roles {
collabIDs = append(collabIDs, id)
}
events, err := h.repo.ListForUser(r.Context(), hostID, collabIDs, limit, offset)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to list events")
return
}
views := make([]eventView, 0, len(events))
for _, ev := range events {
role := roles[ev.ID]
if role == "" && ev.HostID == hostID {
// Defensive: legacy events created before Block C's seed-on-
// create may not have a collaborator row. Fall back to the
// host_id check so they still show as owned.
role = domain.RoleOwner
}
views = append(views, eventView{Event: ev, YourRole: role})
}
writeJSON(w, http.StatusOK, map[string]any{
"events": views,
"limit": limit,
"offset": offset,
})
}
type updateEventRequest struct {
Name *string `json:"name"`
Slug *string `json:"slug"`
EventDate *time.Time `json:"event_date"`
Venue *string `json:"venue"`
MaxCapacity *int `json:"max_capacity"`
Settings *map[string]any `json:"settings"`
Status *string `json:"status"`
}
func (h *eventHandler) update(w http.ResponseWriter, r *http.Request) {
hostID, ok := hostFromContext(w, r)
if !ok {
return
}
id, ok := parseIDParam(w, r, "id")
if !ok {
return
}
// Block C: editor+ can patch event metadata. The plan reserves DELETE
// (and the existing host_id row) for owners only.
if _, _, ok := requireRole(w, r, h.repo, h.collabs, id, hostID, domain.RoleEditor); !ok {
return
}
var req updateEventRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "invalid json")
return
}
params := storage.UpdateEventParams{
Name: req.Name,
EventDate: req.EventDate,
Venue: req.Venue,
MaxCapacity: req.MaxCapacity,
Settings: req.Settings,
}
if req.Slug != nil {
if !slugRe.MatchString(*req.Slug) {
writeError(w, http.StatusBadRequest, "slug must be lowercase alphanumeric with hyphens")
return
}
params.Slug = req.Slug
}
if req.Status != nil {
s := domain.EventStatus(*req.Status)
if !s.Valid() {
writeError(w, http.StatusBadRequest, "invalid status")
return
}
params.Status = &s
}
ev, err := h.repo.UpdateByID(r.Context(), id, params)
if err != nil {
switch {
case errors.Is(err, domain.ErrEventNotFound):
writeError(w, http.StatusNotFound, "event not found")
case errors.Is(err, domain.ErrSlugTaken):
writeError(w, http.StatusConflict, "slug already in use")
default:
writeError(w, http.StatusInternalServerError, "failed to update event")
}
return
}
writeJSON(w, http.StatusOK, ev)
}
func (h *eventHandler) delete(w http.ResponseWriter, r *http.Request) {
hostID, ok := hostFromContext(w, r)
if !ok {
return
}
id, ok := parseIDParam(w, r, "id")
if !ok {
return
}
// Block C: only owners can delete an event. Editors get 403; viewers
// and non-members get 404.
if _, _, ok := requireRole(w, r, h.repo, h.collabs, id, hostID, domain.RoleOwner); !ok {
return
}
if err := h.repo.DeleteByID(r.Context(), id); err != nil {
if errors.Is(err, domain.ErrEventNotFound) {
writeError(w, http.StatusNotFound, "event not found")
return
}
writeError(w, http.StatusInternalServerError, "failed to delete event")
return
}
w.WriteHeader(http.StatusNoContent)
}
func parseIDParam(w http.ResponseWriter, r *http.Request, name string) (uuid.UUID, bool) {
return parseRawUUID(w, name, r.PathValue(name))
}
func parseRawUUID(w http.ResponseWriter, name, raw string) (uuid.UUID, bool) {
if raw == "" {
writeError(w, http.StatusBadRequest, name+" is required")
return uuid.Nil, false
}
id, err := uuid.Parse(raw)
if err != nil {
writeError(w, http.StatusBadRequest, name+" must be a valid uuid")
return uuid.Nil, false
}
return id, true
}
func atoiOr(s string, fallback int) int {
if s == "" {
return fallback
}
if n, err := strconv.Atoi(s); err == nil {
return n
}
return fallback
}