SetField, EditFields and Undo: writes that carry what the editor saw, and Undo as a new event (level-up §5.2, §5.3)
A field already holding the new value is not a change; one holding was takes it; anything else is a 409 conflict naming who changed it, and then nothing is written. One undoable updated event per edit, on a new revision. Undo reverses only a person's own undoable event inside the 90-day value window, puts back only fields that still hold the after value, leaves (and names) the rest, and logs with trigger_id; Redo names an Undo's event. Gates LU3 and LU4, each mutation-checked.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
3 files changed,
+759
−77
internal/fichas/edit.go+372 −0internal/fichas/edit_test.go+280 −0internal/fichas/store.go+107 −77
diff --git a/internal/fichas/edit.go b/internal/fichas/edit.go| new file mode 100644 |
| index 0000000..3e61865 |
| --- /dev/null |
| +++ b/internal/fichas/edit.go |
| @@ -0,0 +1,372 @@ |
| +package fichas |
| + |
| +// Editing in place (level-up spec §5.2, §5.3): writes that carry what |
| +// the editor saw, so they never cross a teammate's, and Undo as a new |
| +// event, never a rewind. |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "sort" |
| + "strings" |
| + "time" |
| + |
| + "amadan.net/oficina/fichas/internal/fichas/seal" |
| + "gorm.io/gorm" |
| +) |
| + |
| +// editPayload is a card event's sealed payload from Phase 1 on. Older |
| +// events hold a bare JSON array of changes, which reads as an edit that |
| +// is not undoable. |
| +type editPayload struct { |
| + Changes []change `json:"changes"` |
| + // Undoable marks a person's own edit, the only kind of event Undo |
| + // takes (§5.3). A redo is one too, so ⌘Z after ⌘⇧Z undoes it again. |
| + Undoable bool `json:"undoable,omitempty"` |
| + // Undo marks an Undo's own event, which only Redo takes. |
| + Undo bool `json:"undo,omitempty"` |
| + Redo bool `json:"redo,omitempty"` |
| +} |
| + |
| +func readPayload(s *seal.Sealer, e Event) (editPayload, bool) { |
| + if len(e.PayloadSealed) == 0 || e.PayloadErasedAt != nil { |
| + return editPayload{}, false |
| + } |
| + raw, err := s.Open(seal.PurposeEventPayload, e.PayloadSealed) |
| + if err != nil { |
| + return editPayload{}, false |
| + } |
| + var p editPayload |
| + if json.Unmarshal(raw, &p) == nil { |
| + return p, true |
| + } |
| + var legacy []change |
| + if json.Unmarshal(raw, &legacy) == nil { |
| + return editPayload{Changes: legacy}, true |
| + } |
| + return editPayload{}, false |
| +} |
| + |
| +// logCardEdit writes one card `updated` event with an editPayload, in |
| +// the caller's transaction. trigger names the event an Undo or Redo |
| +// answers; 0 for an edit. |
| +func logCardEdit(tx *gorm.DB, s *seal.Sealer, card Card, actor Actor, changed []int64, p editPayload, trigger int64) (int64, error) { |
| + if err := actor.valid(); err != nil { |
| + return 0, err |
| + } |
| + sort.Slice(changed, func(i, j int) bool { return changed[i] < changed[j] }) |
| + ids, err := json.Marshal(append([]int64{}, changed...)) |
| + if err != nil { |
| + return 0, fmt.Errorf("fichas: encoding changed fields: %w", err) |
| + } |
| + raw, err := json.Marshal(p) |
| + if err != nil { |
| + return 0, fmt.Errorf("fichas: encoding the change payload: %w", err) |
| + } |
| + sealed, err := s.Seal(seal.PurposeEventPayload, raw) |
| + if err != nil { |
| + return 0, fmt.Errorf("fichas: sealing the change payload: %w", err) |
| + } |
| + if trigger == 0 { |
| + trigger = actor.trigger |
| + } |
| + e := Event{ |
| + Kind: EventUpdated, ObjectKind: ObjectCard, ObjectID: card.ID, |
| + ActorID: actor.memberID, ActorReason: actor.reason, Revision: card.Revision, |
| + ChangedFields: string(ids), PayloadSealed: sealed, TriggerID: trigger, |
| + Nonce: randomPositive(), |
| + } |
| + if err := tx.Create(&e).Error; err != nil { |
| + return 0, fmt.Errorf("fichas: writing the event: %w", err) |
| + } |
| + return e.ID, nil |
| +} |
| + |
| +// Conflict is one field a write did not land on, because someone |
| +// changed it after the editor drew it. |
| +type Conflict struct { |
| + Theirs string // the value it holds now, canonical |
| + By string // who last changed it, an address, or "" when unknown |
| +} |
| + |
| +// ConflictError refuses a write whose `was` is stale (§5.2, 409). |
| +type ConflictError struct{ Fields map[string]Conflict } |
| + |
| +func (e *ConflictError) Error() string { |
| + keys := make([]string, 0, len(e.Fields)) |
| + for k := range e.Fields { |
| + keys = append(keys, k) |
| + } |
| + sort.Strings(keys) |
| + return "fichas: changed since it was drawn: " + strings.Join(keys, ", ") |
| +} |
| + |
| +// IsConflict reports a stale write. |
| +func IsConflict(err error) (*ConflictError, bool) { |
| + var c *ConflictError |
| + return c, errors.As(err, &c) |
| +} |
| + |
| +// EditResult is what an edit did. |
| +type EditResult struct { |
| + EventID int64 // 0 when nothing changed |
| + Changes []change // what changed, canonical |
| + Values map[string]string // the values the fields now hold, canonical |
| +} |
| + |
| +// SetField writes one field, given what the editor saw (§5.2). |
| +func SetField(ctx context.Context, db *gorm.DB, s *seal.Sealer, cardID int64, actor Actor, key, value, was string) (EditResult, error) { |
| + return EditFields(ctx, db, s, cardID, actor, map[string]string{key: value}, map[string]string{key: was}) |
| +} |
| + |
| +// EditFields writes several fields of one card, all or nothing, each |
| +// checked against what the editor saw, in one transaction: |
| +// 1. a field already holding its new value is not a change, so a Retry |
| +// or a second tab making the same change succeeds with no event; |
| +// 2. a field holding its `was` takes the new value; |
| +// 3. any other field is a conflict, and then nothing is written. |
| +// |
| +// The changes land as one `updated` event, marked undoable, and one new |
| +// revision. A key that is not a field of the card's type, or a card |
| +// that is gone, is gorm.ErrRecordNotFound: the caller's 404. |
| +func EditFields(ctx context.Context, db *gorm.DB, s *seal.Sealer, cardID int64, actor Actor, values, was map[string]string) (EditResult, error) { |
| + var res EditResult |
| + err := db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| + card, defs, err := liveCard(tx, cardID) |
| + if err != nil { |
| + return err |
| + } |
| + for k := range values { |
| + if _, ok := defs[k]; !ok { |
| + return gorm.ErrRecordNotFound |
| + } |
| + } |
| + values, err := checkValues(s, defs, values) |
| + if err != nil { |
| + return err |
| + } |
| + res.Values = map[string]string{} |
| + conflicts := map[string]Conflict{} |
| + var changed []int64 |
| + for _, key := range sortedKeys(values) { |
| + def, after := defs[key], values[key] |
| + before, err := currentValue(tx, s, cardID, def) |
| + if err != nil { |
| + return err |
| + } |
| + res.Values[key] = before |
| + switch { |
| + case before == after: |
| + case before == was[key]: |
| + res.Changes = append(res.Changes, change{Field: key, Before: before, After: after}) |
| + changed = append(changed, def.ID) |
| + res.Values[key] = after |
| + default: |
| + by, err := lastEditor(tx, s, cardID, def.ID) |
| + if err != nil { |
| + return err |
| + } |
| + conflicts[key] = Conflict{Theirs: before, By: by} |
| + } |
| + } |
| + if len(conflicts) > 0 { |
| + res = EditResult{} |
| + return &ConflictError{Fields: conflicts} |
| + } |
| + if len(res.Changes) == 0 { |
| + return nil |
| + } |
| + for _, c := range res.Changes { |
| + if err := writeValue(tx, s, cardID, defs[c.Field], c.After); err != nil { |
| + return err |
| + } |
| + } |
| + if err := bumpRevision(tx, &card, nil); err != nil { |
| + return err |
| + } |
| + res.EventID, err = logCardEdit(tx, s, card, actor, changed, editPayload{Changes: res.Changes, Undoable: true}, 0) |
| + return err |
| + }) |
| + if err != nil { |
| + return EditResult{}, err |
| + } |
| + return res, nil |
| +} |
| + |
| +// liveCard is a card that is not gone, with its type's fields by key. |
| +func liveCard(tx *gorm.DB, cardID int64) (Card, map[string]FieldDef, error) { |
| + var card Card |
| + if err := tx.Where("id = ? AND gone = ?", cardID, false).First(&card).Error; err != nil { |
| + return Card{}, nil, err |
| + } |
| + var ct CardType |
| + if err := tx.First(&ct, card.CardTypeID).Error; err != nil { |
| + return Card{}, nil, fmt.Errorf("fichas: loading card %d's type: %w", cardID, err) |
| + } |
| + if ct.Scope != ScopeCard { |
| + return Card{}, nil, gorm.ErrRecordNotFound |
| + } |
| + defs, err := fieldsFor(tx, card.CardTypeID) |
| + return card, defs, err |
| +} |
| + |
| +func sortedKeys(m map[string]string) []string { |
| + keys := make([]string, 0, len(m)) |
| + for k := range m { |
| + keys = append(keys, k) |
| + } |
| + sort.Strings(keys) |
| + return keys |
| +} |
| + |
| +// lastEditor is the address of whoever last wrote a field of a card, by |
| +// the event log; "" when the last write was Fichas' own or unknown. |
| +func lastEditor(tx *gorm.DB, s *seal.Sealer, cardID, fieldID int64) (string, error) { |
| + var events []Event |
| + if err := tx.Where("object_kind = ? AND object_id = ? AND kind IN ?", ObjectCard, cardID, |
| + []string{EventCreated, EventUpdated}).Order("id desc").Limit(200).Find(&events).Error; err != nil { |
| + return "", fmt.Errorf("fichas: reading card %d's history: %w", cardID, err) |
| + } |
| + for _, e := range events { |
| + if !changedField(e, fieldID) { |
| + continue |
| + } |
| + if e.ActorID == nil { |
| + return "", nil |
| + } |
| + return memberAddress(tx, s, *e.ActorID) |
| + } |
| + return "", nil |
| +} |
| + |
| +func changedField(e Event, fieldID int64) bool { |
| + var ids []int64 |
| + if json.Unmarshal([]byte(e.ChangedFields), &ids) != nil { |
| + return false |
| + } |
| + for _, id := range ids { |
| + if id == fieldID { |
| + return true |
| + } |
| + } |
| + return false |
| +} |
| + |
| +// memberAddress opens a member's sealed address. |
| +func memberAddress(tx *gorm.DB, s *seal.Sealer, id int64) (string, error) { |
| + var m Member |
| + if err := tx.First(&m, id).Error; err != nil { |
| + return "", fmt.Errorf("fichas: loading member %d: %w", id, err) |
| + } |
| + raw, err := s.Open(seal.PurposeLabel, m.SealedAddress) |
| + if err != nil { |
| + return "", fmt.Errorf("fichas: opening member %d's address: %w", id, err) |
| + } |
| + return string(raw), nil |
| +} |
| + |
| +// valueWindow is how long an event's before and after values are kept |
| +// (Q11, ruled 2026-11-17): Undo past the toast, Restore in History, and |
| +// detached files all live inside it. |
| +const valueWindow = 90 * 24 * time.Hour |
| + |
| +// UndoResult is what an Undo or Redo did. |
| +type UndoResult struct { |
| + EventID int64 // the new event; 0 when nothing could be put back |
| + Redo bool // the event named was an Undo, so this redid it |
| + Applied []change // each field put back, canonical |
| + Left []Left // each field left as it is, and why |
| +} |
| + |
| +// Left is a field an Undo did not put back. |
| +type Left struct { |
| + Field string |
| + By string // who changed it again; "" when the reason is Gone |
| + Gone bool // its old value can no longer be written |
| +} |
| + |
| +// Undo reverses one event by a new one (§5.3). The event must be an |
| +// `updated` event on this card, by this person, whose payload is still |
| +// held and marked undoable, or an Undo's own event, which Redo takes. |
| +// Anything else is gorm.ErrRecordNotFound, the app's 404. Each field |
| +// goes back only if it still holds the event's after value. |
| +func Undo(ctx context.Context, db *gorm.DB, s *seal.Sealer, cardID int64, actor Actor, eventID int64) (UndoResult, error) { |
| + var res UndoResult |
| + err := db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| + ev, p, err := undoableEvent(tx, s, cardID, actor, eventID) |
| + if err != nil { |
| + return err |
| + } |
| + res.Redo = p.Undo |
| + card, defs, err := liveCard(tx, cardID) |
| + if err != nil { |
| + return err |
| + } |
| + var changed []int64 |
| + for _, c := range p.Changes { |
| + def, ok := defs[c.Field] |
| + if !ok { |
| + res.Left = append(res.Left, Left{Field: c.Field, Gone: true}) |
| + continue |
| + } |
| + now, err := currentValue(tx, s, cardID, def) |
| + if err != nil { |
| + return err |
| + } |
| + if now != c.After { |
| + by, err := lastEditor(tx, s, cardID, def.ID) |
| + if err != nil { |
| + return err |
| + } |
| + res.Left = append(res.Left, Left{Field: c.Field, By: by}) |
| + continue |
| + } |
| + if _, err := checkValues(s, defs, map[string]string{c.Field: c.Before}); err != nil { |
| + if _, person := IsFormError(err); !person { |
| + return err |
| + } |
| + res.Left = append(res.Left, Left{Field: c.Field, Gone: true}) |
| + continue |
| + } |
| + if err := writeValue(tx, s, cardID, def, c.Before); err != nil { |
| + return err |
| + } |
| + res.Applied = append(res.Applied, change{Field: c.Field, Before: now, After: c.Before}) |
| + changed = append(changed, def.ID) |
| + } |
| + if len(res.Applied) == 0 { |
| + return nil |
| + } |
| + if err := bumpRevision(tx, &card, nil); err != nil { |
| + return err |
| + } |
| + payload := editPayload{Changes: res.Applied, Undo: !res.Redo, Redo: res.Redo, Undoable: res.Redo} |
| + res.EventID, err = logCardEdit(tx, s, card, actor, changed, payload, ev.ID) |
| + return err |
| + }) |
| + if err != nil { |
| + return UndoResult{}, err |
| + } |
| + return res, nil |
| +} |
| + |
| +// undoableEvent is the event an Undo names, if this person may undo it. |
| +func undoableEvent(tx *gorm.DB, s *seal.Sealer, cardID int64, actor Actor, eventID int64) (Event, editPayload, error) { |
| + var ev Event |
| + err := tx.Where("id = ? AND object_kind = ? AND object_id = ? AND kind = ?", |
| + eventID, ObjectCard, cardID, EventUpdated).First(&ev).Error |
| + if err != nil { |
| + return Event{}, editPayload{}, err |
| + } |
| + if actor.memberID == nil || ev.ActorID == nil || *ev.ActorID != *actor.memberID || |
| + time.Since(ev.CreatedAt) > valueWindow { |
| + return Event{}, editPayload{}, gorm.ErrRecordNotFound |
| + } |
| + p, ok := readPayload(s, ev) |
| + if !ok || !(p.Undoable || p.Undo) { |
| + return Event{}, editPayload{}, gorm.ErrRecordNotFound |
| + } |
| + return ev, p, nil |
| +} |
diff --git a/internal/fichas/edit_test.go b/internal/fichas/edit_test.go| new file mode 100644 |
| index 0000000..9db72ea |
| --- /dev/null |
| +++ b/internal/fichas/edit_test.go |
| @@ -0,0 +1,280 @@ |
| +package fichas |
| + |
| +import ( |
| + "testing" |
| + |
| + "amadan.net/oficina/fichas/internal/fichas/seal" |
| + "time" |
| + |
| + "gorm.io/gorm" |
| +) |
| + |
| +func newCustomer(t *testing.T, g *gorm.DB, s *seal.Sealer, values map[string]string) Card { |
| + t.Helper() |
| + c, err := CreateCard(ctx(), g, s, TypeCustomer, Person(1), values) |
| + if err != nil { |
| + t.Fatalf("CreateCard: %v", err) |
| + } |
| + return c |
| +} |
| + |
| +func valueOf(t *testing.T, g *gorm.DB, s *seal.Sealer, cardID int64, key string) string { |
| + t.Helper() |
| + defs, _ := fieldsFor(g, typeOfCard(t, g, cardID)) |
| + v, err := currentValue(g, s, cardID, defs[key]) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return v |
| +} |
| + |
| +func typeOfCard(t *testing.T, g *gorm.DB, id int64) int64 { |
| + var c Card |
| + if err := g.First(&c, id).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + return c.CardTypeID |
| +} |
| + |
| +func countEvents(g *gorm.DB) int64 { |
| + var n int64 |
| + g.Model(&Event{}).Count(&n) |
| + return n |
| +} |
| + |
| +// LU4: a write carries what the editor saw. |
| +// |
| +// Mutation, 2026-11-17: comparing against the stored value instead of |
| +// was (case before == was[key] → true) made the stale write land and |
| +// failed "a stale was wrote". |
| +func TestAStaleWasIsRefusedAndWritesNothing(t *testing.T) { |
| + g, s := seeded(t) |
| + ana, bo := memberID(t, g, s, "ana@example.com"), memberID(t, g, s, "bo@example.com") |
| + card := newCustomer(t, g, s, map[string]string{FieldName: "Cnoc", FieldStage: "Lead"}) |
| + |
| + if _, err := SetField(ctx(), g, s, card.ID, Person(bo), FieldStage, "Contacted", "Lead"); err != nil { |
| + t.Fatalf("Bo's edit: %v", err) |
| + } |
| + before := countEvents(g) |
| + _, err := SetField(ctx(), g, s, card.ID, Person(ana), FieldStage, "Won", "Lead") |
| + c, ok := IsConflict(err) |
| + if !ok { |
| + t.Fatalf("a stale was wrote: %v", err) |
| + } |
| + if got := c.Fields[FieldStage]; got.Theirs != "Contacted" || got.By != "bo@example.com" { |
| + t.Fatalf("the conflict says %+v", got) |
| + } |
| + if valueOf(t, g, s, card.ID, FieldStage) != "Contacted" || countEvents(g) != before { |
| + t.Fatal("a refused write changed something") |
| + } |
| + // Use mine: the same write with the current value as was. |
| + if _, err := SetField(ctx(), g, s, card.ID, Person(ana), FieldStage, "Won", "Contacted"); err != nil { |
| + t.Fatalf("Use mine: %v", err) |
| + } |
| + if valueOf(t, g, s, card.ID, FieldStage) != "Won" { |
| + t.Fatal("Use mine did not land") |
| + } |
| +} |
| + |
| +// Mutation, 2026-11-17: dropping the before == after case made the |
| +// repeat a conflict and failed this test. |
| +func TestARepeatedWriteSucceedsWithNoEvent(t *testing.T) { |
| + g, s := seeded(t) |
| + card := newCustomer(t, g, s, map[string]string{FieldName: "Cnoc"}) |
| + if _, err := SetField(ctx(), g, s, card.ID, Person(1), FieldEmail, "a@b.example", ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + before := countEvents(g) |
| + res, err := SetField(ctx(), g, s, card.ID, Person(1), FieldEmail, "a@B.example", "") |
| + if err != nil || res.EventID != 0 || countEvents(g) != before { |
| + t.Fatalf("a retried write: %+v, %v, %d new events", res, err, countEvents(g)-before) |
| + } |
| +} |
| + |
| +func TestTwoPeopleEditingTwoFieldsBothLand(t *testing.T) { |
| + g, s := seeded(t) |
| + card := newCustomer(t, g, s, map[string]string{FieldName: "Cnoc"}) |
| + if _, err := SetField(ctx(), g, s, card.ID, Person(1), FieldStage, "Lead", ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := SetField(ctx(), g, s, card.ID, Person(2), FieldEmail, "a@b.example", ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + if valueOf(t, g, s, card.ID, FieldStage) != "Lead" || valueOf(t, g, s, card.ID, FieldEmail) != "a@b.example" { |
| + t.Fatal("one of two edits to different fields was lost") |
| + } |
| +} |
| + |
| +// Mutation, 2026-11-17: skipping the conflicts check (writing what did |
| +// not conflict) failed "a conflicting edit form wrote". |
| +func TestTheEditFormIsAllOrNothing(t *testing.T) { |
| + g, s := seeded(t) |
| + card := newCustomer(t, g, s, map[string]string{FieldName: "Cnoc", FieldStage: "Lead"}) |
| + SetField(ctx(), g, s, card.ID, Person(memberID(t, g, s, "bo@example.com")), FieldStage, "Won", "Lead") |
| + _, err := EditFields(ctx(), g, s, card.ID, Person(1), |
| + map[string]string{FieldEmail: "a@b.example", FieldStage: "Lost"}, |
| + map[string]string{FieldEmail: "", FieldStage: "Lead"}) |
| + if _, ok := IsConflict(err); !ok { |
| + t.Fatalf("want a conflict, got %v", err) |
| + } |
| + if valueOf(t, g, s, card.ID, FieldEmail) != "" { |
| + t.Fatal("a conflicting edit form wrote its other field") |
| + } |
| +} |
| + |
| +func TestAnEditIsOneUndoableEventOnANewRevision(t *testing.T) { |
| + g, s := seeded(t) |
| + card := newCustomer(t, g, s, map[string]string{FieldName: "Cnoc"}) |
| + res, err := EditFields(ctx(), g, s, card.ID, Person(1), |
| + map[string]string{FieldEmail: "a@b.example", FieldStage: "Lead"}, map[string]string{}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var ev Event |
| + g.First(&ev, res.EventID) |
| + var after Card |
| + g.First(&after, card.ID) |
| + p, ok := readPayload(s, ev) |
| + if !ok || !p.Undoable || len(p.Changes) != 2 || ev.Revision != after.Revision || after.Revision == card.Revision { |
| + t.Fatalf("the edit's event: %+v %+v; revision %d → %d", ev, p, card.Revision, after.Revision) |
| + } |
| +} |
| + |
| +// LU3: an edit whose event cannot be written does not land. |
| +func TestAnEditThatCannotBeLoggedDoesNotLand(t *testing.T) { |
| + g, s := seeded(t) |
| + card := newCustomer(t, g, s, map[string]string{FieldName: "Cnoc", FieldStage: "Lead"}) |
| + res, _ := SetField(ctx(), g, s, card.ID, Person(1), FieldStage, "Won", "Lead") |
| + failEvents(t, g) |
| + if _, err := SetField(ctx(), g, s, card.ID, Person(1), FieldStage, "Lost", "Won"); err == nil { |
| + t.Fatal("an edit landed with no event") |
| + } |
| + if _, err := Undo(ctx(), g, s, card.ID, Person(1), res.EventID); err == nil { |
| + t.Fatal("an undo landed with no event") |
| + } |
| + if valueOf(t, g, s, card.ID, FieldStage) != "Won" { |
| + t.Fatal("a write whose event failed changed the value") |
| + } |
| +} |
| + |
| +func failEvents(t *testing.T, g *gorm.DB) { |
| + t.Helper() |
| + if err := g.Exec("CREATE TRIGGER no_events BEFORE INSERT ON events BEGIN SELECT RAISE(ABORT, 'no'); END").Error; err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// LU4, Undo. Mutation, 2026-11-17: dropping the now != c.After check |
| +// put Niamh's later value back to Lead and failed "Undo overwrote". |
| +func TestUndoPutsBackOnlyWhatStillHoldsItsAfterValue(t *testing.T) { |
| + g, s := seeded(t) |
| + ana, niamh := memberID(t, g, s, "ana@example.com"), memberID(t, g, s, "niamh@example.com") |
| + card := newCustomer(t, g, s, map[string]string{FieldName: "Cnoc", FieldStage: "Lead"}) |
| + res, _ := EditFields(ctx(), g, s, card.ID, Person(ana), |
| + map[string]string{FieldStage: "Won", FieldEmail: "a@b.example"}, |
| + map[string]string{FieldStage: "Lead", FieldEmail: ""}) |
| + SetField(ctx(), g, s, card.ID, Person(niamh), FieldStage, "Lost", "Won") |
| + |
| + u, err := Undo(ctx(), g, s, card.ID, Person(ana), res.EventID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if valueOf(t, g, s, card.ID, FieldStage) != "Lost" { |
| + t.Fatal("Undo overwrote a later change") |
| + } |
| + if valueOf(t, g, s, card.ID, FieldEmail) != "" || len(u.Applied) != 1 { |
| + t.Fatalf("Undo did not put back the field it could: %+v", u) |
| + } |
| + if len(u.Left) != 1 || u.Left[0].Field != FieldStage || u.Left[0].By != "niamh@example.com" { |
| + t.Fatalf("Undo did not name what it left: %+v", u.Left) |
| + } |
| + var ev Event |
| + g.First(&ev, u.EventID) |
| + if ev.TriggerID != res.EventID || ev.ActorID == nil || *ev.ActorID != ana { |
| + t.Fatalf("the Undo's event: %+v", ev) |
| + } |
| + // Redo names the Undo's event. |
| + r, err := Undo(ctx(), g, s, card.ID, Person(ana), u.EventID) |
| + if err != nil || !r.Redo || valueOf(t, g, s, card.ID, FieldEmail) != "a@b.example" { |
| + t.Fatalf("Redo: %+v, %v", r, err) |
| + } |
| + // And ⌘Z after ⌘⇧Z undoes the redo. |
| + if again, err := Undo(ctx(), g, s, card.ID, Person(ana), r.EventID); err != nil || again.Redo || valueOf(t, g, s, card.ID, FieldEmail) != "" { |
| + t.Fatalf("undoing a redo: %+v, %v", again, err) |
| + } |
| +} |
| + |
| +// Mutations, 2026-11-17: removing the actor check (Bo undid Ana's edit), |
| +// the undoable check (a legacy edit was undone) or the window check each |
| +// failed this test. |
| +func TestUndoRefusesWhatItMayNotReverse(t *testing.T) { |
| + g, s := seeded(t) |
| + ana, bo := memberID(t, g, s, "ana@example.com"), memberID(t, g, s, "bo@example.com") |
| + card := newCustomer(t, g, s, map[string]string{FieldName: "Cnoc", FieldStage: "Lead"}) |
| + edit, _ := SetField(ctx(), g, s, card.ID, Person(ana), FieldStage, "Won", "Lead") |
| + var created, entryEv Event |
| + g.Where("object_id = ? AND kind = ?", card.ID, EventCreated).First(&created) |
| + AddEntry(ctx(), g, s, card.ID, Person(ana), TypeCallLog, "manual", map[string]string{FieldBody: "hello"}) |
| + g.Where("kind = ?", EventEntryAdded).First(&entryEv) |
| + other := newCustomer(t, g, s, map[string]string{FieldName: "Other"}) |
| + reconcile := Event{Kind: EventUpdated, ObjectKind: ObjectCard, ObjectID: card.ID, ActorReason: "number grammar", ChangedFields: "[]", Nonce: 1} |
| + g.Create(&reconcile) |
| + old, _ := SetField(ctx(), g, s, card.ID, Person(ana), FieldEmail, "a@b.example", "") |
| + g.Model(&Event{}).Where("id = ?", old.EventID).Update("created_at", time.Now().Add(-valueWindow-time.Hour)) |
| + UpdateCard(ctx(), g, s, card.ID, Person(ana), map[string]string{FieldNotes: "legacy"}) |
| + var legacy Event |
| + g.Where("object_id = ? AND kind = ?", card.ID, EventUpdated).Order("id desc").First(&legacy) |
| + erased, _ := SetField(ctx(), g, s, card.ID, Person(ana), FieldPhone, "+353 1 555 0100", "") |
| + now := time.Now() |
| + g.Model(&Event{}).Where("id = ?", erased.EventID).Updates(map[string]any{"payload_sealed": nil, "payload_erased_at": &now}) |
| + |
| + for name, c := range map[string]struct { |
| + card, event int64 |
| + who int64 |
| + }{ |
| + "a created event": {card.ID, created.ID, ana}, |
| + "another person's": {card.ID, edit.EventID, bo}, |
| + "an entry": {card.ID, entryEv.ID, ana}, |
| + "a reconcile's change": {card.ID, reconcile.ID, ana}, |
| + "another card's": {other.ID, edit.EventID, ana}, |
| + "one past the window": {card.ID, old.EventID, ana}, |
| + "one whose payload erased": {card.ID, erased.EventID, ana}, |
| + "one that never existed": {card.ID, 999999, ana}, |
| + "one not marked undoable": {card.ID, legacy.ID, ana}, |
| + } { |
| + if _, err := Undo(ctx(), g, s, c.card, Person(c.who), c.event); err != gorm.ErrRecordNotFound { |
| + t.Errorf("%s: Undo answered %v; want not found", name, err) |
| + } |
| + } |
| +} |
| + |
| +func TestUndoLeavesAnOptionTheFieldNoLongerHas(t *testing.T) { |
| + g, s := seeded(t) |
| + card := newCustomer(t, g, s, map[string]string{FieldName: "Cnoc", FieldStage: "Lead"}) |
| + res, _ := SetField(ctx(), g, s, card.ID, Person(1), FieldStage, "Won", "Lead") |
| + var fd FieldDef |
| + g.Where("key = ?", FieldStage).First(&fd) |
| + opts, _ := openOptions(s, fd.SealedOptions) |
| + var kept []string |
| + for _, o := range opts { |
| + if o != "Lead" { |
| + kept = append(kept, o) |
| + } |
| + } |
| + if err := UpdateField(ctx(), g, s, FieldStage, Person(1), "Stage", kept); err != nil { |
| + t.Fatal(err) |
| + } |
| + u, err := Undo(ctx(), g, s, card.ID, Person(1), res.EventID) |
| + if err != nil || len(u.Left) != 1 || !u.Left[0].Gone || valueOf(t, g, s, card.ID, FieldStage) != "Won" { |
| + t.Fatalf("an unknown option: %+v, %v", u, err) |
| + } |
| +} |
| + |
| +func memberID(t *testing.T, g *gorm.DB, s *seal.Sealer, address string) int64 { |
| + t.Helper() |
| + m, err := memberByAddress(ctx(), g, s, address) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return m.ID |
| +} |
diff --git a/internal/fichas/store.go b/internal/fichas/store.go| index 889970a..d47f39e 100644 |
| --- a/internal/fichas/store.go |
| +++ b/internal/fichas/store.go |
| @@ -171,109 +171,139 @@ func logEvent(tx *gorm.DB, s *seal.Sealer, kind, objectKind string, objectID, ch |
| // define is an error rather than something quietly dropped — a silently |
| // ignored field is a value a person believes they saved. |
| func writeValues(tx *gorm.DB, s *seal.Sealer, cardID int64, defs map[string]FieldDef, values map[string]string) ([]int64, []change, error) { |
| - for key := range values { |
| - if _, ok := defs[key]; !ok { |
| - return nil, nil, fmt.Errorf("fichas: %s is not a field of this card type", key) |
| + values, err := checkValues(s, defs, values) |
| + if err != nil { |
| + return nil, nil, err |
| + } |
| + keys := make([]string, 0, len(values)) |
| + for k := range values { |
| + keys = append(keys, k) |
| + } |
| + sort.Strings(keys) |
| + |
| + var changed []int64 |
| + var detail []change |
| + for _, key := range keys { |
| + def := defs[key] |
| + after := values[key] |
| + before, err := currentValue(tx, s, cardID, def) |
| + if err != nil { |
| + return nil, nil, err |
| + } |
| + if before == after { |
| + continue // not a change; it must not appear in the log as one |
| } |
| + if err := writeValue(tx, s, cardID, def, after); err != nil { |
| + return nil, nil, err |
| + } |
| + changed = append(changed, def.ID) |
| + detail = append(detail, change{Field: key, Before: before, After: after}) |
| } |
| - // Numbers are stored bare: "1,200" is accepted from a person and kept |
| - // as "1200", or it would sort as text and never compare as a number. |
| + return changed, detail, nil |
| +} |
| + |
| +// normaliseValue is the stored form of what a person typed, by kind. |
| +// Numbers are stored bare: "1,200" is accepted from a person and kept |
| +// as "1200", or it would sort as text and never compare as a number. |
| +// (A form reads numbers in the reader's locale first, §6.8; this keeps |
| +// the store's own callers, which pass canonical text, as they were.) |
| +func normaliseValue(def FieldDef, v string) string { |
| + switch def.Kind { |
| + case KindNumber: |
| + v = strings.ReplaceAll(strings.TrimSpace(v), ",", "") |
| + case KindEmail: |
| + // The domain is case-blind; the local part is the server's |
| + // business, so it is left as typed. |
| + if local, domain, ok := strings.Cut(strings.TrimSpace(v), "@"); ok { |
| + v = local + "@" + strings.ToLower(domain) |
| + } |
| + case KindPhone: |
| + v = strings.Join(strings.Fields(v), " ") |
| + case KindURL: |
| + // A value that will not normalise is left as typed so that |
| + // validateValues can say what is wrong with it. |
| + if n, err := normaliseURL(v); err == nil { |
| + v = n |
| + } |
| + } |
| + return v |
| +} |
| + |
| +// checkValues normalises values and refuses, with a FormError, any a |
| +// person must fix: a bad value for its kind, an empty title, a choice |
| +// that is not an option. A key that is not a field is a programming |
| +// error, not a person's. |
| +func checkValues(s *seal.Sealer, defs map[string]FieldDef, values map[string]string) (map[string]string, error) { |
| normalised := make(map[string]string, len(values)) |
| for k, v := range values { |
| - switch defs[k].Kind { |
| - case KindNumber: |
| - v = strings.ReplaceAll(strings.TrimSpace(v), ",", "") |
| - case KindEmail: |
| - // The domain is case-blind; the local part is the server's |
| - // business, so it is left as typed. |
| - if local, domain, ok := strings.Cut(strings.TrimSpace(v), "@"); ok { |
| - v = local + "@" + strings.ToLower(domain) |
| - } |
| - case KindPhone: |
| - v = strings.Join(strings.Fields(v), " ") |
| - case KindURL: |
| - // A value that will not normalise is left as typed so that |
| - // validateValues can say what is wrong with it. |
| - if n, err := normaliseURL(v); err == nil { |
| - v = n |
| - } |
| + def, ok := defs[k] |
| + if !ok { |
| + return nil, fmt.Errorf("fichas: %s is not a field of this card type", k) |
| } |
| - normalised[k] = v |
| + normalised[k] = normaliseValue(def, v) |
| } |
| - values = normalised |
| - fe := validateValues(defs, values) |
| + fe := validateValues(defs, normalised) |
| // Every card has a name (UX review, 2026-11-12: an empty "Add a |
| // customer" made a card called "Card 305"). The browser's required |
| // attribute is a convenience; this is the rule. A write that does not |
| // touch the title (a partial update) is not asked for it. |
| if title := titleOf(defs); title != "" { |
| - if v, ok := values[title]; ok && strings.TrimSpace(v) == "" { |
| + if v, ok := normalised[title]; ok && strings.TrimSpace(v) == "" { |
| if fe == nil { |
| fe = FormError{} |
| } |
| fe[title] = "Give it a name." |
| } |
| } |
| - fe, err := optionsError(s, defs, values, fe) |
| + fe, err := optionsError(s, defs, normalised, fe) |
| if err != nil { |
| - return nil, nil, err |
| + return nil, err |
| } |
| if fe != nil { |
| - return nil, nil, fe |
| + return nil, fe |
| } |
| + return normalised, nil |
| +} |
| - keys := make([]string, 0, len(values)) |
| - for k := range values { |
| - keys = append(keys, k) |
| +// currentValue is a card's stored value for one field, opened. |
| +func currentValue(tx *gorm.DB, s *seal.Sealer, cardID int64, def FieldDef) (string, error) { |
| + var existing CardValue |
| + err := tx.Where("card_id = ? AND field_def_id = ?", cardID, def.ID).First(&existing).Error |
| + if err == gorm.ErrRecordNotFound { |
| + return "", nil |
| } |
| - sort.Strings(keys) |
| - |
| - var changed []int64 |
| - var detail []change |
| - |
| - for _, key := range keys { |
| - def, ok := defs[key] |
| - if !ok { |
| - return nil, nil, fmt.Errorf("fichas: %s is not a field of this card type", key) |
| - } |
| - after := values[key] |
| - |
| - var existing CardValue |
| - err := tx.Where("card_id = ? AND field_def_id = ?", cardID, def.ID).First(&existing).Error |
| - if err != nil && err != gorm.ErrRecordNotFound { |
| - return nil, nil, fmt.Errorf("fichas: reading %s: %w", key, err) |
| - } |
| - var before string |
| - if err == nil && len(existing.SealedValue) > 0 { |
| - raw, oerr := s.Open(seal.PurposeValue, existing.SealedValue) |
| - if oerr != nil { |
| - return nil, nil, fmt.Errorf("fichas: opening the previous %s: %w", key, oerr) |
| - } |
| - before = string(raw) |
| - } |
| - if before == after { |
| - continue // not a change; it must not appear in the log as one |
| - } |
| + if err != nil { |
| + return "", fmt.Errorf("fichas: reading %s: %w", def.Key, err) |
| + } |
| + if len(existing.SealedValue) == 0 { |
| + return "", nil |
| + } |
| + raw, err := s.Open(seal.PurposeValue, existing.SealedValue) |
| + if err != nil { |
| + return "", fmt.Errorf("fichas: opening the previous %s: %w", def.Key, err) |
| + } |
| + return string(raw), nil |
| +} |
| - sealed, serr := s.Seal(seal.PurposeValue, []byte(after)) |
| - if serr != nil { |
| - return nil, nil, fmt.Errorf("fichas: sealing %s: %w", key, serr) |
| - } |
| - row := CardValue{CardID: cardID, FieldDefID: def.ID, SealedValue: sealed} |
| - if def.Tier == TierPrint { |
| - p, perr := printFor(s, def, after) |
| - if perr != nil { |
| - return nil, nil, perr |
| - } |
| - row.Print = p |
| - } |
| - if err := tx.Save(&row).Error; err != nil { |
| - return nil, nil, fmt.Errorf("fichas: writing %s: %w", key, err) |
| +// writeValue seals and stores one value, with its print when the field |
| +// is printed. |
| +func writeValue(tx *gorm.DB, s *seal.Sealer, cardID int64, def FieldDef, after string) error { |
| + sealed, err := s.Seal(seal.PurposeValue, []byte(after)) |
| + if err != nil { |
| + return fmt.Errorf("fichas: sealing %s: %w", def.Key, err) |
| + } |
| + row := CardValue{CardID: cardID, FieldDefID: def.ID, SealedValue: sealed} |
| + if def.Tier == TierPrint { |
| + p, perr := printFor(s, def, after) |
| + if perr != nil { |
| + return perr |
| } |
| - changed = append(changed, def.ID) |
| - detail = append(detail, change{Field: key, Before: before, After: after}) |
| + row.Print = p |
| } |
| - return changed, detail, nil |
| + if err := tx.Save(&row).Error; err != nil { |
| + return fmt.Errorf("fichas: writing %s: %w", def.Key, err) |
| + } |
| + return nil |
| } |
| // randomBytes is where randomPositive draws from: crypto/rand. A variable |