oficina / fichas Public

The 90-day value window: a sweep that erases payloads past it, and CardHistory (level-up §5.5, Q11)

The sweep logs nothing (a named exemption), runs off the boot path once
and then hourly from main, and never stops the app. History lists each
change newest first with who, when and which fields, and before and
after only inside the window.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 880c5cc45c0befc668b6c0dec3985e3fd501d4d6 parent 6e531e1
4 files changed, +239 −3
  • cmd/fichas/main.go +4 −0
  • internal/fichas/edit.go +3 −3
  • internal/fichas/history.go +168 −0
  • internal/fichas/history_test.go +64 −0
diff --git a/cmd/fichas/main.go b/cmd/fichas/main.go
index 750a9ec..832ff0d 100644
--- a/cmd/fichas/main.go
+++ b/cmd/fichas/main.go
@@ -3,6 +3,7 @@
package main
import (
+ "context"
"log/slog"
"os"
@@ -55,6 +56,9 @@ func main() {
logger.Error("build app", "err", err)
os.Exit(1)
}
+ // The value window's sweep (level-up Q11), off the boot path: it
+ // runs once now and hourly, and never stops the app.
+ go fichas.Sweep(context.Background(), d.G, logger)
// Wire the mailer BEFORE auth. Without a real sender rastrillo
// substitutes mail.Logged, which writes the magic link — a live
diff --git a/internal/fichas/edit.go b/internal/fichas/edit.go
index 3e61865..cee49c5 100644
--- a/internal/fichas/edit.go
+++ b/internal/fichas/edit.go
@@ -274,10 +274,10 @@ 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
+ 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 []Left // each field left as it is, and why
}
// Left is a field an Undo did not put back.
diff --git a/internal/fichas/history.go b/internal/fichas/history.go
new file mode 100644
index 0000000..d0fe137
--- /dev/null
+++ b/internal/fichas/history.go
@@ -0,0 +1,168 @@
+package fichas
+
+// History on the card (level-up §5.5) and the value window that bounds
+// it (Q11: 90 days). Past the window an event keeps who, when and which
+// fields; its before and after values are erased.
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "log/slog"
+ "strings"
+ "time"
+
+ "amadan.net/oficina/fichas/internal/fichas/seal"
+ "gorm.io/gorm"
+)
+
+// HistoryItem is one change to a card, as History lists it.
+type HistoryItem struct {
+ EventID int64
+ When time.Time
+ Who string // the person's address; "" for Fichas itself
+ Reason string // Fichas' reason, when Fichas acted
+ Kind string // created, updated, entry_added, deleted
+ Undo bool // an Undo's own event
+ Redo bool
+ // Held is true inside the value window: the values are still kept,
+ // so each field shows before and after, and can be restored.
+ Held bool
+ Fields []HistoryField
+}
+
+// HistoryField is one field one change touched.
+type HistoryField struct {
+ Key, Label, Kind string
+ Before, After string
+ Gone bool // the field no longer exists
+}
+
+// historyLimit bounds one History page: a card edited daily for years
+// still draws quickly, and the oldest changes are past the window anyway.
+const historyLimit = 200
+
+// CardHistory is a card's changes, newest first.
+func CardHistory(ctx context.Context, db *gorm.DB, s *seal.Sealer, cardID int64) ([]HistoryItem, error) {
+ g := db.WithContext(ctx)
+ var card Card
+ if err := g.Where("id = ? AND gone = ?", cardID, false).First(&card).Error; err != nil {
+ return nil, err
+ }
+ var defs []FieldDef
+ if err := g.Where("card_type_id = ?", card.CardTypeID).Find(&defs).Error; err != nil {
+ return nil, fmt.Errorf("fichas: loading field definitions: %w", err)
+ }
+ byID := map[int64]FieldDef{}
+ labels := map[int64]string{}
+ for _, d := range defs {
+ byID[d.ID] = d
+ if labels[d.ID], _ = openLabel(s, d.SealedLabel); labels[d.ID] == "" {
+ labels[d.ID] = d.Key
+ }
+ }
+ var events []Event
+ if err := g.Where("object_kind = ? AND object_id = ?", ObjectCard, cardID).
+ Order("id desc").Limit(historyLimit).Find(&events).Error; err != nil {
+ return nil, fmt.Errorf("fichas: reading card %d's history: %w", cardID, err)
+ }
+ people := map[int64]string{}
+ out := make([]HistoryItem, 0, len(events))
+ for _, e := range events {
+ item := HistoryItem{EventID: e.ID, When: e.CreatedAt, Kind: e.Kind, Reason: e.ActorReason}
+ if e.ActorID != nil {
+ if _, ok := people[*e.ActorID]; !ok {
+ people[*e.ActorID], _ = memberAddress(g, s, *e.ActorID)
+ }
+ item.Who = people[*e.ActorID]
+ }
+ p, held := readPayload(s, e)
+ item.Held = held && time.Since(e.CreatedAt) <= valueWindow
+ item.Undo, item.Redo = p.Undo, p.Redo
+ item.Fields = historyFields(e, p, item.Held, byID, labels)
+ out = append(out, item)
+ }
+ return out, nil
+}
+
+// historyFields names the fields an event touched, with their values
+// when they are still held.
+func historyFields(e Event, p editPayload, held bool, byID map[int64]FieldDef, labels map[int64]string) []HistoryField {
+ var ids []int64
+ _ = json.Unmarshal([]byte(e.ChangedFields), &ids)
+ values := map[string]change{}
+ if held {
+ for _, c := range p.Changes {
+ values[c.Field] = c
+ }
+ }
+ var out []HistoryField
+ for _, id := range ids {
+ d, ok := byID[id]
+ if !ok {
+ out = append(out, HistoryField{Label: "A removed field", Gone: true})
+ continue
+ }
+ f := HistoryField{Key: d.Key, Label: labels[id], Kind: d.Kind}
+ if c, ok := values[d.Key]; ok {
+ f.Before, f.After = c.Before, c.After
+ }
+ out = append(out, f)
+ }
+ return out
+}
+
+// ErasePayloads empties the before and after values of every event
+// older than the value window, and stamps when. It logs no event: it
+// removes only what nobody can still reach (level-up §9's named
+// exemption), and an event would have to name Fichas as the actor.
+func ErasePayloads(ctx context.Context, db *gorm.DB, now time.Time) (int64, error) {
+ res := db.WithContext(ctx).Model(&Event{}).
+ Where("created_at < ? AND payload_sealed IS NOT NULL", now.Add(-valueWindow)).
+ Updates(map[string]any{"payload_sealed": nil, "payload_erased_at": now})
+ if res.Error != nil {
+ return 0, fmt.Errorf("fichas: erasing payloads past the value window: %w", res.Error)
+ }
+ return res.RowsAffected, nil
+}
+
+// sweepEvery is how often a running Fichas sweeps. The window is days
+// long, so an hour's lag past it costs nothing.
+const sweepEvery = time.Hour
+
+// Sweep erases payloads past the window now and then every hour, until
+// ctx ends. It never stops the app: a failed sweep is logged and tried
+// again on the next tick.
+func Sweep(ctx context.Context, db *gorm.DB, logger *slog.Logger) {
+ run := func() {
+ n, err := ErasePayloads(ctx, db, time.Now())
+ if err != nil {
+ logger.Error("value window sweep", "err", err)
+ return
+ }
+ if n > 0 {
+ logger.Info("value window sweep", "erased", n)
+ }
+ }
+ run()
+ t := time.NewTicker(sweepEvery)
+ defer t.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-t.C:
+ run()
+ }
+ }
+}
+
+// personName is how a person is shown until rosters carry names (§6.5):
+// the part of their address before the @.
+func personName(address string) string {
+ if address == "" {
+ return "Fichas"
+ }
+ name, _, _ := strings.Cut(address, "@")
+ return name
+}
diff --git a/internal/fichas/history_test.go b/internal/fichas/history_test.go
new file mode 100644
index 0000000..d1ee43a
--- /dev/null
+++ b/internal/fichas/history_test.go
@@ -0,0 +1,64 @@
+package fichas
+
+import (
+ "testing"
+ "time"
+)
+
+// The value window (Q11). Mutation, 2026-11-17: dropping the created_at
+// bound from ErasePayloads erased the fresh payload too and failed
+// "a payload inside the window".
+func TestTheSweepErasesOnlyPayloadsPastTheWindow(t *testing.T) {
+ g, s := seeded(t)
+ card := newCustomer(t, g, s, map[string]string{FieldName: "Cnoc", FieldStage: "Lead"})
+ old, _ := SetField(ctx(), g, s, card.ID, Person(memberID(t, g, s, "ana@example.com")), FieldStage, "Won", "Lead")
+ fresh, _ := SetField(ctx(), g, s, card.ID, Person(memberID(t, g, s, "ana@example.com")), FieldEmail, "a@b.example", "")
+ g.Model(&Event{}).Where("id = ?", old.EventID).Update("created_at", time.Now().Add(-valueWindow-time.Minute))
+ events := countEvents(g)
+
+ if _, err := ErasePayloads(ctx(), g, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ var o, f Event
+ g.First(&o, old.EventID)
+ g.First(&f, fresh.EventID)
+ if o.PayloadSealed != nil || o.PayloadErasedAt == nil {
+ t.Fatal("a payload past the window was kept")
+ }
+ if f.PayloadSealed == nil || f.PayloadErasedAt != nil {
+ t.Fatal("a payload inside the window was erased")
+ }
+ if countEvents(g) != events {
+ t.Fatal("the sweep logged an event; it is a named exemption")
+ }
+}
+
+// History (§5.5): inside the window each change shows before and after;
+// past it, who, when and which fields only.
+func TestHistoryShowsValuesOnlyInsideTheWindow(t *testing.T) {
+ g, s := seeded(t)
+ ana := memberID(t, g, s, "ana@example.com")
+ card := newCustomer(t, g, s, map[string]string{FieldName: "Cnoc", FieldStage: "Lead"})
+ old, _ := SetField(ctx(), g, s, card.ID, Person(ana), FieldStage, "Won", "Lead")
+ 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.Minute))
+ ErasePayloads(ctx(), g, time.Now())
+
+ items, err := CardHistory(ctx(), g, s, card.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(items) != 3 {
+ t.Fatalf("%d history items; want created and two edits", len(items))
+ }
+ newest, past := items[0], items[1]
+ if !newest.Held || newest.Fields[0].Label != "Email" || newest.Fields[0].After != "a@b.example" || newest.Who != "ana@example.com" {
+ t.Fatalf("the newest change: %+v", newest)
+ }
+ if past.Held || past.Fields[0].Label != "Stage" || past.Fields[0].Before != "" || past.Fields[0].After != "" {
+ t.Fatalf("a change past the window shows values: %+v", past)
+ }
+ if _, err := CardHistory(ctx(), g, s, 99999); err == nil {
+ t.Fatal("a card that does not exist has a history")
+ }
+}