Files
projax/web/public_listing_test.go
mAi f6cf050c3f feat(phase 4d): public-listing fields so projax becomes the portfolio source of truth
Adds five additive columns on projax.items and propagates them through
every read/write path. flexsiebels.de (and any future portfolio renderer)
can now pull the public set via the MCP `list_items(public=true)` filter
and stop hard-coding project lists.

## Schema (migration 0014)
- public               boolean       default false (partial index when true)
- public_description   text          default ''
- public_live_url      text          default ''
- public_source_url    text          default ''
- public_screenshots   text[]        default '{}'
- items_unified view rebuilt to include the five new columns
- items_public_idx     PARTIAL INDEX WHERE public = true (5% of rows)

## Store
- Item struct + scan/scanItems extended (5 cols)
- UpdateInput accepts the new fields with full-replace semantics
- new SetPublic(ids, bool) for bulk write
- SearchFilters gains Public *bool — nil = no filter

## MCP
- list_items: new `public` boolean filter (input schema + handler)
- update_item: 5 new partial-update fields (nil pointer = leave alone)
- itemView always emits the 5 fields (even when public=false) so consumers
  can preview "what would publish" without a second round-trip
- 2 new integration tests against the DB

## Web
- /i/{path} grows a "Public listing" fieldset: toggle + textarea + 2 URL
  inputs + screenshot list editor with add/remove rows + inline JS for
  the editor. Values persist when public is off so toggling never
  destroys typed-in content.
- /admin/bulk action bar gains "Make public" / "Make private" via a new
  select; SQL update is a single statement per action.
- /?public=1 and /?public=0 chip parameters narrow the tree page.
  Active() + QueryString() + TogglePublic() round-trip the state.
- parseScreenshotList helper trims + drops empties + preserves order
- 5 integration tests: migration landed, form round-trip, bulk action
  round-trip, detail-page affordances, tree-filter narrowing

## docs/design.md §15
Documents the schema, MCP contract, UI surfaces, flexsiebels consumption
pattern, and what's NOT in scope (flexsiebels-side render, asset hosting,
approval workflows).

## Out of scope (per task brief)
- Flexsiebels rendering — separate task in m/flexsiebels.de after this ships
- Asset hosting (projax stores URLs, never bytes — same PER discipline)
- Multi-stage publish workflow (boolean is enough)
2026-05-17 19:11:26 +02:00

256 lines
8.9 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)
_, yesBody := get(t, h, "/?public=1")
if !strings.Contains(yesBody, pubSlug) {
t.Errorf("?public=1 should show pub-filt-yes")
}
if strings.Contains(yesBody, prvSlug) {
t.Errorf("?public=1 should hide pub-filt-no")
}
_, noBody := get(t, h, "/?public=0")
if strings.Contains(noBody, pubSlug) {
t.Errorf("?public=0 should hide pub-filt-yes")
}
if !strings.Contains(noBody, prvSlug) {
t.Errorf("?public=0 should show pub-filt-no")
}
}