Files
projax/web/calendar_integration_test.go
mAi 6f0a318979 fix(filters): preserve every value from <select multiple> filter strips
Symptom (m-reported): /calendar filters don't work.

Root cause: ParseTreeFilter and calendar's ?kind parser both used
`r.URL.Query().Get(key)` to read tag/mgmt/has/status/kind. `Get()`
returns ONLY the first value when a URL has the same key repeated, and
the HTMX filter-strip forms (calendar_section.tmpl, timeline_section,
dashboard_section, graph, bulk) all use `<select multiple name="tag">`
which the browser serialises as `?tag=foo&tag=bar` — repeated params,
not the comma-joined `?tag=foo,bar` the tree page emits from its hidden
input. Every second-and-beyond chip silently dropped on every filter
submission across every page with a multi-select strip; m happened to
catch it on /calendar.

Fix (single helper, four call-site swaps):

- web/server.go parseValues(q, key): collects q[key] (the full slice of
  values), joins on comma, runs parseCSV. Accepts both URL shapes:
    ?tag=foo,bar          → ["foo", "bar"]
    ?tag=foo&tag=bar      → ["foo", "bar"]
    ?tag=foo,bar&tag=baz  → ["foo", "bar", "baz"]

- web/tree_filter.go ParseTreeFilter: tag / mgmt / status / has all
  switch from `parseCSV(q.Get(...))` to `parseValues(q, ...)`. q / show-
  archived / public stay on `q.Get` — they're single-value by design.

- web/calendar.go parseCalendarQuery: ?kind handling drops the bespoke
  q.Get + strings.Split + dedup-map and uses `parseValues(..., "kind")`
  for the same reason. Behaviour preserved for legacy comma-joined
  `?kind=event,doc` AND new repeated-param submission.

Regression test:

- TestCalendarFilterMultiValueTagsFromForm seeds three items — one with
  both test tags (A+B), one with only A, one with only B — drops a
  dated link on each, then probes `/calendar?tag=A&tag=B`. Before the
  fix the A-only note leaked through (the parser kept just tag=A);
  after, only the A+B item appears per the AND-across-tags contract.

Full web suite green. Pre-existing db/TestBackfillTagsFromArea failure
unchanged (independent of this change).

Same fix transparently repairs /timeline, /dashboard, /graph, /bulk —
they all consume ParseTreeFilter and shared the bug.
2026-05-26 11:56:42 +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, "/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="/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, "/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, "/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, "/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, "/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, "/calendar?month=2026-05")
if !strings.Contains(body, `href="/calendar?month=2026-04"`) {
t.Errorf("expected prev link to 2026-04, body did not include it")
}
if !strings.Contains(body, `href="/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, "/calendar?month=2026-05")
for _, want := range []string{
`id="calendar-filterbar"`,
`hx-target="#calendar-section"`,
`hx-get="/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", "/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 := "/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, "/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")
}
}