Files
projax/web/public_listing_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

263 lines
9.3 KiB
Go

package web_test
import (
"context"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
)
// TestPublicListingMigrationLanded asserts the five new columns are
// queryable. The migration runs as part of mustServer setup; if it
// silently failed (CREATE INDEX clash etc.) every subsequent query against
// the new columns would 500 — surface that loudly here.
func TestPublicListingMigrationLanded(t *testing.T) {
_, pool := mustServer(t)
defer pool.Close()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
var cols []string
rows, err := pool.Query(ctx, `
SELECT column_name FROM information_schema.columns
WHERE table_schema = 'projax' AND table_name = 'items'
AND column_name IN ('public','public_description','public_live_url','public_source_url','public_screenshots')
ORDER BY column_name`)
if err != nil {
t.Fatalf("information_schema query: %v", err)
}
defer rows.Close()
for rows.Next() {
var c string
if err := rows.Scan(&c); err != nil {
t.Fatalf("scan: %v", err)
}
cols = append(cols, c)
}
want := []string{"public", "public_description", "public_live_url", "public_screenshots", "public_source_url"}
if len(cols) != len(want) {
t.Fatalf("expected 5 public_* columns on projax.items, got %v", cols)
}
for i, w := range want {
if cols[i] != w {
t.Errorf("column[%d] = %q, want %q", i, cols[i], w)
}
}
}
// TestPublicListingFormRoundTrip seeds an item, POSTs the detail form with
// public=1 + the four field values + two screenshots, then asserts the
// stored row matches what was submitted.
func TestPublicListingFormRoundTrip(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 := "pub-rt-" + 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[], 'Pub RT', $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)
form := url.Values{}
form.Set("title", "Pub RT")
form.Set("slug", slug)
form.Set("status", "active")
form.Set("public", "1")
form.Set("public_description", "A test public listing.")
form.Set("public_live_url", "https://example.com/live")
form.Set("public_source_url", "https://mgit.msbls.de/m/example")
form.Add("public_screenshots", "https://example.com/a.png")
form.Add("public_screenshots", "https://example.com/b.png")
form.Add("public_screenshots", "") // empty row — parseScreenshotList must drop it
form.Set("parent_id", dev)
req := httptest.NewRequest(http.MethodPost, "/i/dev."+slug, strings.NewReader(form.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
w := httptest.NewRecorder()
h.ServeHTTP(w, req)
if w.Result().StatusCode != http.StatusSeeOther {
t.Fatalf("POST /i/dev.%s → %d", slug, w.Result().StatusCode)
}
var pub bool
var desc, live, src string
var shots []string
if err := pool.QueryRow(ctx,
`select public, public_description, public_live_url, public_source_url, public_screenshots
from projax.items where id = $1`, id,
).Scan(&pub, &desc, &live, &src, &shots); err != nil {
t.Fatalf("re-read: %v", err)
}
if !pub {
t.Errorf("public flag did not flip on")
}
if desc != "A test public listing." {
t.Errorf("description round-trip lost the value, got %q", desc)
}
if live != "https://example.com/live" {
t.Errorf("live_url round-trip broken: %q", live)
}
if src != "https://mgit.msbls.de/m/example" {
t.Errorf("source_url round-trip broken: %q", src)
}
if len(shots) != 2 || shots[0] != "https://example.com/a.png" || shots[1] != "https://example.com/b.png" {
t.Errorf("screenshots round-trip lost order/values: %v", shots)
}
}
// TestPublicListingBulkActionMakesPublic seeds an item private, POSTs the
// bulk apply with set_public=make_public, then verifies the flag flipped.
func TestPublicListingBulkActionMakesPublic(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 := "pub-bk-" + 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[], 'Pub Bulk', $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)
form := url.Values{}
form.Add("ids", id)
form.Set("set_public", "make_public")
req := httptest.NewRequest(http.MethodPost, "/admin/bulk/apply", strings.NewReader(form.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
w := httptest.NewRecorder()
h.ServeHTTP(w, req)
// Either HTMX 200 with fragment or 303 non-HTMX redirect; both fine.
if c := w.Result().StatusCode; c != http.StatusOK && c != http.StatusSeeOther {
t.Fatalf("bulk apply → %d", c)
}
var pub bool
if err := pool.QueryRow(ctx, `select public from projax.items where id=$1`, id).Scan(&pub); err != nil {
t.Fatalf("re-read: %v", err)
}
if !pub {
t.Errorf("make_public bulk action did not flip the flag")
}
// Round-trip make_private.
form2 := url.Values{}
form2.Add("ids", id)
form2.Set("set_public", "make_private")
req2 := httptest.NewRequest(http.MethodPost, "/admin/bulk/apply", strings.NewReader(form2.Encode()))
req2.Header.Set("Content-Type", "application/x-www-form-urlencoded")
w2 := httptest.NewRecorder()
h.ServeHTTP(w2, req2)
if err := pool.QueryRow(ctx, `select public from projax.items where id=$1`, id).Scan(&pub); err != nil {
t.Fatalf("re-read after make_private: %v", err)
}
if pub {
t.Errorf("make_private bulk action did not flip the flag back")
}
}
// TestPublicListingDetailFormShipsAffordances proves the detail page
// renders the public-listing fieldset with all five inputs and the
// screenshot list editor.
func TestPublicListingDetailFormShipsAffordances(t *testing.T) {
srv, pool := mustServer(t)
defer pool.Close()
h := srv.Routes()
code, body := get(t, h, "/i/dev")
if code != 200 {
t.Fatalf("GET /i/dev → %d", code)
}
for _, want := range []string{
`<fieldset class="public-listing">`,
`name="public"`,
`name="public_description"`,
`name="public_live_url"`,
`name="public_source_url"`,
`name="public_screenshots"`,
`id="public-screenshot-add"`,
} {
if !strings.Contains(body, want) {
t.Errorf("detail page missing public-listing element %q", want)
}
}
}
// TestTreeFilterPublicNarrows seeds two items, sets one to public, then
// asserts ?public=1 narrows to the public one and ?public=0 to the private.
func TestTreeFilterPublicNarrows(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)
}
var pubID, prvID string
pubSlug := "pub-filt-yes-" + stamp
prvSlug := "pub-filt-no-" + stamp
if err := pool.QueryRow(ctx,
`insert into projax.items (kind, title, slug, parent_ids, public)
values (array['project']::text[], 'Pub Yes', $1, ARRAY[$2]::uuid[], true)
returning id`, pubSlug, dev).Scan(&pubID); err != nil {
t.Fatalf("seed public: %v", err)
}
if err := pool.QueryRow(ctx,
`insert into projax.items (kind, title, slug, parent_ids, public)
values (array['project']::text[], 'Pub No', $1, ARRAY[$2]::uuid[], false)
returning id`, prvSlug, dev).Scan(&prvID); err != nil {
t.Fatalf("seed private: %v", err)
}
defer pool.Exec(context.Background(), `delete from projax.items where id in ($1, $2)`, pubID, prvID)
// Phase 5i Slice A: the project picker drops every item path into a
// <select> dropdown, so naive substring assertions trip on filtered-out
// rows visible in the picker. Anchor the row assertion on the
// tree-row link instead — that only renders for items that pass the
// filter.
pubLink := `href="/i/dev.` + pubSlug + `"`
prvLink := `href="/i/dev.` + prvSlug + `"`
_, yesBody := get(t, h, "/views/tree?public=1")
if !strings.Contains(yesBody, pubLink) {
t.Errorf("?public=1 should show pub-filt-yes row")
}
if strings.Contains(yesBody, prvLink) {
t.Errorf("?public=1 should hide pub-filt-no row")
}
_, noBody := get(t, h, "/views/tree?public=0")
if strings.Contains(noBody, pubLink) {
t.Errorf("?public=0 should hide pub-filt-yes row")
}
if !strings.Contains(noBody, prvLink) {
t.Errorf("?public=0 should show pub-filt-no row")
}
}