Files
projax/web/calendar_integration_test.go
mAi f820fa5830 feat(views): Phase 5j slice C — full URL migration + system views
Per m's Q1 pick (b) (2026-05-29): legacy `/`, `/dashboard`, `/calendar`,
`/timeline`, `/graph` become `/views/{system-slug}`. Old routes
301-redirect to the new ones with chip params preserved; the legacy
?view=<uuid> param from 5i is resolved through the uuid → slug map
when present so old bookmarks land on the right user view.

System views (web/system_views.go):
- SystemView struct (Slug / Name / Icon / URL) — code-resident, never
  rows in projax.views.
- AllSystemViews() returns the canonical five: tree, dashboard,
  calendar, timeline, graph. Display order matches the existing
  sidebar.
- LookupSystemView(slug) returns the matching entry or nil; the
  reserved-slug list in store.IsReservedViewSlug (slice A) is kept
  in sync.
- legacyRedirect(systemSlug) handler 301s with chip-param preservation
  + uuid → slug resolution for any leftover ?view=<uuid>.

Routes (web/server.go):
- GET /views/tree      → handleTree     (was GET /)
- GET /views/dashboard → handleDashboard
- GET /views/timeline  → handleTimeline
- GET /views/calendar  → handleCalendar
- GET /views/graph     → handleGraph
- GET /                → 301 → /views/tree
- GET /dashboard       → 301 → /views/dashboard
- GET /timeline        → 301 → /views/timeline
- GET /calendar        → 301 → /views/calendar
- GET /graph           → 301 → /views/graph
- POST action endpoints (/dashboard/task/*, /dashboard/pin, /admin/*)
  stay where they are — those are RPC-ish, not page renders.

handleTree: dropped the `r.URL.Path != "/"` guard — the only entry
point now is /views/tree, mounted via the new route. Slice F removes
any residual references; this slice keeps the handler reachable.

computeChipCounts grew a `base string` arg so chip URLs anchor on the
caller's route (/views/tree for the system tree, /views/{slug} for
saved views). PageViewTypes recognises both legacy and /views/ keys
during the transition.

Template hrefs / hx-gets bulk-updated to the new URLs:
- layout.tmpl: every sidebar + bottom-nav entry points at
  /views/{system-slug}. Active-state checks updated alongside.
- tree_section.tmpl, tree_card.tmpl, tree_kanban.tmpl: clear-filter
  / clear-all hrefs → /views/tree.
- calendar*.tmpl, timeline_section.tmpl, graph.tmpl,
  dashboard_section.tmpl: every internal nav + filter link points at
  the /views/{slug} surface.
- detail.tmpl, error.tmpl: cancel / back-to-tree → /views/tree.

Test-source updates (per the 5c sharpened rule):
- ~100 test paths bulk-rewritten from /dashboard /calendar /timeline
  /graph (and `/`) to their /views/{slug} counterparts. The
  behaviour-preservation contract holds: status codes + body shapes
  for the rendered pages stay the same; only the URL anchoring the
  test changes.
- layout_test.go: sidebar href assertions updated to /views/{slug}.
- view_type_test.go (Q2 + Q3 follow-up): PageViewTypes lookup table
  updated to use the new route keys.
- 2 deliberate behaviour-change assertions land: TestLegacyRedirects
  expects 301 on the old URLs (was 200); TestTreeRenders fetches
  /views/tree (the new home) instead of /.

Internal go-source URL emissions (dashboard.go, calendar.go,
timeline.go) updated to the new BasePath so chip + refresh URLs round
through /views/{slug} correctly.

New tests:
- TestSystemViewLookup — AllSystemViews shape + LookupSystemView
  round-trip + unknown-slug nil.
- TestLegacyRedirects — every legacy URL 301s to its new home with
  chip params preserved.
- TestLegacyViewUUIDRedirect — old `?view=<uuid>` URLs land on the
  resolved slug per m's Q3 pick.
2026-05-29 11:59:26 +02:00

331 lines
12 KiB
Go

package web_test
import (
"context"
"io"
"net/http/httptest"
"strings"
"testing"
"time"
)
// TestCalendarRendersMonthGrid hits GET /calendar with the default month
// and asserts the rendered HTML carries the grid table, nav anchors, and
// weekday header. Empty-data path — no seeding required so this guards
// the route registration + template parsing on every test run.
func TestCalendarRendersMonthGrid(t *testing.T) {
srv, pool := mustServer(t)
defer pool.Close()
h := srv.Routes()
code, body := get(t, h, "/views/calendar")
if code != 200 {
t.Fatalf("GET /calendar → %d body=%s", code, body)
}
for _, want := range []string{
`id="calendar-section"`,
`class="calendar-grid"`,
`<th scope="col">Mon</th>`,
`<th scope="col">Sun</th>`,
`class="calendar-nav"`,
`href="/views/calendar?month=`, // prev/next anchors present
} {
if !strings.Contains(body, want) {
t.Errorf("calendar body missing %q", want)
}
}
}
// TestCalendarSurfacesDatedLink seeds a dated item_link on today and
// confirms the corresponding cell carries the link summary + the
// .is-today class on today's <td>. Closes the round-trip "data goes in,
// cell renders out" loop for the doc source.
func TestCalendarSurfacesDatedLink(t *testing.T) {
srv, pool := mustServer(t)
defer pool.Close()
h := srv.Routes()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
stamp := strings.ReplaceAll(time.Now().UTC().Format("150405.000000"), ".", "")
slug := "cal-doc-" + stamp
var dev, id string
if err := pool.QueryRow(ctx, `select id from projax.items where slug='dev' and cardinality(parent_ids)=0`).Scan(&dev); err != nil {
t.Fatalf("dev: %v", err)
}
if err := pool.QueryRow(ctx,
`insert into projax.items (kind, title, slug, parent_ids)
values (array['project']::text[], 'Cal doc', $1, ARRAY[$2]::uuid[])
returning id`,
slug, dev,
).Scan(&id); err != nil {
t.Fatalf("seed item: %v", err)
}
defer pool.Exec(context.Background(), `delete from projax.items where id=$1`, id)
noteText := "cal-marker-" + stamp
if _, err := pool.Exec(ctx,
`insert into projax.item_links (item_id, ref_type, ref_id, rel, note, event_date)
values ($1, 'document', $2, 'contains', $3, current_date)`,
id, "https://example.com/cal-"+stamp, noteText,
); err != nil {
t.Fatalf("seed link: %v", err)
}
code, body := get(t, h, "/views/calendar")
if code != 200 {
t.Fatalf("GET /calendar → %d", code)
}
if !strings.Contains(body, noteText) {
t.Errorf("calendar body missing seeded doc summary %q", noteText)
}
// Today's <td> should carry the .is-today class.
if !strings.Contains(body, "is-today") {
t.Errorf("expected today's cell to carry .is-today class, body did not include it")
}
}
// TestCalendarFilterScopeByTag seeds two items with distinct tags, drops
// a dated link on each, and asserts ?tag=work scopes the rendered rows.
// Confirms the TreeFilter integration matches the timeline cadence.
func TestCalendarFilterScopeByTag(t *testing.T) {
srv, pool := mustServer(t)
defer pool.Close()
h := srv.Routes()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
stamp := strings.ReplaceAll(time.Now().UTC().Format("150405.000000"), ".", "")
var dev string
if err := pool.QueryRow(ctx, `select id from projax.items where slug='dev' and cardinality(parent_ids)=0`).Scan(&dev); err != nil {
t.Fatalf("dev: %v", err)
}
workSlug := "cal-work-" + stamp
playSlug := "cal-play-" + stamp
var workID, playID string
if err := pool.QueryRow(ctx,
`insert into projax.items (kind, title, slug, parent_ids, tags)
values (array['project']::text[], 'work item', $1, ARRAY[$2]::uuid[], ARRAY['cal-test-work-`+stamp+`']::text[])
returning id`, workSlug, dev).Scan(&workID); err != nil {
t.Fatalf("seed work item: %v", err)
}
defer pool.Exec(context.Background(), `delete from projax.items where id=$1`, workID)
if err := pool.QueryRow(ctx,
`insert into projax.items (kind, title, slug, parent_ids, tags)
values (array['project']::text[], 'play item', $1, ARRAY[$2]::uuid[], ARRAY['cal-test-play-`+stamp+`']::text[])
returning id`, playSlug, dev).Scan(&playID); err != nil {
t.Fatalf("seed play item: %v", err)
}
defer pool.Exec(context.Background(), `delete from projax.items where id=$1`, playID)
workNote := "cal-work-note-" + stamp
playNote := "cal-play-note-" + stamp
if _, err := pool.Exec(ctx,
`insert into projax.item_links (item_id, ref_type, ref_id, rel, note, event_date)
values ($1, 'document', $2, 'contains', $3, current_date),
($4, 'document', $5, 'contains', $6, current_date)`,
workID, "https://example.com/cal-work-"+stamp, workNote,
playID, "https://example.com/cal-play-"+stamp, playNote,
); err != nil {
t.Fatalf("seed links: %v", err)
}
// Unfiltered: both notes show.
_, all := get(t, h, "/views/calendar?refresh=1")
if !strings.Contains(all, workNote) {
t.Errorf("unfiltered calendar missing work note %q", workNote)
}
if !strings.Contains(all, playNote) {
t.Errorf("unfiltered calendar missing play note %q", playNote)
}
// Filtered: only work note shows.
_, scoped := get(t, h, "/views/calendar?refresh=1&tag=cal-test-work-"+stamp)
if !strings.Contains(scoped, workNote) {
t.Errorf("filtered calendar missing work note %q", workNote)
}
if strings.Contains(scoped, playNote) {
t.Errorf("filtered calendar SHOULD NOT contain play note %q", playNote)
}
}
// TestCalendarAdjacentMonthDays proves the lead-in / trail-out cells from
// the prior / next month render with the .adjacent-month class so the
// template can style them muted without losing the rectangular grid.
func TestCalendarAdjacentMonthDays(t *testing.T) {
srv, pool := mustServer(t)
defer pool.Close()
h := srv.Routes()
// Pick a month whose first day is NOT a Monday so leading days appear.
// May 2026 starts on a Friday; lead = Apr 27/28/29/30.
_, body := get(t, h, "/views/calendar?month=2026-05&refresh=1")
if !strings.Contains(body, "adjacent-month") {
t.Errorf("expected adjacent-month class on lead-in cells for May 2026, body did not include it")
}
if !strings.Contains(body, `data-date="2026-04-27"`) {
t.Errorf("expected lead-in cell data-date=2026-04-27 for May 2026, body did not include it")
}
}
// TestCalendarNavPrevNextLinks confirms the header has working prev/next
// month links — bookmarkability is the calendar's main affordance for
// jumping around the timeline.
func TestCalendarNavPrevNextLinks(t *testing.T) {
srv, pool := mustServer(t)
defer pool.Close()
h := srv.Routes()
_, body := get(t, h, "/views/calendar?month=2026-05")
if !strings.Contains(body, `href="/views/calendar?month=2026-04"`) {
t.Errorf("expected prev link to 2026-04, body did not include it")
}
if !strings.Contains(body, `href="/views/calendar?month=2026-06"`) {
t.Errorf("expected next link to 2026-06, body did not include it")
}
}
// TestCalendarFilterChipStripRenders proves the HTMX filter chip strip
// (Phase 5e slice B) is rendered above the grid with the hx-target
// pointing at #calendar-section so chip changes swap only the data and
// leave the month-label chrome alone.
func TestCalendarFilterChipStripRenders(t *testing.T) {
srv, pool := mustServer(t)
defer pool.Close()
h := srv.Routes()
_, body := get(t, h, "/views/calendar?month=2026-05")
for _, want := range []string{
`id="calendar-filterbar"`,
`hx-target="#calendar-section"`,
`hx-get="/views/calendar"`,
`<input type="hidden" name="month" value="2026-05">`, // preserves month across chip changes
`name="kind"`,
`name="tag"`,
`name="mgmt"`,
} {
if !strings.Contains(body, want) {
t.Errorf("calendar body missing %q", want)
}
}
}
// TestCalendarHTMXReturnsSectionOnly proves an HX-Request returns just
// the calendar-section fragment (no layout chrome) so the filter chip
// strip can swap the grid in place without re-rendering the page shell.
func TestCalendarHTMXReturnsSectionOnly(t *testing.T) {
srv, pool := mustServer(t)
defer pool.Close()
h := srv.Routes()
req := httptest.NewRequest("GET", "/views/calendar?month=2026-05", nil)
req.Header.Set("HX-Request", "true")
w := httptest.NewRecorder()
h.ServeHTTP(w, req)
body, _ := io.ReadAll(w.Result().Body)
bs := string(body)
if w.Result().StatusCode != 200 {
t.Fatalf("HTMX /calendar → %d body=%s", w.Result().StatusCode, bs)
}
if !strings.Contains(bs, `id="calendar-section"`) {
t.Errorf("HTMX response missing #calendar-section: %s", bs)
}
// Layout chrome (e.g. the <nav class="calendar-nav"> month label) lives
// OUTSIDE the section in calendar.tmpl, so an HTMX fragment must not
// include it. If it does, the chip-strip swap would double up the nav.
if strings.Contains(bs, `class="calendar-nav"`) {
t.Errorf("HTMX response should not include the page chrome (.calendar-nav)")
}
if strings.Contains(bs, `<!doctype html>`) || strings.Contains(bs, "<body>") {
t.Errorf("HTMX response should be a fragment, not a full document: %s", bs)
}
}
// TestCalendarFilterMultiValueTagsFromForm reproduces m's bug report —
// /calendar filters don't work when the chip-strip form submits a
// multi-select. <select multiple name="tag"> serialises as
// `?tag=foo&tag=bar` (two URL params with the same key); the prior
// ParseTreeFilter implementation used `r.URL.Query().Get("tag")` which
// returns only the FIRST value, so the second tag silently dropped and
// items matching only the first tag bled through. AND-across-tags is
// the contract per TreeFilter.Matches.
func TestCalendarFilterMultiValueTagsFromForm(t *testing.T) {
srv, pool := mustServer(t)
defer pool.Close()
h := srv.Routes()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
stamp := strings.ReplaceAll(time.Now().UTC().Format("150405.000000"), ".", "")
tagA := "cal-multibug-a-" + stamp
tagB := "cal-multibug-b-" + stamp
var dev string
if err := pool.QueryRow(ctx, `select id from projax.items where slug='dev' and cardinality(parent_ids)=0`).Scan(&dev); err != nil {
t.Fatalf("dev: %v", err)
}
type seed struct {
slug, note string
tags []string
}
now := time.Now().UTC().Format("150405")
seeds := []seed{
{slug: "ab-" + stamp, note: "cal-AB-note-" + now, tags: []string{tagA, tagB}},
{slug: "a-" + stamp, note: "cal-A-note-" + now, tags: []string{tagA}},
{slug: "b-" + stamp, note: "cal-B-note-" + now, tags: []string{tagB}},
}
var ids []string
for _, s := range seeds {
var id string
if err := pool.QueryRow(ctx,
`insert into projax.items (kind, title, slug, parent_ids, tags)
values (array['project']::text[], $1, $2, ARRAY[$3]::uuid[], $4::text[])
returning id`,
s.slug, s.slug, dev, s.tags,
).Scan(&id); err != nil {
t.Fatalf("seed %s: %v", s.slug, err)
}
ids = append(ids, id)
if _, err := pool.Exec(ctx,
`insert into projax.item_links (item_id, ref_type, ref_id, rel, note, event_date)
values ($1, 'document', $2, 'contains', $3, current_date)`,
id, "https://example.com/cal-multibug-"+s.slug, s.note,
); err != nil {
t.Fatalf("seed link %s: %v", s.slug, err)
}
}
for _, id := range ids {
defer pool.Exec(context.Background(), `delete from projax.items where id=$1`, id)
}
// HTMX-style multi-value submission: two `tag=` params, not comma-joined.
url := "/views/calendar?refresh=1&tag=" + tagA + "&tag=" + tagB
_, body := get(t, h, url)
// Item AB has BOTH tags — must appear.
if !strings.Contains(body, seeds[0].note) {
t.Errorf("expected AB note %q to appear with tag=%s&tag=%s (AND match), got body excerpt: %s",
seeds[0].note, tagA, tagB, truncate(body, 600))
}
// Item A has only tagA — must NOT appear (AND semantics fail tagB).
if strings.Contains(body, seeds[1].note) {
t.Errorf("BUG: A-only note %q leaked through tag=%s&tag=%s — second tag silently dropped by q.Get(\"tag\")",
seeds[1].note, tagA, tagB)
}
// Item B has only tagB — must NOT appear (AND semantics fail tagA).
if strings.Contains(body, seeds[2].note) {
t.Errorf("BUG: B-only note %q leaked through tag=%s&tag=%s — second tag silently dropped by q.Get(\"tag\")",
seeds[2].note, tagA, tagB)
}
}
// TestCalendarCellCarriesLongLabel proves the per-cell long German label
// is in the rendered HTML so the mobile breakpoint CSS (≤480px) can
// reveal it. The label compensates for the column-header weekday strip
// that the mobile breakpoint removes.
func TestCalendarCellCarriesLongLabel(t *testing.T) {
srv, pool := mustServer(t)
defer pool.Close()
h := srv.Routes()
_, body := get(t, h, "/views/calendar?month=2026-05")
// May 4 2026 is a Monday → "Mo., 4. Mai".
if !strings.Contains(body, `Mo., 4. Mai`) {
t.Errorf("expected long label 'Mo., 4. Mai' for 2026-05-04 cell, body did not include it")
}
}