package fichastest
import (
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"amadan.net/oficina/fichas/internal/fichas"
)
// withCookies GETs target carrying the cookies a response set.
func withCookies(t *testing.T, h http.Handler, target string, from *httptest.ResponseRecorder) string {
t.Helper()
req := httptest.NewRequest(http.MethodGet, target, nil)
for _, c := range from.Result().Cookies() {
if c.MaxAge >= 0 {
req.AddCookie(c)
}
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("GET %s: status %d", target, rec.Code)
}
return rec.Body.String()
}
// Comfortable is the default; Compact is a choice that sticks, and the
// change lands back on the list it was made on, its search kept.
func TestDensityIsTheReadersChoice(t *testing.T) {
h := newApp(t)
createACustomer(t, h, "Cnoc Teoranta")
if body := get(t, h, "/").Body.String(); !strings.Contains(body, `data-density="comfortable"`) {
t.Fatal("the table is not comfortable by default")
}
back := "/t/" + fichas.TypeCustomer + "?q=cnoc"
rec := post(t, h, "/t/"+fichas.TypeCustomer+"/view", url.Values{"density": {"compact"}, "return_to": {back}})
if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != back {
t.Fatalf("POST view: %d to %q, want 303 to %q", rec.Code, rec.Header().Get("Location"), back)
}
body := withCookies(t, h, back, rec)
if !strings.Contains(body, `data-density="compact"`) {
t.Fatal("Compact did not stick")
}
if !strings.Contains(body, `value="compact" aria-pressed="true"`) {
t.Fatal("the View menu does not show Compact as chosen")
}
}
// Hiding a column drops its header and its cells; the title column cannot
// be hidden, because every row is named by it and opens its card from it.
func TestColumnsAreTheReadersChoice(t *testing.T) {
h := newApp(t)
createACustomer(t, h, "Cnoc Teoranta") // email ana@example.com
base := "/t/" + fichas.TypeCustomer
// Show only Stage: Name, Email, Domain and the rest unticked.
rec := post(t, h, base+"/view", url.Values{"columns": {"1"}, "show": {fichas.FieldStage}, "return_to": {base}})
if rec.Code != http.StatusSeeOther {
t.Fatalf("POST view: %d", rec.Code)
}
body := withCookies(t, h, base, rec)
grid := body[strings.Index(body, "
")]
if strings.Contains(grid, "ana@example.com") || strings.Contains(grid, ">Email<") {
t.Errorf("a hidden column is still drawn:\n%s", grid)
}
if !strings.Contains(grid, "Cnoc Teoranta") || !strings.Contains(grid, ">Name<") {
t.Errorf("the title column was hidden:\n%s", grid)
}
if !strings.Contains(grid, ">Stage<") || !strings.Contains(grid, "Lead") {
t.Errorf("a column left ticked is gone:\n%s", grid)
}
if strings.Contains(grid, "Last call") {
t.Error("Last call was unticked but still shows")
}
// The checklist says what is shown, and the title is locked on.
if !strings.Contains(body, `value="`+fichas.FieldName+`" checked disabled`) {
t.Error("the title column is not locked on in the checklist")
}
if strings.Contains(body, `value="`+fichas.FieldEmail+`" checked`) {
t.Error("the checklist shows Email as shown")
}
// Ticking everything again forgets the choice.
all := url.Values{"columns": {"1"}, "return_to": {base}}
for _, k := range []string{fichas.FieldDomain, fichas.FieldEmail, fichas.FieldPhone, fichas.FieldStage, fichas.FieldNextAction, fichas.SortLastCall} {
all.Add("show", k)
}
rec = post(t, h, base+"/view", all)
var cleared bool
for _, c := range rec.Result().Cookies() {
if strings.HasPrefix(c.Name, "fichas-hide-") && c.MaxAge < 0 {
cleared = true
}
}
if !cleared {
t.Error("showing every column did not clear the cookie")
}
}
// A view change goes back only to a list: never another path, never
// another origin.
func TestAViewChangeOnlyReturnsToAList(t *testing.T) {
h := newApp(t)
base := "/t/" + fichas.TypeCustomer
for _, to := range []string{"//evil.example/", "https://evil.example/", "/cards/1/delete", "/\\evil.example", "/t/other",
// The list's own path, carrying a control character or a backslash.
base + "?x=\t//evil.example", base + "?x=\\evil.example"} {
rec := post(t, h, base+"/view", url.Values{"density": {"compact"}, "return_to": {to}})
if loc := rec.Header().Get("Location"); loc != base {
t.Errorf("return_to %q went to %q, want %q", to, loc, base)
}
}
}
// The name opens the card beside the list (level-up §5.4, D1); the
// stretched row link of 2026-11-12 is gone, because every other cell
// edits its own field.
func TestTheNameOpensTheCardBesideTheList(t *testing.T) {
h := newApp(t)
path := createACustomer(t, h, "Cnoc Teoranta")
id := strings.TrimPrefix(path, "/cards/")
body := get(t, h, "/").Body.String()
if !strings.Contains(body, `Cnoc Teoranta`) {
t.Fatal("the name is not a link to the card beside the list")
}
if strings.Contains(body, "fichas-row-link") {
t.Fatal("the stretched row link is still there")
}
}
// A sort by a hidden column is dropped: rows are never ordered by
// something the reader cannot see, and no link on the page carries it on.
func TestAHiddenColumnDoesNotSort(t *testing.T) {
h := newApp(t)
createACustomer(t, h, "Cnoc Teoranta")
base := "/t/" + fichas.TypeCustomer
sorted := base + "?sort=" + fichas.FieldEmail
if body := get(t, h, sorted).Body.String(); !strings.Contains(body, "sort="+fichas.FieldEmail) {
t.Fatal("precondition: a shown column's sort is carried by the page's links")
}
rec := post(t, h, base+"/view", url.Values{"columns": {"1"}, "show": {fichas.FieldStage}, "return_to": {base}})
// The list's own links (the page content; the account menu's Appearance
// return is the raw URL, and a return there drops the sort again).
body := withCookies(t, h, sorted, rec)
page := body[strings.Index(body, `id="main"`):]
if i := strings.Index(page, "sort="+fichas.FieldEmail); i >= 0 {
t.Errorf("the page still sorts by the hidden Email column: …%s…", page[max(0, i-200):i+40])
}
}
// Served over HTTPS, the preference cookies are Secure, as every other
// cookie the app and estilo set is; always HttpOnly and SameSite=Lax.
func TestPreferenceCookiesAreSecureOverHTTPS(t *testing.T) {
const origin = "https://fichas.example"
h := appWith(t, func(c *fichas.Config) { c.Origin = origin })
base := "/t/" + fichas.TypeCustomer
for _, form := range []url.Values{
{"density": {"compact"}},
{"columns": {"1"}, "show": {fichas.FieldStage}},
{"columns": {"1"}, "show": {fichas.FieldDomain, fichas.FieldEmail, fichas.FieldPhone, fichas.FieldStage, fichas.FieldNextAction, fichas.SortLastCall}},
} {
req := httptest.NewRequest(http.MethodPost, origin+base+"/view", strings.NewReader(form.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Origin", origin)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
cookies := rec.Result().Cookies()
if rec.Code != http.StatusSeeOther || len(cookies) == 0 {
t.Fatalf("POST %v: %d, %d cookies", form, rec.Code, len(cookies))
}
for _, c := range cookies {
if !c.Secure || !c.HttpOnly || c.SameSite != http.SameSiteLaxMode {
t.Errorf("%s is not Secure, HttpOnly and SameSite=Lax over HTTPS: %s", c.Name, c.String())
}
}
}
}