| 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 |
| +} |