oficina / fichas Public

Gates over HTTP: the one-field route with and without script, the conflict page, the card beside the list across pages, History's Restore, LU5 (a GET writes nothing) and LU17 (formats), each mutation-checked

Also: stillInView syncs the index before reading the type's fields.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 343d62764d13cd24c68dcd6cd2f9807d77e9dea0 parent 594545a
3 files changed, +385 −3
  • internal/fichas/edit_handlers.go +3 −3
  • internal/fichas/formats_test.go +8 −0
  • internal/fichastest/edit_routes_test.go +374 −0
diff --git a/internal/fichas/edit_handlers.go b/internal/fichas/edit_handlers.go
index 6eff832..b0c3e5e 100644
--- a/internal/fichas/edit_handlers.go
+++ b/internal/fichas/edit_handlers.go
@@ -256,6 +256,9 @@ func (a *app) stillInView(r *http.Request, card CardView, key, list string) bool
if err != nil {
return true
}
+ if err := a.ix.Sync(r.Context()); err != nil {
+ return true
+ }
fields, err := a.ix.Fields(card.TypeKey)
if err != nil {
return true
@@ -264,9 +267,6 @@ func (a *app) stillInView(r *http.Request, card CardView, key, list string) bool
if l.Sort == key {
return false
}
- if err := a.ix.Sync(r.Context()); err != nil {
- return true
- }
return a.ix.Matches(card.TypeKey, l.query(), card.Card.ID)
}
diff --git a/internal/fichas/formats_test.go b/internal/fichas/formats_test.go
index ecad35b..8996e17 100644
--- a/internal/fichas/formats_test.go
+++ b/internal/fichas/formats_test.go
@@ -105,7 +105,15 @@ func TestTheInterimReadingIsTheLocalesOwnOnly(t *testing.T) {
}
}
+// Mutation, 2026-11-17: dropping the seed check refused the legacy value
+// and failed this test.
func TestAnUnchangedSeedIsTheStoredValue(t *testing.T) {
+ // A value stored before the grammar, not canonical, is drawn as it is
+ // stored; a German reader who leaves it alone has not changed it,
+ // though their own reading would refuse it.
+ if got, err := readNumberInput("de", "1200.50", "1200.50"); err != nil || got != "1200.50" {
+ t.Errorf("an unchanged legacy value: got %q, %v", got, err)
+ }
// 1.234 in German is "1,234", which a grouping reader could take for
// 1234: the unchanged seed is never read at all.
if got, err := readNumberInput("de", "1,234", "1.234"); err != nil || got != "1.234" {
diff --git a/internal/fichastest/edit_routes_test.go b/internal/fichastest/edit_routes_test.go
new file mode 100644
index 0000000..2e079be
--- /dev/null
+++ b/internal/fichastest/edit_routes_test.go
@@ -0,0 +1,374 @@
+package fichastest
+
+// Editing in place over HTTP (level-up §5): the one-field route with and
+// without script, the edit form's was and its conflict page, Undo, the
+// card beside the list, History, and gates LU5 and LU17.
+
+import (
+ "encoding/json"
+ "fmt"
+ "io"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "path/filepath"
+ "sort"
+ "strconv"
+ "strings"
+ "testing"
+
+ "amadan.net/rastrillo/rastrillo/db"
+
+ fichas "amadan.net/oficina/fichas/internal/fichas"
+)
+
+// editRig is the app, its database and a customer type with a Number
+// field ("Budget"), which the catalogue's Customer does not have.
+type editRig struct {
+ h http.Handler
+ d *db.DB
+ cfg fichas.Config
+ budget string // the Budget field's key
+}
+
+func newEditRig(t *testing.T) editRig {
+ t.Helper()
+ logger := slog.New(slog.NewTextHandler(io.Discard, nil))
+ d, err := db.Open(filepath.Join(t.TempDir(), "app.db"), logger)
+ if err != nil {
+ t.Fatalf("db.Open: %v", err)
+ }
+ t.Cleanup(func() { d.Close() })
+ cfg := testConfig(t)
+ h, err := fichas.AppForTest(d, cfg, logger, TestOwner)
+ if err != nil {
+ t.Fatalf("AppForTest: %v", err)
+ }
+ m, err := fichas.EnsureMember(t.Context(), d.G, cfg.Sealer, TestOwner)
+ if err != nil {
+ t.Fatal(err)
+ }
+ fd, err := fichas.AddField(t.Context(), d.G, cfg.Sealer, fichas.TypeCustomer, fichas.Person(m.ID),
+ fichas.FieldSpec{Label: "Budget", Kind: fichas.KindNumber, Tier: fichas.TierSealed})
+ if err != nil {
+ t.Fatal(err)
+ }
+ return editRig{h: h, d: d, cfg: cfg, budget: fd.Key}
+}
+
+func (r editRig) card(t *testing.T, values map[string]string) int64 {
+ t.Helper()
+ m, _ := fichas.EnsureMember(t.Context(), r.d.G, r.cfg.Sealer, TestOwner)
+ c, err := fichas.CreateCard(t.Context(), r.d.G, r.cfg.Sealer, fichas.TypeCustomer, fichas.Person(m.ID), values)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return c.ID
+}
+
+func (r editRig) value(t *testing.T, id int64, key string) string {
+ t.Helper()
+ c, err := fichas.LoadCard(t.Context(), r.d.G, r.cfg.Sealer, id)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return c.Field(key).Value
+}
+
+// postJSON is a script's post: form-encoded, JSON back (§6.8).
+func postJSON(t *testing.T, h http.Handler, target string, form url.Values) (int, map[string]any) {
+ t.Helper()
+ req := httptest.NewRequest(http.MethodPost, target, strings.NewReader(form.Encode()))
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ req.Header.Set("Accept", "application/json")
+ req.Header.Set("Origin", testOrigin)
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ var out map[string]any
+ _ = json.Unmarshal(rec.Body.Bytes(), &out)
+ return rec.Code, out
+}
+
+func getAs(t *testing.T, h http.Handler, target, lang string) *httptest.ResponseRecorder {
+ t.Helper()
+ req := httptest.NewRequest(http.MethodGet, target, nil)
+ req.Header.Set("Accept-Language", lang)
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ return rec
+}
+
+func cardPath(id int64) string { return "/cards/" + strconv.FormatInt(id, 10) }
+
+func TestAFieldSavesAtOnceWithScript(t *testing.T) {
+ r := newEditRig(t)
+ id := r.card(t, map[string]string{fichas.FieldName: "Cnoc", fichas.FieldStage: "Lead"})
+ code, out := postJSON(t, r.h, cardPath(id)+"/fields/"+fichas.FieldStage, url.Values{
+ fichas.FieldStage: {"Won"}, "was." + fichas.FieldStage: {"Lead"},
+ })
+ if code != 200 || out["message"] != "Stage changed to Won." || out["event"].(float64) == 0 || !strings.Contains(out["cell"].(string), "Won") {
+ t.Fatalf("a script's edit: %d %v", code, out)
+ }
+ if r.value(t, id, fichas.FieldStage) != "Won" {
+ t.Fatal("the edit did not land")
+ }
+ // A teammate's stale editor: 409, naming who and what, writing nothing.
+ code, out = postJSON(t, r.h, cardPath(id)+"/fields/"+fichas.FieldStage, url.Values{
+ fichas.FieldStage: {"Lost"}, "was." + fichas.FieldStage: {"Lead"},
+ })
+ if code != http.StatusConflict || out["message"] != "ana changed this to Won a moment ago." || out["theirs"] != "Won" {
+ t.Fatalf("a stale edit: %d %v", code, out)
+ }
+ // Unknown fields and cards are the app's 404.
+ if code, _ := postJSON(t, r.h, cardPath(id)+"/fields/f_nosuch", url.Values{"f_nosuch": {"x"}}); code != 404 {
+ t.Errorf("an unknown field: %d", code)
+ }
+ if code, _ := postJSON(t, r.h, "/cards/99999/fields/"+fichas.FieldStage, url.Values{fichas.FieldStage: {"Won"}}); code != 404 {
+ t.Errorf("an unknown card: %d", code)
+ }
+}
+
+func TestAFieldSavesWithoutScriptAndComesBackWithUndo(t *testing.T) {
+ r := newEditRig(t)
+ id := r.card(t, map[string]string{fichas.FieldName: "Cnoc"})
+ rec := post(t, r.h, cardPath(id)+"/fields/"+fichas.FieldEmail, url.Values{
+ fichas.FieldEmail: {"a@b.example"}, "was." + fichas.FieldEmail: {""}, "return_to": {"/t/t_customer"},
+ })
+ loc := rec.Header().Get("Location")
+ if rec.Code != http.StatusSeeOther || !strings.HasPrefix(loc, "/t/t_customer?saved=") {
+ t.Fatalf("a scriptless edit: %d %q", rec.Code, loc)
+ }
+ page := get(t, r.h, loc).Body.String()
+ event := strings.TrimPrefix(loc, "/t/t_customer?saved=")
+ if !strings.Contains(page, "Saved.") || !strings.Contains(page, `name="event" value="`+event+`"`) {
+ t.Fatal("the list does not say Saved. with an Undo form")
+ }
+ undo := post(t, r.h, cardPath(id)+"/undo", url.Values{"event": {event}, "return_to": {"/t/t_customer"}})
+ if undo.Code != http.StatusSeeOther || r.value(t, id, fichas.FieldEmail) != "" {
+ t.Fatalf("the scriptless Undo: %d, email %q", undo.Code, r.value(t, id, fichas.FieldEmail))
+ }
+ if !strings.Contains(get(t, r.h, undo.Header().Get("Location")).Body.String(), "Undone.") {
+ t.Fatal("the Undo does not come back saying so")
+ }
+ // A crafted return_to goes nowhere else.
+ away := post(t, r.h, cardPath(id)+"/fields/"+fichas.FieldEmail, url.Values{
+ fichas.FieldEmail: {"c@d.example"}, "was." + fichas.FieldEmail: {""}, "return_to": {"//evil.example/x"},
+ })
+ if loc := away.Header().Get("Location"); !strings.HasPrefix(loc, cardPath(id)+"?") {
+ t.Fatalf("return_to //evil.example went to %q", loc)
+ }
+}
+
+// LU4 for the edit form: all or nothing, with theirs and mine (§5.2).
+func TestTheEditFormsConflictPageOffersTheirsAndMine(t *testing.T) {
+ r := newEditRig(t)
+ id := r.card(t, map[string]string{fichas.FieldName: "Cnoc", fichas.FieldStage: "Lead"})
+ // Someone else moves the stage on.
+ postJSON(t, r.h, cardPath(id)+"/fields/"+fichas.FieldStage, url.Values{fichas.FieldStage: {"Won"}, "was." + fichas.FieldStage: {"Lead"}})
+ rec := post(t, r.h, cardPath(id), url.Values{
+ fichas.FieldName: {"Cnoc"}, "was." + fichas.FieldName: {"Cnoc"},
+ fichas.FieldEmail: {"a@b.example"}, "was." + fichas.FieldEmail: {""},
+ fichas.FieldStage: {"Lost"}, "was." + fichas.FieldStage: {"Lead"},
+ })
+ body := rec.Body.String()
+ if rec.Code != http.StatusConflict {
+ t.Fatalf("a conflicting form: status %d", rec.Code)
+ }
+ if r.value(t, id, fichas.FieldEmail) != "" {
+ t.Fatal("the conflicting form wrote the field that did not conflict")
+ }
+ for _, want := range []string{
+ `type="radio" name="f_stage" value="Won" checked`, `type="radio" name="f_stage" value="Lost"`,
+ `name="was.f_stage" value="Won"`, `value="a@b.example"`,
+ } {
+ if !strings.Contains(body, want) {
+ t.Errorf("the conflict page lacks %s", want)
+ }
+ }
+ // Use mine: the form posted again as it now stands.
+ again := post(t, r.h, cardPath(id), url.Values{
+ fichas.FieldName: {"Cnoc"}, "was." + fichas.FieldName: {"Cnoc"},
+ fichas.FieldEmail: {"a@b.example"}, "was." + fichas.FieldEmail: {""},
+ fichas.FieldStage: {"Lost"}, "was." + fichas.FieldStage: {"Won"},
+ })
+ if again.Code != http.StatusSeeOther || r.value(t, id, fichas.FieldStage) != "Lost" || r.value(t, id, fichas.FieldEmail) != "a@b.example" {
+ t.Fatalf("Use mine: %d", again.Code)
+ }
+}
+
+// §5.1: an edit that takes a card out of the list says so.
+func TestAnEditThatLeavesTheViewSaysSo(t *testing.T) {
+ r := newEditRig(t)
+ id := r.card(t, map[string]string{fichas.FieldName: "Cnoc", fichas.FieldStage: "Lead"})
+ _, out := postJSON(t, r.h, cardPath(id)+"/fields/"+fichas.FieldStage, url.Values{
+ fichas.FieldStage: {"Won"}, "was." + fichas.FieldStage: {"Lead"}, "list": {"f_stage=Lead"},
+ })
+ if out["outOfView"] != true {
+ t.Fatalf("leaving a Stage is Lead list: %v", out)
+ }
+ _, out = postJSON(t, r.h, cardPath(id)+"/fields/"+fichas.FieldEmail, url.Values{
+ fichas.FieldEmail: {"a@b.example"}, "was." + fichas.FieldEmail: {""}, "list": {"f_stage=Won"},
+ })
+ if out["outOfView"] != false {
+ t.Fatalf("an edit that keeps the card in the list: %v", out)
+ }
+}
+
+func TestTheCardBesideTheListWalksTheWholeList(t *testing.T) {
+ r := newEditRig(t)
+ var ids []int64
+ for i := 0; i < 102; i++ {
+ ids = append(ids, r.card(t, map[string]string{fichas.FieldName: fmt.Sprintf("Card %03d", i)}))
+ }
+ sort.Slice(ids, func(i, j int) bool { return ids[i] < ids[j] })
+ // Sorted by name, the 100th card's Next is the 101st, on page 2.
+ body := get(t, r.h, "/t/t_customer?sort=f_name&card="+strconv.FormatInt(ids[99], 10)).Body.String()
+ next := `rel="next" href="/t/t_customer?card=` + strconv.FormatInt(ids[100], 10) + `&amp;sort=f_name"`
+ if !strings.Contains(body, next) || !strings.Contains(body, "100 of 102") {
+ i := strings.Index(body, `rel="next"`)
+ t.Fatalf("the 100th card's Next is not the 101st across the page: %.200s", body[max(i, 0):])
+ }
+ page2 := get(t, r.h, "/t/t_customer?sort=f_name&card="+strconv.FormatInt(ids[100], 10)).Body.String()
+ if !strings.Contains(page2, `aria-current="true"`) || !strings.Contains(page2, "Card 100") || strings.Contains(page2, ">Card 000<") {
+ t.Fatal("the narrowed list did not move to the open card's page")
+ }
+ // A card not in the list opens, says so, and has no Next.
+ other := get(t, r.h, "/t/t_customer?q=nothing-matches&card="+strconv.FormatInt(ids[0], 10)).Body.String()
+ if !strings.Contains(other, "Not in this view") || strings.Contains(other, `rel="next"`) {
+ t.Fatal("a card outside the list does not say so")
+ }
+ if get(t, r.h, "/t/t_customer?card=999999").Code != 404 {
+ t.Fatal("an unknown card beside the list is not the app's 404")
+ }
+}
+
+func TestHistoryShowsAndRestores(t *testing.T) {
+ r := newEditRig(t)
+ id := r.card(t, map[string]string{fichas.FieldName: "Cnoc", fichas.FieldStage: "Lead"})
+ postJSON(t, r.h, cardPath(id)+"/fields/"+fichas.FieldStage, url.Values{fichas.FieldStage: {"Won"}, "was." + fichas.FieldStage: {"Lead"}})
+ body := get(t, r.h, cardPath(id)+"/history").Body.String()
+ if !strings.Contains(body, "changed Stage") || !strings.Contains(body, "Restore this value") {
+ t.Fatal("History does not show the change with Restore")
+ }
+ restore := post(t, r.h, cardPath(id)+"/fields/"+fichas.FieldStage, url.Values{
+ fichas.FieldStage: {"Lead"}, "was." + fichas.FieldStage: {"Won"}, "return_to": {cardPath(id) + "/history"},
+ })
+ if restore.Code != http.StatusSeeOther || r.value(t, id, fichas.FieldStage) != "Lead" {
+ t.Fatalf("Restore: %d", restore.Code)
+ }
+}
+
+// LU17: drawn in the reader's format, never stored in it (§6.8).
+func TestNumbersAreDrawnAndReadInTheReadersFormat(t *testing.T) {
+ r := newEditRig(t)
+ id := r.card(t, map[string]string{fichas.FieldName: "Cnoc", r.budget: "1200.5"})
+ de := getAs(t, r.h, "/t/t_customer?card="+strconv.FormatInt(id, 10), "de-DE,de;q=0.9").Body.String()
+ if !strings.Contains(de, `data-locale="de"`) || !strings.Contains(de, `value="1200,5"`) || !strings.Contains(de, `name="`+r.budget+`.locale" value="de"`) {
+ t.Fatal("a German reader's card does not seed 1200,5 with its locale")
+ }
+ list := getAs(t, r.h, "/", "de-DE").Body.String()
+ if !strings.Contains(list, `<span fichas-number>1200,5</span>`) || !strings.Contains(list, `data-seed="1200,5"`) || !strings.Contains(list, `data-was="1200.5"`) {
+ t.Fatal("a German reader's table does not draw 1200,5 over a canonical was")
+ }
+ if en := getAs(t, r.h, "/", "en").Body.String(); !strings.Contains(en, `<span fichas-number>1200.5</span>`) {
+ t.Fatal("an Irish reader's table does not draw 1200.5")
+ }
+
+ // The same change from a German page and from an English page stores
+ // the same canonical value.
+ code, out := postJSON(t, r.h, cardPath(id)+"/fields/"+r.budget, url.Values{
+ r.budget: {"1.300,25"}, "was." + r.budget: {"1200.5"}, r.budget + ".locale": {"de"},
+ })
+ if code != 200 || r.value(t, id, r.budget) != "1300.25" || out["seed"] != "1300,25" {
+ t.Fatalf("a German edit: %d %v, stored %q", code, out, r.value(t, id, r.budget))
+ }
+ code, _ = postJSON(t, r.h, cardPath(id)+"/fields/"+r.budget, url.Values{
+ r.budget: {"1,400.75"}, "was." + r.budget: {"1300.25"}, r.budget + ".locale": {"en-IE"},
+ })
+ if code != 200 || r.value(t, id, r.budget) != "1400.75" {
+ t.Fatalf("an English edit: %d, stored %q", code, r.value(t, id, r.budget))
+ }
+ // An unchanged seed is no change, in any locale.
+ code, out = postJSON(t, r.h, cardPath(id)+"/fields/"+r.budget, url.Values{
+ r.budget: {"1400,75"}, "was." + r.budget: {"1400.75"}, r.budget + ".locale": {"de"},
+ })
+ if code != 200 || out["event"].(float64) != 0 {
+ t.Fatalf("an unchanged German seed: %d %v", code, out)
+ }
+ // What is not the page's own convention is refused, and writes nothing.
+ code, out = postJSON(t, r.h, cardPath(id)+"/fields/"+r.budget, url.Values{
+ r.budget: {"1,5"}, "was." + r.budget: {"1400.75"}, r.budget + ".locale": {"en-IE"},
+ })
+ if code != 422 || out["error"] != "Enter a number, like 1200.5." || r.value(t, id, r.budget) != "1400.75" {
+ t.Fatalf("1,5 on an English page: %d %v", code, out)
+ }
+ // A page that names no locale Fichas reads in cannot say what it meant.
+ for _, bad := range []string{"", "xx-YY", "de-DE"} {
+ code, out = postJSON(t, r.h, cardPath(id)+"/fields/"+r.budget, url.Values{
+ r.budget: {"5"}, "was." + r.budget: {"1400.75"}, r.budget + ".locale": {bad},
+ })
+ if code != 422 || out["error"] != "Enter the value again." || r.value(t, id, r.budget) != "1400.75" {
+ t.Fatalf("locale echo %q: %d %v", bad, code, out)
+ }
+ }
+}
+
+// LU5: a GET writes nothing. A logical dump of every table is the same
+// before and after every page Phase 1 draws.
+//
+// Mutation, 2026-11-17: making showCard bump the card's revision (a
+// write on a GET) failed this test at /cards/{id}.
+func TestAGetWritesNothing(t *testing.T) {
+ r := newEditRig(t)
+ id := r.card(t, map[string]string{fichas.FieldName: "Cnoc", fichas.FieldStage: "Lead", r.budget: "7"})
+ _, out := postJSON(t, r.h, cardPath(id)+"/fields/"+fichas.FieldStage, url.Values{fichas.FieldStage: {"Won"}, "was." + fichas.FieldStage: {"Lead"}})
+ event := strconv.FormatInt(int64(out["event"].(float64)), 10)
+ before := dump(t, r.d)
+ for _, path := range []string{
+ "/", "/t/t_customer", "/t/t_customer?view=cards", "/t/t_customer?card=" + strconv.FormatInt(id, 10),
+ "/t/t_customer?card=" + strconv.FormatInt(id, 10) + "&saved=" + event, "/t/t_customer?q=cnoc&f_stage=Won&sort=f_name",
+ cardPath(id), cardPath(id) + "/edit", cardPath(id) + "/edit?field=f_stage", cardPath(id) + "/history",
+ cardPath(id) + "?undone=" + event, "/t/t_customer?card=999999",
+ } {
+ for _, lang := range []string{"en-IE", "de-DE"} {
+ getAs(t, r.h, path, lang)
+ }
+ if after := dump(t, r.d); after != before {
+ t.Fatalf("GET %s wrote to the database", path)
+ }
+ }
+}
+
+// dump is every row of every table, in a fixed order.
+func dump(t *testing.T, d *db.DB) string {
+ t.Helper()
+ var tables []string
+ if err := d.G.Raw("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").Scan(&tables).Error; err != nil {
+ t.Fatal(err)
+ }
+ var b strings.Builder
+ for _, table := range tables {
+ rows, err := d.G.Raw(`SELECT * FROM "` + table + `"`).Rows()
+ if err != nil {
+ t.Fatal(err)
+ }
+ cols, _ := rows.Columns()
+ var lines []string
+ for rows.Next() {
+ vals := make([]any, len(cols))
+ ptrs := make([]any, len(cols))
+ for i := range vals {
+ ptrs[i] = &vals[i]
+ }
+ if err := rows.Scan(ptrs...); err != nil {
+ t.Fatal(err)
+ }
+ lines = append(lines, fmt.Sprint(vals...))
+ }
+ rows.Close()
+ sort.Strings(lines)
+ fmt.Fprintf(&b, "%s\n%s\n", table, strings.Join(lines, "\n"))
+ }
+ return b.String()
+}